lundi 1 février 2016

Python Creating a nested list with random module

Let's say I want to create a nested list with number sequence, and I want no repeated list sequence.

i.e. I would like something like this: [[1,2,3,4],[2,1,3,4],[4,2,3,1]] ,where the len of list depend on how many non repeated number sequence I could generate in limited attempt (four attempts in below case)

So here my first attempt:

import random
rng = random.Random()
bd =list(range(4))
i = 0
result =[]

while i <4:
    rng.shuffle(bd)
    if bd not in result:
        result.append(bd)
    i +=1
print(result)

I created the a list bd = [0,1,2,3] first before entering the while loop.

While running the above code, I got surprisingly only one element in my nested list every time.

Result: [[1, 2, 0, 3]]

But if I modify the code a little bit, it works as I expected. Here my modified code:

import random
rng = random.Random()
i = 0
result =[]

while i <4:
    bd =list(range(4))
    rng.shuffle(bd)
    if bd not in result:
        result.append(bd)
    i +=1
print(result)

Result: [[3, 2, 0, 1], [1, 0, 3, 2], [0, 1, 3, 2]]

What I do is just reset the list bd in every loop over again.

As per my understanding the list bd would be shuffled in every loop, so resetting bd to [0,1,2,3] should be meaningless. Could somebody explain to me why the modified code works? Thanks.




Aucun commentaire:

Enregistrer un commentaire