I have a simple script to generate UK lottery numbers (7 numbers, 1 to 49 inclusive).
My code has a function that generates 7 random numbers into a list, runs set on the list removing duplicate numbers, checks if there are still 7 members in the list, and if not the function calls itself to generate 7 new numbers.
However, when the function calls itself it does not return the list.
I’d appreciate knowing what I’m doing wrong here.
from random import randint
def lotto():
l = []
for r in range(1,8):
l.append(randint(1,49))
print "DEBUG: l=", l
print "DEBUG: set(l)=", set(l), len(set(l))
if(len(set(l)) !=7):
lotto()
else:
print "Before return l, l = ", l
return l
def main():
numbers = lotto()
print numbers
Here is a sample run that does not work correctly:
DEBUG: l= [44, 32, 12, 12, 33, 16, 31]
DEBUG: set(l)= set([32, 33, 44, 12, 16, 31]) 6
DEBUG: l= [46, 20, 10, 24, 16, 35, 44]
DEBUG: set(l)= set([35, 10, 44, 46, 16, 20, 24]) 7
Before return l, l = [46, 20, 10, 24, 16, 35, 44]
None
And a sample run that does work correctly:
DEBUG: l= [20, 5, 21, 37, 10, 44, 38]
DEBUG: set(l)= set([37, 38, 10, 44, 20, 21, 5]) 7
Before return l, l = [20, 5, 21, 37, 10, 44, 38]
[20, 5, 21, 37, 10, 44, 38]
You’re not returning the result of the recursive call.