pythonrandominteger

Simple Lottery: Generate new six unique random numbers between 1 and 49


I started programming the first two in my list:

import random

def lottery_six():
    setOfSix = set()
    while len(setOfSix) < 6:
        setOfSix.add(random.randint(1,49))
    lottery = list(setOfSix)
    return lottery

def generateLottery(lottery):
    abc = set()
    while (all(i >= 25 for i in lottery) == True) or (all(i < 25 for i in lottery) == True) or \
    (sum(i >= 25 for i in lottery) >= 5) or (sum(i < 25 for i in lottery) >= 5):
        abc = lottery_six()
    return abc

print(generateLottery(lottery_six()))

However, that does not work. Why? And how can I fix it?


Solution

  • Consider this, we will repeat this code until we find a suitable set of values. First we will take the range [1,49] and we will randomly order them and take the first 6 values. Then we check if the range satisfies either of the first 2 requirements. If it does we break the loop and we keep this list of values.

    while True:
        x = (np.random.permutation(49)+1)[0:6]
        if len([i for i in x if 1<=i<25]) > 4: break
        if len([i for i in x if 25<=i<=49]) > 4: break
    
    print(x)
    

    The entirety of your code can be written as

    while True:
        x = (np.random.permutation(49)+1)[0:6]    
        # Check for short
        if len([i for i in x if 1<=i<25]) > 4: break
        # Check for large
        if len([i for i in x if 25<=i<=49]) > 4: break
        # Check for even
        if len([i for i in x if i%2 == 0]) > 5: break 
        # Check for odd
        if len([i for i in x if (i+1)%2 == 0]) > 5: break 
        # Check for successive
        if len([i for ix, i in enumerate(x[0:-2]) 
                if (x[ix+1] - i == 1 and x[ix+2] - x[ix+1] == 1)]) > 0: break
    
    print(x)
    

    This will find a list which satisfies your conditions. The last statement is a bit dense, broken down it goes through every value in your list and checks if you have at least 3 successive values x[ix+1] - i == 1 and x[ix+2] - x[ix+1] == 1. If this is true, we add the value to the list, if at the end there is at least 1 value in this new list we can conclude that there was at least 3 consecutive values.