python - How to randomize the order of elements of a list while making sure no consecutive values are equal? -


i have python list of strings, let's say:

elems = ["a", "b", "c", "d"] 

i want create new list elements each element of elems repeated fixed number of times (let's twice), in random order, while making sure 2 consecutive elements never have same value.

for example, ["d", "b", "a", "b", "d", "c", "a", "c"] result. ["d", "b", "a", "b", "d", "c", "c", "a"] not (c repeated in 6th , 7th position).

the simplest idea probbaly just:

ans = 2*elems random.shuffle(ans) 

and code take care of repetitions, solutions can think of involve potentially infinite loops. there simple , reliable way ?

thanks.

i assuming input list has distinct elements.

import random  def randomize_carefully(elems, n_repeat=2):     s = set(elems)     res = []     n in range(n_repeat):         if res:             # avoid last placed element             lst = list(s.difference({res[-1]}))             # shuffle             random.shuffle(lst)             lst.append(res[-1])             # shuffle once more avoid obvious repeating patterns in last position             lst[1:] = random.sample(lst[1:], len(lst)-1)         else:             lst = elems[:]             random.shuffle(lst)         res.extend(lst)     return res  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'] 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -