首页 > 代码库 > Add, remove, shuffle and sort
Add, remove, shuffle and sort
To deal cards, we would like a method that removes a card from the deck and returns it. The list method pop provides a convenient way to do that. Since pop removes the last card in the list, we are in effect dealing from the bottom of the deck. To add a card, we can use the list method append. As another example, we can write a Deck method named shuffle using the function shuffle from the random module.
def pop_card(self): return self.cards.pop() def add_card(self,card): return self.cards.append(card) def shuffle(self): random.shuffle(self.cards) def sort(self): for i in range(len(self.cards)): for j in range(i+1,len(self.cards)): if(self.cards[i].cmp(self.cards[j])>0): self.cards[i],self.cards[j] = self.cards[j],self.cards[i]
A method like this that uses another function without doing much real work is sometimes called a veneer, the metaphor comes from woodworking, where it is common to glue a thin layer of good quality wood to the surface of a cheaper piece of wood.
from Thinking in Python
Add, remove, shuffle and sort