[英]how to create a list sequence in python containing all possible pairs an equal number of times?
給定字母x,y
,有一種方法可以編寫一個python函數,該函數返回一個包含所有可能對( [x,x], [x,y], [y,x], [y,y]
)的列表序列。相等次數?
例如,我可以編寫一個函數來接收輸入(例如[x,y]
)和每個可能的對出現的次數(例如2
),然后返回例如列表序列: [xxxyyxyyx]
嗎?
優選地,我希望函數生成一個“隨機”序列,以便它也可以返回:
[y x y y x x x y y]
在兩種情況下, [x,x] [x,y] [y,x]
和[y,y]
恰好出現兩次。
理想情況下,我想找到一種解決方案,該解決方案也適用於例如4個字母[x,y,z,w]
。
根據您的編輯,以下內容將指導您所參考的瀏覽。
import random
import itertools
def generate_sequence(alphabet, num_repeats):
# generate the permutations of the list of size 2
# repeated `num_repeats` times
perms = [(letter1, letter2) for letter1, letter2 in itertools.product(alphabet, alphabet) for i in xrange(num_repeats)]
# save the original length of `perm` for later
perm_len = len(perms)
# randomly choose a starting point and add it to our result
curr_s, curr_e = random.choice(perms)
result = [curr_s, curr_e]
# remove the starting point from the list... on to the next one
perms.remove((curr_s, curr_e))
# while we still have pairs in `perms`...
while len(perms):
# get all possible next pairs if the end of the current pair
# equals the beginning of the next pair
next_vals = [(s,e) for s,e in perms if s == curr_e]
# if there aren't anymore, we may have exhausted the pairs that
# start with `curr_e`, in which case choose a new random pair
if len(next_vals) != 0:
next_s, next_e = random.choice(next_vals)
else:
next_s, next_e = random.choice(perms)
# remove the next pair from `perm` and append it to the `result`
perms.remove((next_s, next_e))
result.append(next_e)
# set the current pair to the next pair and continue iterating...
curr_s, curr_e = next_s, next_e
return result
alphabet = ('x', 'y', 'z')
num_repeats = 2
print generate_sequence(alphabet, num_repeats)
這個輸出
['z', 'z', 'z', 'x', 'x', 'y', 'z', 'y', 'y', 'z', 'y', 'x', 'y', 'x', 'z', 'x',
'z', 'y', 'x']
有了這個,您可以選擇最常見的對:
>>> from collections import Counter
>>> dict(Counter(zip(a, a[1:])).most_common())
{('z', 'z'): 2, ('z', 'y'): 2, ('x', 'y'): 2, ('z', 'x'): 2, ('y', 'y'): 2, ('x', 'x'): 2, ('y', 'x'): 2, ('x', 'z'): 2, ('y', 'z'): 2}
如果您只關心配對:
>>> [t[0] for t in Counter(zip(a, a[1:])).most_common()]
[('z', 'z'), ('z', 'y'), ('x', 'y'), ('z', 'x'), ('x', 'x'), ('y', 'x'), ('x', 'z'), ('y', 'y'), ('y', 'z')]
如果您只關心哪些對出現2次:
>>> [pair for pair, count in Counter(zip(a, a[1:])).items() if count == 2]
[('z', 'z'), ('z', 'y'), ('x', 'y'), ('z', 'x'), ('x', 'x'), ('y', 'x'), ('x', 'z'), ('y', 'y'), ('y', 'z')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.