我已经概述了代码中我遇到问题的地方。我是一个python newb,需要一些帮助。我想做的是单手牌,然后按照套装和排名选择排序。我希望为每张卡分配自己的值,然后比较卡片,最终完成排序。目前,当我运行代码时,我收到一个错误,指出我的字符串索引超出范围。我假设这是因为我没有正确定义card1 card2指数,但我不知道如何解决它们。提前谢谢!
编辑:对于card1和card2我希望能够根据他们的等级对它们进行比较,如果我得到一个正数,我知道card1大于card2,如果为负,我知道card1小于card2。然后我可以在find_largest中使用它来比较13张卡片。
import random
def shuffle_deck():
result = []
for suit in ['H', 'C', 'D', 'S']:
for value in ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']:
result += [value + suit];
random.shuffle(result)
return result
def deal_hand(n, deck):
hand = []
for i in range(n):
card = deck.pop()
hand += [card]
return hand
# This is where the trouble I'm having begins as I'm not sure what cards to compare
def compare(card1,card2):
value = 'A23456789TJQK'
suit = 'HCDS'
card1 = value.find(card1[0] [0]) + ((suit.find(card1[0][1]))*20)
card2 = value.find(card2[1] [0]) + ((suit.find(card2[1][1]))*20)
return(card1 - card2)
def find_largest(hand, n):
largestIdx = 0
for i in range(1, n):
# I am also not certain what should be compared in this part. I know it should be the
#current hand compared to the position of the largest card currently.
if compare(hand [i], hand[largestIdx]) > 0:
largestIdx = i
return largestIdx
def selection_sort(hand):
for idx in range(len(hand)-1, 0, -1):
largestIdx = find_largest(hand, idx +1)
hand[idx], hand[largestIdx] = hand[largestIdx], hand[idx]
print(hand)
编辑:
selection_sort(deal_hand(13, shuffle_deck()))
Traceback (most recent call last):
File "C:\Program Files\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
File "C:\Program Files\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 92, in selection_sort
File "C:\Program Files\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 79, in find_largest
File "C:\Program Files\Wing IDE 101 5.0\src\debug\tserver\_sandbox.py", line 64, in compare
builtins.IndexError: string index out of range
答案 0 :(得分:1)
如果我正确关注您的代码,变量card1
和card2
应包含一些字符串,如'AC'
或'5D'
。看起来你想分别看一下套装和号码(value.find(card1[0] [0]) + ((suit.find(card1[0][1]))*20)
)。你这里只需要一个索引,而不是两个。看看下面的例子:
>>> a = 'AC'
>>> a[0]
'A'
>>> a[1]
'C'
>>> a[0][0]
'A'
>>> a[0][1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
字符串'C'
只有一个元素,因此当您执行card1[0][1]
时会出现索引错误。您想用
card1 = value.find(card1[0]) + ((suit.find(card1[1]))*20)
card2 = value.find(card2[0]) + ((suit.find(card2[1]))*20)
那应该摆脱你的IndexError
。