dimanche 18 février 2018

Python random generator odds different to calculated odds

I have an exercise to simulate a lottery (4 balls drawn from 45). I randomly generated a list of four numbers then iteratively compare it to further randomly generated sets of 4. This seems to work though the number of attempts to get a match is generally in the 10's-100's of thousands yet the odds of matching 4/45 should be closer to 1 in 5000. As I compare my lists as sets, the order shouldn't matter so I am stumped as to why the odds are so low compared to the "theoretical". I have run it dozens of times and always with the same output. I am new to Python so am guessing there is a basic error here, but any insight would be helpful.

import random

def comparator(x,y):
    counter = 1
    while set(x) != set(y):
    y = random.sample(range(1,46),4)
    if set(x) == set(y):
        print x,y
        return counter
    else:
        counter +=1


#call the function 5 times 
for i in range(1,6):
    selection = random.sample(range(1,46),4)
    draw = []
    output = comparator(selection,draw)
    print "Iteration %d = %d attempts" %(i,output)




Aucun commentaire:

Enregistrer un commentaire