user17737438
user17737438

Reputation:

I feel like the results that my code is showing for lottery is not right

I believe there is a logical error with my code. I'm trying to generate a winning random lottery ticket that will match another random lottery ticket as well. My program is running but it's hard to believe that it only takes around 20 to 50 "tries" for my ticket to match the other one. Is my code legit?

Compared to this guy's work it reaches thousands of tries for both tickets to match.

from random import randint, choice

winning_ticket = []
tries = 0
possibilities = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "a", "b", "c", "d", "e"]
my_ticket = []

#This creates the winning ticket 
while len(winning_ticket) < 4:
    random_char = choice(possibilities)
    if random_char not in winning_ticket:
        winning_ticket.append(random_char)

print(f"This is the winning ticket: {winning_ticket}")

#This creates my ticket that needs to match the winning ticket 
while len(my_ticket) < 4:
    my_char = choice(possibilities)
    tries += 1
    if my_char in winning_ticket and my_char not in my_ticket:
        my_ticket.append(my_char)

print(f"This is my ticket: {my_ticket}")
print(f"The number of tries: {tries}")

Upvotes: 0

Views: 63

Answers (1)

BrokenBenchmark
BrokenBenchmark

Reputation: 19253

There is a logical difference between your code and the code in the Pastebin. The difference is extremely subtle, so please post a follow-up if any of the following is unclear.

The Pastebin code generates a combination of four elements from the possibilities list as my_ticket. It then checks if this combination is the same as that in the winning_ticket. There are (15 choose 4) combinations, so the expected number of iterations is (15 choose 4) = 1365. This seems to make sense in light of your observation that this code can run for thousands of iterations.

Your code, on the other hand, generates one character at a time with the ability to peek at what's on the winning ticket. It adds an element to my_ticket only if it's in the winning ticket and it hasn't been added already. This leads to much fewer iterations, in expectation 15/4 + 15/3 + 15/2 + 15 = 31.25 iterations. This checks out with your observation that your code terminates in 20-50 iterations.

Here's what the second while loop should look like:

# Transform the ticket lists to sets,
# to see if the elements in my_ticket and winning_ticket
# are the same ignoring order.
while set(my_ticket) != set(winning_ticket):
    my_ticket = []
    while len(my_ticket) < 4:
        my_char = choice(possibilities)

        if my_char not in my_ticket:
            my_ticket.append(my_char)
    tries += 1

Upvotes: 0

Related Questions