开发者社区> 问答> 正文

卡片中的选择排序

我目前正在尝试在添加卡片时将选择排序实施到一系列卡片中。这是我当前的代码。我了解选择排序应该如何工作,并且只是在寻找有关如何开始在我的add函数中实现选择的建议。

手班 newHand(object)类:

def __init__(self, label = ""):
    """
    create an empty collection of cards with the given label
    """
    self.label = label
    self.cards = []


def add(self, card):
    """
    # Implements selection sort
    pre: card is a Card
    post: appended the card to the hand and sorts the deck
    """

    self.cards.append(card)


def sort(self):
    """
    post: arrange the cards in decending order
    """
    cards0 = self.cards
    cards1 = []
    while len(cards0) > 0:
        card = max(cards0)
        cards0.remove(card)
        cards1.append(card)
    self.cards = cards1


def dump(self):
    """
    post: outputs the contents in the hand
    """

    print(self.label + "'s Cards: ")
    for card in self.cards:
        print("\t", card)

展开
收起
祖安文状元 2020-02-21 14:10:44 335 0
1 条回答
写回答
取消 提交回答
  • 如果您想selection sort在您的add方法中实现卡片,则可以执行以下操作,

    def add(self, card):
        """
        # Implements selection sort
        pre: card is a Card
        post: appended the card to the hand and sorts the deck
        """
    
        self.cards.append(card)
    
        cards = self.cards
        for i in range(len(cards) - 1):
            min = i
            for j in range(i + 1, len(cards)):
                if cards[j] < cards[min]:
                    min = j
            if i != min:
                temp = cards[i]
                cards[i] = cards[min]
                cards[min] = temp
    
    2020-02-21 14:10:55
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载