Home > Enterprise >  How can I create a program that simulates a lottery in Python?
How can I create a program that simulates a lottery in Python?

Time:06-16

I need to write a program that simulates a lottery. The program should have a list of seven numbers that represent a lottery ticket. It should then generate seven random numbers. After comparing the numbers the proram should output a prize for three matching numbers, four matching numbers, etc.

I'm not sure how to do the last bit where I need to check if there are three, four, five, etc matching numbers and output a prize depending on how many numbers are matching.

CodePudding user response:

This can be done with sets:

import random
winning_numbers = {random.randint(0, 99) for _ in range(8)}
ticket_numbers = {1, 2, 3, 8, 9, 10, 11}
matches = winning_numbers & ticket_numbers

prizes = {
    0: 0,
    1: 1,
    2: 10,
    3: 100,
    4: 1_000,
    5: 10_000,
    6: 100_000,
    7: 1_000_000
}

print(matches)
print(prizes[len(matches)])

output:

{1, 2, 3}
100

CodePudding user response:

Program:

from random import randint

win_ticket = [randint(0, 10) for _ in range(7)]
received_ticket = [randint(0, 10) for _ in range(7)]
result = list()

for i in range(len(win_ticket)):
    if i in received_ticket:
        result.append(i)

print(f'Winner ticket: {win_ticket}')
print(f'Received ticket: {received_ticket}')
print(f'Amount win nums: {len(result)}\nWin nums: {result}')

Output:

Winner ticket: [1, 4, 0, 5, 2, 1, 10]
Received ticket: [4, 0, 9, 8, 5, 10, 3]
Amount win nums: 4
Win nums: [0, 3, 4, 5]

CodePudding user response:

Try this:

import random

numbers = list(range(1, 20)) # Numbers from 1 to 19

ticket = list(sorted(random.sample(numbers, 7)))

print('Your ticket is', ticket)

lottery = list(sorted(random.sample(numbers, 7)))

print('The winning numbers are', lottery)

matching = []
for i in ticket:
    if i in lottery:
        matching.append(i)


print(len(matching), 'number(s) match ('   str(matching)   ')')

Output:

Your ticket is [5, 6, 7, 12, 13, 15, 17]
The winning numbers are [1, 3, 6, 7, 8, 15, 19]
3 number(s) match ([5, 6, 15])

CodePudding user response:

Do your homework yourself

seq = 4727523
win_seq = 4729897
def comp(input_seq, checklen):
    #compare 3:
    print(str(input_seq)[0:checklen])
    if str(input_seq)[0:checklen] in str(win_seq):
        print("win {}".format(checklen))
        if checklen < 7:
            checklen  = 1
            comp(input_seq, checklen)
                    
comp(seq, 3)
  • Related