eltower wrote:
Hey all,
I'm trying to write a program in Python for learning purposes which is
meant to:
Generate a random number from 0 to 6
Insert this random number to the end of a list unless the number is
already there
finish with a len(list) = 7
so far, I have this:
import random
random_list = []
while len(random_list) < 8:
j = random.randrange(6)
if (j in random_list):
continue
else:
random_list.append(j)
continue
print random_list
however, I get stuck in an infinite loop.
Any suggestions?
Thank you in advance,
Adri
Maybe this would help:
>>while True:
print random.randrange(6),
3 2 5 4 1 3 1 3 5 0 5 3 4 0 2 2 5 2 2 5 3 1 0 2 0 4 2 4 3 1 3 3 2 3 3 2
1 5 4 2 0 1 5 3 4 1 2 3 5 1 1 5 4 0 3 0 4 4 1 2 1 4 4 5 2 4 5 4 2 5 5 3
5 0 2 3 2 3 5 5 2 0 0 1 5 5 0 0 3 5 3 2 1 4 4 0 1 0 3 1 0 2 0 5 5 2 5 0
5 5 1 0 2 3 1 4 3 3 1 3 5 2 1 4 0 5 3 2 5 0 2 5 3 4 5 5 0 0 3 4 3 1 5 5
3 4 3 4 5 0 3 0 2 5 5 1 3 3 5 3 4 0 3 3 2 5 1 1 1 1 0 3 0 3 5 0 4 5 4 0
1 0 5 2 3 1 1 4 4 3 0 0 0 3 3 5 3 5 4 1 1 0 2 4 5 3 3 1 3 5 5 0 1 4 2 1
0 0 0 3 0 4 5 5 5 5 0 4 1 3 4 0 5 3 0 0 5 1 1 3 4 1 0 5 4 5 0 1 1 5 4 1
2 2 5 2 0 1 1 5 4 5 1 5 5 3 0 3 2 4 3 4 3 2 2 0 3 2 4 2 4 2 3 5 0 4 0 0
1 3 0 4 1 0 0 4 2 4 5 3 5 0 4 2 1 4 4 2 0 0 4 4 1
Traceback (most recent call last):
File "<pyshell#8>", line 2, in -toplevel-
print random.randrange(6),
KeyboardInterrupt
If not, try putting "print random_list" *inside* your while loop.
HTH,
~Simon
P.S. Take a look at the random.shuffle() function... :-)