[英]How to generate a sequence where each element is separated from an identical element by at least six different elements
From a list of 8 possible letters I want to generate a random sequence where each element is separated from an identical element by at least six different elements. 从8个可能的字母列表中,我想生成一个随机序列,其中每个元素至少由六个不同的元素与相同的元素分开。
sequence_list = []
target_list = ["a","b","c","d","e","f","g","h"]
for i in range(1,41):
sequence_list.append(random.choice(target_list))
print sequence_list
For example if the first letter in sequence_list
is an a
it should not be repeated for at least the next 6 items in the list. 例如,如果
sequence_list
的第一个字母是a
,则不应该至少重复列表中的后6个项目。 Same for every other item. 每个其他项目都相同。 Appreciate your help.
感谢您的帮助。
this is probably not the most efficient way of doing it, but you can do it like this: 这可能不是最有效的方法,但你可以这样做:
>>> target_list = list(string.ascii_letters[:8])
>>> target_list
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> sequence_list = []
>>> for i in range(1,41):
... el_list = [x for x in target_list if x not in sequence_list[-6:]]
... sequence_list.append(random.choice(el_list))
...
>>>
>>> sequence_list
['e', 'h', 'g', 'a', 'c', 'f', 'd', 'b', 'e', 'h', 'g', 'c', 'f', 'd', 'a', 'e', 'b', 'g', 'c', 'f', 'h', 'a', 'e', 'b', 'g', 'd', 'f', 'c', 'h', 'a', 'b', 'g', 'd', 'f', 'e', 'c', 'a', 'b', 'h', 'd']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.