-1

I have five elements in a list variable (call it A). I want to represent every possible order for those five elements with each order being stored in another list as a list (call it B). If I append A to B then attempt to re-shuffle A to get a new order the previously stored list in B is also shuffled as it is assigned to A so after trying to produce the 25 different orders of the five elements of A, I get 25 of the same order in B. Is there a way that I can add A to B then shuffle A without shuffling the appended A in B?

Here is the basic code:


from random import shuffle

A = ["M1", "M2", "M3", "M4", "M5"]

B = []

for i in range(len(A) * 5):
    shuffle(A)
    temp = A
    B.append(temp)


print (T)

Thanks

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
marcef
  • 1
  • On the forth line the B.append(temp) is meant to be on a new line. – marcef Oct 12 '16 at 14:09
  • 1
    What the `T`(`print (T)`)? – vishes_shell Oct 12 '16 at 14:10
  • 4
    `from itertools import permutations \\ B = list(permutations(A))`? – Efferalgan Oct 12 '16 at 14:11
  • 2
    If my abilities to do statistics are not too rusty, you have approximately 0.000000046 percent chance of getting all 25 permutations, with your code. You should not rely on a random method to generate your permutations, or, if you really want to do it that way, do waaaaay more iterations and store your results in a set. – Efferalgan Oct 12 '16 at 14:17

2 Answers2

2

I want to represent every possible order for those five elements with each order being stored in another list as a list.

Assuming this is an XY problem, let's step back and consider: shuffling is not the correct way to find all permutations.

There is a standard library solution (already referenced in the comments) that does all of this in one step:

>>> from itertools import permutations
>>> list(permutations(["M1", "M2", "M3", "M4", "M5"]))
[('M1', 'M2', 'M3', 'M4', 'M5'), ...] # and off to the races...

Note that this returns a list of tuples, which should be fine for your intents and purposes. You can use a list comprehension to convert them to lists, if need be.

Community
  • 1
  • 1
brianpck
  • 8,084
  • 1
  • 22
  • 33
-1

You should use copy or deepcopy.

from copy import deepcopy, copy
from random import shuffle

A = ["M1", "M2", "M3", "M4", "M5"]

B = []
# Use deep deepcopy if you have lists with lists e.g. [[12, [2]], [2]]
for i in range(len(A) * 5):
     shuffle(A)
     B.append(deepcopy(A))
# But in this case better to use copy()
C = []
for i in range(len(A) * 5):
     shuffle(A)
     C.append(copy(A))
Oleksandr Dashkov
  • 2,249
  • 1
  • 15
  • 29