[NEWB]: List with random numbers
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Sun Aug 20 02:32:09 EDT 2006
In <1156054456.520655.49040 at b28g2000cwb.googlegroups.com>, eltower wrote:
> 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:
Well, you said yourself that you finish with a list of length 7. And you
are doing this as long as your list is shorter than 8. 7 < 8 is always
true → infinite loop.
> 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?
Do you know `random.shuffle()`?
In [4]: random_list = range(7)
In [5]: random.shuffle(random_list)
In [6]: random_list
Out[6]: [1, 4, 6, 2, 5, 0, 3]
Same effect but more efficient than your approach.
Ciao,
Marc 'BlackJack'
More information about the Python-list
mailing list