Home > database >  Adding random integers to list if criteria met
Adding random integers to list if criteria met

Time:03-08

I am trying to make function make(ls) generate a list of 4 random integers. If these integers passes the three checks in the function check(ls) they should be added as a list to res. If they do not pass another set will be generated until I have a list of 4 lists. The code below gives me IndexError: list index out of range - Any idea?

def check(ls):
    for n in ls:
        if n==0 or ls[0] == ls[2] or ls[1] == ls[3]:
            return False
    return True 

def make(ls):
    res = []
    while len(res) < 4:
        tmp = [randint(1,9),randint(1,9),randint(1,9),randint(1,9)]
        if check([tmp]) == True:
            res.append(tmp)
    return res

CodePudding user response:

You call the function with a nested list, dont do this

if check([tmp]) == True:

should just be

if check(tmp):
  • Related