web-dev-qa-db-ja.com

Python:IndexError:インデックスが範囲外です

私は自分のプログラムを完成させたと思いますが、...うまくいきません。宝くじゲームをシミュレートするプログラムを作成しようとしていますが、チケットの推測数に対してユーザーの推測を確認しようとすると、「リストインデックスが範囲外です」というエラーが表示されます。ランダムな数字を「a」、「b」、「c」などに割り当てるコードの部分と関係があると思いますが、よくわかりません。

コード全体は次のとおりです。

import random

def main():
random.seed()

#Prompts the user to enter the number of tickets they wish to play.
tickets = int(input("How many lottery tickets do you want?\n"))

#Creates the dictionaries "winning_numbers" and "guess." Also creates the variable "winnings" for total amount of money won.
winning_numbers = []
guess = []
winnings = 0

#Generates the winning lotto numbers.
for i in range(tickets):
    del winning_numbers[:]

    a = random.randint(1,30)
    while not (a in winning_numbers):
        winning_numbers.append(a)

    b = random.randint(1,30)
    while not (b in winning_numbers):
        winning_numbers.append(b)

    c = random.randint(1,30)
    while not (c in winning_numbers):
        winning_numbers.append(c)

    d = random.randint(1,30)
    while not (d in winning_numbers):
        winning_numbers.append(d)

    e = random.randint(1,30)
    while not (e in winning_numbers):
        winning_numbers.append(e)

    print(winning_numbers)
    getguess(guess, tickets)
    nummatches = checkmatch(winning_numbers, guess)

    print("Ticket #"+str(i+1)+": The winning combination was",winning_numbers,".You matched",nummatches,"number(s).\n")

    if nummatches == 0 or nummatches == 1:
        winnings = winnings + 0
    Elif nummatches == 2:
        winnings = winnings + 10
    Elif nummatches == 3:
        winnings = winnings + 500
    Elif nummatches == 4:
        winnings = winnings + 20000
    Elif nummatches == 5:
        winnings = winnings + 1000000

print("You won a total of",winnings,"with",tickets,"tickets.\n")

#Gets the guess from the user.
def getguess(guess, tickets):
del guess[:]

for i in range(tickets):
    bubble = input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split(" ")
    guess.append(bubble)
print(bubble)

#Checks the user's guesses with the winning numbers.
def checkmatch(winning_numbers, guess):
match = 0
for i in range(5):

    if guess[i] == winning_numbers[i]:
        match = match+1

return match

main()

そして、ここに私が得るエラーがあります:

Traceback (most recent call last):
  File "C:\Users\Ryan\Downloads\Program # 2\Program # 2\lottery.py", line 85, in <module>
    main()
  File "C:\Users\Ryan\Downloads\Program # 2\Program # 2\lottery.py", line 45, in main
   nummatches = checkmatch(winning_numbers, guess)
File "C:\Users\Ryan\Downloads\Program # 2\Program # 2\lottery.py", line 79, in checkmatch
    if guess[i] == winning_numbers[i]:
IndexError: list index out of range
9
Ryan W

エラーが指摘するように、問題は次の行にあります。

if guess[i] == winning_numbers[i]

エラーは、リストのインデックスが範囲外であることです。つまり、存在しないインデックスを参照しようとしています。コードを完全にデバッグせずに、入力に基づいて推測を追加する行を確認します。

for i in range(tickets):
    bubble = input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split(" ")
    guess.append(bubble)
print(bubble)

ユーザーに与えている推測のサイズは、

# Prompts the user to enter the number of tickets they wish to play.
tickets = int(input("How many lottery tickets do you want?\n"))

したがって、必要なチケットの数が5未満の場合、ここのコード

for i in range(5):

if guess[i] == winning_numbers[i]:
    match = match+1

return match

guessリストにはそれほど多くの要素がないため、エラーがスローされます。

10
simchona

これがあなたのコードです。 print()input()の使用に基づいてpython 3を使用していると仮定しています。

import random

def main():
    #random.seed() --> don't need random.seed()

    #Prompts the user to enter the number of tickets they wish to play.

    #python 3 version:
    tickets = int(input("How many lottery tickets do you want?\n"))

    #Creates the dictionaries "winning_numbers" and "guess." Also creates the variable "winnings" for total amount of money won.
    winning_numbers = []
    winnings = 0

    #Generates the winning lotto numbers.
    for i in range(tickets * 5):
        #del winning_numbers[:] what is this line for?
        randNum = random.randint(1,30)
        while randNum in winning_numbers:    
            randNum = random.randint(1,30)
        winning_numbers.append(randNum)

    print(winning_numbers)
    guess = getguess(tickets)
    nummatches = checkmatch(winning_numbers, guess)

    print("Ticket #"+str(i+1)+": The winning combination was",winning_numbers,".You matched",nummatches,"number(s).\n")

    winningRanks = [0, 0, 10, 500, 20000, 1000000]

    winnings = sum(winningRanks[:nummatches + 1])

    print("You won a total of",winnings,"with",tickets,"tickets.\n")


#Gets the guess from the user.
def getguess(tickets):
    guess = []
    for i in range(tickets):
        bubble = [int(i) for i in input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split()]
        guess.extend(bubble)
        print(bubble)
    return guess

#Checks the user's guesses with the winning numbers.
def checkmatch(winning_numbers, guess):
    match = 0
    for i in range(5):
        if guess[i] == winning_numbers[i]:
            match += 1
    return match

main()
2
Joel Cornett

あなたはランダムなa、b、cなどのローリングを置くことを意味すると思うwithinループ:

a = None # initialise
while not (a in winning_numbers):
    # keep rolling an a until you get one not in winning_numbers
    a = random.randint(1,30)
    winning_numbers.append(a)

それ以外の場合、aonceだけで生成され、既にwinning_numbersにある場合は追加されません。 aの生成は外部while(コード内)であるため、aが既にwinning_numbersにある場合は、あまりにも悪いです、再ロールされず、勝ち番号が1つ少なくなります。

それがif guess[i] == winning_numbers[i]のエラーの原因になる可能性があります。 (winning_numbersの長さは常に5とは限りません)。

1