How To Randomize The Order Of Elements Of A List While Making Sure No Consecutive Values Are Equal?
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
Solution 1:
I am assuming that the input list has distinct elements.
import random
defrandomize_carefully(elems, n_repeat=2):
s = set(elems)
res = []
for n inrange(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 inrange(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']
Solution 2:
You could make a function that checks if two consecutive values in a list x
are the same:
defcompareConsecutive(x):
for i in x:
if i == x[x.index(i)+1]:
returnFalse
Then shuffle the list in a while
loop until compareConsecutive()
stops returning False
:
whilecompareConsecutive(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 :)
Solution 3:
I think this could be an algorithm for doing what you want:
let R
be your result list
- pick a random element
e
fromelems
, and appende
toR
- let
elems_1 = elems \ e
, i.e. removee
fromelems
- pick a random element
e_1
fromelems_1
, and appende_1
toR
- let
elems_1 = elems \ e_1
, i.e. removee_1
fromelems
- repeat from step 3 until
R
is long enough
Solution 4:
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 > 0and 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
Post a Comment for "How To Randomize The Order Of Elements Of A List While Making Sure No Consecutive Values Are Equal?"