I have a python list of strings, let's say:
elems = ["A", "B", "C", "D"]
I want to create a new list whose elements are each element of elems
repeated a fixed number of times (let's say twice), in a random order, but while making sure that two consecutive elements never have the same value.
For example, ["D", "B", "A", "B", "D", "C", "A", "C"]
is a good result. ["D", "B", "A", "B", "D", "C", "C", "A"]
is not (C is repeated in 6th and 7th position).
The simplest idea is probbaly just:
ans = 2*elems
random.shuffle(ans)
and then some code to take care of the repetitions, but all the solutions I can think of involve potentially infinite loops. Is there a simple and reliable way to do that ?
Thanks.
I am assuming that the input list has distinct elements.
import random
def randomize_carefully(elems, n_repeat=2):
s = set(elems)
res = []
for n in range(n_repeat):
if res:
# Avoid the last placed element
lst = list(s.difference({res[-1]}))
# Shuffle
random.shuffle(lst)
lst.append(res[-1])
# Shuffle once more to avoid obvious repeating patterns in the last position
lst[1:] = random.sample(lst[1:], len(lst)-1)
else:
lst = elems[:]
random.shuffle(lst)
res.extend(lst)
return res
for i in range(10):
print randomize_carefully(["A", "B", "C", "D"])
Some output:
['B', 'C', 'D', 'A', 'C', 'A', 'D', 'B']
['B', 'D', 'C', 'A', 'C', 'B', 'A', 'D']
['C', 'B', 'D', 'A', 'B', 'C', 'D', 'A']
['B', 'D', 'A', 'C', 'A', 'B', 'D', 'C']
['D', 'C', 'A', 'B', 'C', 'D', 'A', 'B']
['C', 'D', 'A', 'B', 'D', 'C', 'A', 'B']
['D', 'A', 'C', 'B', 'C', 'A', 'B', 'D']
['C', 'D', 'A', 'B', 'C', 'D', 'A', 'B']
['C', 'B', 'A', 'D', 'A', 'B', 'D', 'C']
['B', 'D', 'A', 'C', 'A', 'D', 'C', 'B']
You could make a function that checks if two consecutive values in a list x
are the same:
def compareConsecutive(x):
for i in x:
if i == x[x.index(i)+1]:
return False
Then shuffle the list in a while
loop until compareConsecutive()
stops returning False
:
while compareConsecutive(ans) == False:
random.shuffle(ans)
This could take a while with a long list, since random.shuffle()
could keep generating lists that have consecutive values in them, but it will work eventually :)
I think this could be an algorithm for doing what you want:
let R
be your result list
- pick a random element
e
from elems
, and append e
to R
- let
elems_1 = elems \ e
, i.e. remove e
from elems
- pick a random element
e_1
from elems_1
, and append e_1
to R
- let
elems_1 = elems \ e_1
, i.e. remove e_1
from elems
- repeat from step 3 until
R
is long enough
I think this will work, although it is not so elegant.
import random
elems = ['a','b','c','d']
length = len(elems)
l = []
for i in range(2):
random.shuffle(elems)
l.extend( elems )
if i > 0 and l[ i*length ] == l[ i*length - 1 ]:
l[i*length-2], l[i*length-1] = l[i*length-1], l[i*length-2]
print l