如何在确保没有连续值相等的情况下随机分配列表元素的顺序? [英] How to randomize the order of elements of a list while making sure no consecutive values are equal?
问题描述
我有一个python字符串列表,比方说:
I have a python list of strings, let's say:
elems = ["A", "B", "C", "D"]
我想创建一个新列表,其元素是elems
的每个元素,以随机顺序重复固定的次数(比如说两次),但是要确保两个连续的元素永远不会具有相同的值.
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.
例如,["D", "B", "A", "B", "D", "C", "A", "C"]
是一个很好的结果. ["D", "B", "A", "B", "D", "C", "C", "A"]
不是(C在第6位和第7位重复).
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 ?
谢谢.
推荐答案
我假设输入列表具有不同的元素.
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"])
一些输出:
['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']
这篇关于如何在确保没有连续值相等的情况下随机分配列表元素的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!