#!/usr/bin/python """ Exercise 13, page 380 of Zelle's "Intro Python" Jim Mahoney, Nov 6 2006 This one uses the playing_card.py to define the card itself. """ from playing_card import Playing_Card def compare(card1, card2): """ sort cards first by rank, then by suit """ if card1.getRank() != card2.getRank(): return cmp(card1.getRank(), card2.getRank()) else: return cmp(card1.getSuit(), card2,getSuit()) class Card_Stack: """ A stack of cards. """ def __init__( self, string='', filename='' ): """ Create a stack from a string or (if no string is given) a file, or (if neither is given), return an empty stack. Each card is given by a rank and suit separated by a space, i.e. '1 s' for the ace of spades. The cards in the input may be separated by commas or newlines. """ if string: lines = string.split("/n") elif filename: lines = open(filename,'r').readlines() else: lines = [] self.cards = [] for line in lines: # e.g. line = '1 s, 2 d, 3 c' for rank_suit in line.split(','): # e.g. rank_suit = '1 s' rank_suit_tuple = rank_suit.split() # e.g. ('1', 's') if len(rank_suit_tuple)==2: (rank, suit) = rank_suit.split() # e.g. rank='1', suit='s' self.cards.append( Playing_Card(int(rank), suit) ) def __str__(self): card_strings = [] for card in self.cards: card_strings.append(str(card)) return ', '.join(card_strings) def sort(self): self.cards.sort(compare) print Card_Stack('1 s, 2 d, 3 c') a = Card_Stack(filename='cards.txt') print a a.sort() print a