我目前正在尝试在添加卡片时将选择排序实施到一系列卡片中。这是我当前的代码。我了解选择排序应该如何工作,并且只是在寻找有关如何开始在我的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)
如果您想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
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。