+ 1

what's wrong with the program?

I wanted to make a program to shuffle a list of alphabets and store shuffled list in an another list such that no two lists are shuffled exactly the same. /////////////////////////////////////////////////////////////////////////////////////////// import random h = ['a','b','c','d','e','f'] store = [] NumOfLetters = len(h) for j in range(10): if (h not in store): print('not in') store.append(h) print(store) for i in range(NumOfLetters): l = random.randint(0,5) letter = h[i] h[i] = h[l] h[l] = letter print(store) //////////////////////////////////////////////////////////////////////////////////////////////////// everything works as intended when i run the loops separately, it's when I nest for loops where things go wrong. I'm still new, so any advise will be much appreciated.

14th Sep 2018, 6:14 PM
Mayank Dhillon
Mayank Dhillon - avatar
5 Respostas
+ 6
Mayank Dhillon I found the problem! The way the code currently stands, a reference (not a copy) of `h` is being put in `store`. So even after shuffling `h`, it always "is" in `store` (the reference of `h` that is inside `store` is also shuffled). That causes the `if` block to be entered only at the first iteration, and that's why the length of `store` is 1 in the end. Passing a copy of `h` to `store` solves the problem. Like this: store.append(h.copy())
15th Sep 2018, 5:50 AM
Eduardo Petry
Eduardo Petry - avatar
+ 7
You can use random.shuffle to perform that. Also, you can swap values of variables in Python in one line: h[i], h[l] = h[l], h[i]
14th Sep 2018, 6:49 PM
Eduardo Petry
Eduardo Petry - avatar
+ 7
You can also use random.sample() using the length of the list as the length of the sample. This code uses that principle (lines 23 - 28): https://code.sololearn.com/ce35x5Xy1cSY/#py
15th Sep 2018, 4:08 AM
David Ashton
David Ashton - avatar
+ 1
I think I was not clear enough with my question What I want is something like this [['a', 'b', 'c', 'f', 'e', 'd'], ['a', 'b', 'c', 'd', 'e', 'f'], ['b', 'a', 'c', 'f', 'e', 'd']] and I don't wan't the same sequences to be in list that is, I don't want 2 of ['a', 'b', 'c', 'f', 'e', 'd'] in the "store" list when is use: \\\\\\\\\\\\\\\\\\\ if (h not in store): store.append(h) \\\\\\\\\\\\\\\\\\\\ only the shuffled "h" list generated at the end of loop is added to "store" list which means that there is only one element in the "store" list. I'm sure I'm doing something wrong I just want to know what. And thanks for informing me about random.shuffle() and h[i], h[l] = h[l], h[i] this really shorten the code for me.
15th Sep 2018, 4:53 AM
Mayank Dhillon
Mayank Dhillon - avatar
+ 1
@Eduardo Petry Thanks, I get it now. Really appreciate the help.
15th Sep 2018, 7:24 AM
Mayank Dhillon
Mayank Dhillon - avatar