I’m working on an exercise: create a function which retuns a list with "n" non-duplicated random numbers, in crescent order, from 1-60.
The code is working fine, but eventually it generates more than "n" numbers (about 1/7 times).
Heres the code:
import random
def r_list (n):
r_list = []
while len(r_list) < n:
for i in range(n):
rn = random.randint(1,61)
if rn not in r_list:
r_list.append(rn)
else:
continue
r_list.sort()
print(r_list)
Why it generates more than "n" numbers? How do I fix this?
>Solution :
your inner loop is the problem, as long as you are using that it’ll add extras.
import random
def r_list (n):
r_list = []
while len(r_list) < n:
rn = random.randint(1,61)
if rn not in r_list:
r_list.append(rn)
else:
continue
r_list.sort()
print(r_list)