web-dev-qa-db-fra.com

Python: IndexError: liste des index hors limites

Je pense que mon programme est terminé, mais ... cela ne fonctionne pas. J'essaie d'écrire un programme qui simule un jeu de loterie, mais lorsque j'essaie de vérifier les suppositions de l'utilisateur par rapport au nombre de suppositions sur le ticket, j'obtiens une erreur qui me dit que "l'index de la liste est hors de portée". Je pense que cela a quelque chose à voir avec la partie du code où j'attribue les chiffres aléatoires à "a", "b", "c", etc. Mais je ne suis pas sûr.

Voici le code dans son intégralité:

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()

Et voici l'erreur que j'obtiens:

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

Comme le note l'erreur, le problème est dans la ligne:

if guess[i] == winning_numbers[i]

L'erreur est que vos index de liste sont hors de portée - c'est-à-dire que vous essayez de faire référence à un index qui n'existe même pas. Sans déboguer complètement votre code, je vérifierais la ligne où vous ajoutez des suppositions en fonction de l'entrée:

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)

La taille du nombre de suppositions que vous donnez à votre utilisateur est basée sur

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

Donc, si le nombre de billets qu'ils veulent est inférieur à 5, alors votre code ici

for i in range(5):

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

return match

générera une erreur car il n'y a tout simplement pas autant d'éléments dans la liste guess.

10
simchona

Voici votre code. Je suppose que vous utilisez python 3 basé sur votre utilisation de print() et input():

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

Je pense que vous voulez mettre le roulement de l'aléatoire a, b, c, etc dans la boucle:

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)

Sinon, a sera généré juste ne fois, et s'il est dans winning_numbers déjà, il ne sera pas ajouté. Puisque la génération de a est extérieur le while (dans votre code), si a est déjà dans winning_numbers alors tant pis, il ne sera pas relancé, et vous aurez un numéro gagnant en moins.

Cela pourrait être la cause de votre erreur dans if guess[i] == winning_numbers[i]. (Votre winning_numbers n'est pas toujours de longueur 5).

1
mathematical.coffee