首页 > 其他 > 详细

Add, remove, shuffle and sort

时间:2014-10-06 18:31:40      阅读:276      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/ryansunyu/p/4008476.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!