I am using itertools.combinations()
to generate a list of two-item tuples based off a list of non-repetitive elements. I then shuffle the list produced. However, the contents of the tuples themselves are organized chronologically. For example, running the code below:
import random
import itertools
items = ["a","b","c","d","e"]
item_combos = list(itertools.combinations(items, 2))
random.shuffle(item_combos)
print(item_combos)
outputs this:
['a', 'b', 'c', 'd', 'e']
[('b', 'd'), ('a', 'e'), ('b', 'c'), ('a', 'd'), ('a', 'b'), ('a', 'c'), ('c', 'e'), ('c', 'd'), ('b', 'e'), ('d', 'e')]
The characters are ordered within the tuples by when they appear in the input list (Not alphabetically, the input list just happens to be alphabetically sorted. Scrambling the list would not solve the problem, just hide it). 'c' will always appear to the left of 'd', 'a' will always appear left of everything else.
My solution is to simply replace all the tuples with scrambled tuples (shown below). This works, but proves to be exceedingly slow, especially on larger lists.
for i in range(len(item_combos)):
item_combos[i] = tuple(random.sample(item_combos[i], 2))
Is there a faster way to do this that yields similar outputs?
Instead of scrambling each tuple, choosing random tuples to reverse works much faster. This has the same result, as each tuple in item_combos
only contain two items.
New tuple "scrambling" code:
for i in range(len(item_combos)):
if random.random()<.5:
item_combos[i] = item_combos[i][::-1]