Farhan Naufal
Farhan Naufal

Reputation: 17

loop and choice() function in Python

I'm a novice programmer and I tried to write code for a challenge in my book with a loop that takes numbers and/or letters randomly to announce the winner of the lottery.

I'm trying to write code that:

from random import choice #Import choice() function from the random module

lottery_1 = (1,2,3,4,5,6,7,8,9,'a','b','c','d','e')
lottery_winner = []

for i in range(4): #Takes 4 random numbers and/or letters
    random = choice(lottery_1)

    if random not in lottery_winner:
        lottery_winner.append(pulled_number)

print('$1M Winner\n')
print(lottery_winner)

sometimes it only picks 2 characters result:

$1M Winner

[1, 'e']
>>>

Why did it happen? What can I change to make it picks 4 characters?

Upvotes: 1

Views: 1344

Answers (3)

CrazyChucky
CrazyChucky

Reputation: 3518

It is, in fact, picking four characters. However, when one of the picked characters is already in lottery_winner, it's not added. In such a case, you end up with fewer than four total results.

lenik's answer is the most practical solution. However, if you're curious about the logic of how you'd go about it using the choice function, keep in mind that you need to either choose again when a repeat comes out of the hat, or you need to eliminate options from the hat as you go.

Option #1, try again whenever a winner is a repeat:

for i in range(4):
    new_winner = False # Initially, we have not found a new winner yet.
    while not new_winner: # Repeat the following as long as new_winner is false:
        random = choice(lottery_1)

        if random not in lottery_winner:
            lottery_winner.append(pulled_number)
            new_winner = True # We're done! The while loop won't run again.
                              # (The for loop will keep going, of course.)

Option #2, remove winners from the list each time, so they can't get picked again:

for i in range(4):
    random = choice(lottery_1)

    lottery_winner.append(pulled_number)
    lottery_1.remove(pulled_number) # Now it can't get chosen again.

Note that remove() removes the first instance of the specified value, which might not do what you want in cases where the values aren't unique.

Upvotes: 2

Keith
Keith

Reputation: 77

import random

lottery_1 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e')

'''Instead of using the choice method which can randomly grab the same value,
i suggest that you use the sample method which ensures that you only get randomly unique values'''

# The k value represents the number of items that you want to get
lottery_winner = random.sample(lottery_1, k=4)

print('$1M Winner\n')
print(lottery_winner)

Upvotes: 0

lenik
lenik

Reputation: 23508

This works for me:

>>> import random
>>> lottery_1 = (1,2,3,4,5,6,7,8,9,'a','b','c','d','e')
>>> random.sample(lottery_1, 4)
[1, 7, 'a', 'e']
>>> 

Upvotes: 3

Related Questions