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.
You could make a function that checks if two consecutive values in a list
x
are the same:Then shuffle the list in a
while
loop untilcompareConsecutive()
stops returningFalse
: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 will work, although it is not so elegant.
I think this could be an algorithm for doing what you want:
let
R
be your result liste
fromelems
, and appende
toR
elems_1 = elems \ e
, i.e. removee
fromelems
e_1
fromelems_1
, and appende_1
toR
elems_1 = elems \ e_1
, i.e. removee_1
fromelems
R
is long enoughI am assuming that the input list has distinct elements.
Some output: