def initDeck(n):
cards = []
for i in range(n):
cards.append(i + 1)
return cards
def cutDeck(deck):
decklength = len(deck)
if((decklength % 2) != 0): #odds
numTop = decklength//2
numBot = numTop + 1
else: #evens
numTop = decklength//2
numBot = decklength//2
bottomDeck = []
bottomDeck = deck[:(numBot)]
topDeck = []
topDeck = deck[(numBot):]
return topDeck, bottomDeck
def shuffle(topDeck, bottomDeck):
newDeck = []
numcards = (len(topDeck)) + (len(bottomDeck))
for g in range(numcards):
newDeck.append(bottomDeck[g])
newDeck.append(topDeck[g])
return newDeck
#--------MAIN--------
n = int(input("How many cards do you want to shuffle? "))
numshuffles = int(input("How many times would you like to shuffle the deck? "))
deck = initDeck(n)
topDeck,bottomDeck = cutDeck(deck)
print(bottomDeck, '\n', topDeck, sep="")
while(numshuffles > 0):
shuffledDeck = shuffle(topDeck, bottomDeck)
numshuffles += -1
print(shuffledDeck)
该程序需要你想要多少张牌,你想要洗牌多少次,然后轻轻地洗牌。问题是当我尝试运行它时,它需要我的两个输入,然后输出两个错误。
Traceback (most recent call last):
File "C:\etc", line 51, in <module>
shuffledDeck = shuffle(topDeck, bottomDeck)
File "C:\etc", line 35, in shuffle
newDeck.append(bottomDeck[g])
IndexError: list index out of range
我不完全确定错误是什么,因为它看起来很好并且对我有意义。任何帮助将非常感谢,因为这将在上午8点到期!
答案 0 :(得分:0)
numcards = (len(topDeck)) + (len(bottomDeck))
for g in range(numcards):
newDeck.append(bottomDeck[g])
你的g达到topDeck和bottomDeck的长度之和,因此变得大于len(bottomDeck)。
答案 1 :(得分:0)
在
numcards = (len(topDeck)) + (len(bottomDeck))
for g in range(numcards):
newDeck.append(bottomDeck[g])
newDeck.append(topDeck[g])
您要将bottomDeck[g]
和topDeck[g]
追加到newDeck
和g
,范围从0
到len(bottomDeck) + len (topDeck)
。表示某点g
变得大于len(topDeck)
或len(bottomDeck)
。
修改强> 你可以像这样解决它。
for g in range(len(topDeck)):
newDeck.append(bottomDeck[g])
newDeck.append(topDeck[g])
# if total cards are odd, one card will be left in bottomDeck
if(len(topDeck) != len(bottomDeck)):
newDeck.append(bottomDeck[-1])
你也应该在洗牌后再次切割牌组
while(numshuffles > 0):
shuffledDeck = shuffle(topDeck, bottomDeck)
numshuffles += -1
print(shuffledDeck)
topDeck,bottomDeck = cutDeck(shuffledDeck)