Search code examples
pythonloopsenumerate

Index of number of loops; enumerate()


I'm just going through the exercise in my python book and I'm struggling with the finish.

In the beginning, I was supposed to make a list with a series of 10 numbers and five letters. Randomly select 4 elements and print the message about the winning ticket.

from random import choice, branding

numbers_and_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                   '1', '2', '3', '4', '5']

print("If you've got those 4 numbers or letters you've won!!!")
for i in range(1, 5):
    print(choice(numbers_and_letters))

Then I suppose to make a loop to see how hard it might be to win the kind of lottery I just created. I need to make a list called my_ticket then write a loop that keeps pulling numbers until the ticket wins. Print a message reporting how many times the loop had to tun to give a winning ticket.

from random import choice
from itertools import count

numbers_and_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                       '1', '2', '3', '4', '5']
winning_numbers = []
my_ticket = ['a','1', '5', 'j']

for i in count():   #infinite loop
    for i in range(1, 5):   # four elements from the numbers_and_letters list
        i = choice(numbers_and_letters)
        winning_numbers.append(i)
    print(winning_numbers)
    
    if sorted(winning_numbers) != sorted(my_ticket):
        winning_numbers.clear()
    elif sorted(winning_numbers) == sorted(my_ticket):
        print('The numbers are identical')
        break

The only thing I need to do is to count how many times the code integrated through the loop. I know I need to use enumerate(), however, I'm not sure how to apply it to my code.


Solution

  • You are already counting the number of iterations it takes you to find a match with your loop on count(). But you're overwriting the value you get from that loop with other values later on, since you are reusing the variable name i several times.

    Try using different names for the variables in these three lines, rather than reusing i:

    for draw_count in count():
        for character_count in range(1, 5):
            character = choice(numbers_and_letters)
    

    Now you can use draw_count later on. You probably want to print out draw_count + 1, since the itertools.count iterator starts at zero by default.