2014-11-21 59 views
-1
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) 

該程序需要您需要多少張卡片,您想要洗牌多少次,然後再洗牌。問題是當我嘗試運行它時,它需要我的兩個輸入,然後輸出兩個錯誤。Python3:列表索引超出範圍

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

numcards = (len(topDeck)) + (len(bottomDeck)) 
for g in range(numcards): 
    newDeck.append(bottomDeck[g]) 
    newDeck.append(topDeck[g]) 

要附加bottomDeck[g]topDeck[g]newDeckg範圍從0len(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) 
+0

感謝您的迴應!我該如何解決這個問題(抱歉,我的想法是間隔)?我嘗試在'(len(topDeck))+(len(bottomDeck))之後加上' - 1',並且這樣做不起作用,因此我試圖將它添加到'range(numcards - 1)'中,工作。謝謝! – Iounno 2014-11-21 07:58:09

+0

感謝一堆爲修復!現在我遇到了一個問題,每當我洗牌時,它都會輸出相同的內容。問題是我的'newDeck []'在函數'shuffle()'中?當我將它移動到MAIN時,它不斷擴展列表。我怎樣才能解決這個問題?感謝一羣幫助btw!如果可以的話,我會讓你滿意的。 – Iounno 2014-11-21 08:17:21

+0

因爲你的'topDeck'和'bottomDeck'沒有改變。您可以從'shuffledDeck'創建新的'topDeck'和'bottomDeck',但它也會在'len(topDeck)'次後重複。你也應該使用隨機模塊來洗牌。如果您無法註冊,您可以將其標記爲已接受,因爲您發佈的問題已解決。 – 2014-11-21 08:27:30

0
numcards = (len(topDeck)) + (len(bottomDeck)) 
    for g in range(numcards): 
     newDeck.append(bottomDeck[g]) 

你的g增加到topDeck和bottomDeck的長度之和,因此變得比len(bottomDeck)大。

+0

感謝您的答覆!我該如何解決這個問題(抱歉,我的想法是間隔)?我嘗試在'(len(topDeck))+(len(bottomDeck))之後加上' - 1',並且這樣做不起作用,因此我試圖將它添加到'range(numcards - 1)'中,工作。謝謝! – Iounno 2014-11-21 07:59:41