1 回答

TA貢獻1826條經驗 獲得超6個贊
由于您只有 6 個類別,您可以使用 itertools.product 然后根據您的標準過濾您的結果。
您的示例有些令人困惑,因為我不確定您如何從不包含“D”的前三個類別“ABC”中獲得“AAABCD”,或者如何通過組合不包含“BCDEI”的“BCDEI”獲得“ABBBBC”包含“A”。但是,假設您想要獲得長度為 6 的“ABCDEF”的某個子集的所有唯一組合,直到符號替換,您可以這樣做。
from itertools import product
CATEGORIES = 'ABCDEF'
def combinations(cats):
# use itertools to get all combinations
all_combs = product(cats,repeat=len(CATEGORIES))
valid_combs = set()
# For every possible combination find the order in which the characters appear
for s in all_combs:
s = ''.join(s)
order = []
for c in s:
if c not in order:
order.append(c)
# replace the character by ones following a set predetermined order
for i,c in enumerate(order):
replace_char = CATEGORIES[i].lower()
s = s.replace(c, replace_char)
# add to set to remove duplicates
s = s.upper()
valid_combs.add(s)
return list(valid_combs)
用法
combinations('AB')
['ABABBB', 'ABABBA', 'AABBBB', 'ABAABB', 'ABBAAA', 'AABAAA', 'AABABB', 'AAABAB', 'AABABA', 'AABAAB', 'ABAAAB', 'AABBAB', 'AAAAAB', 'ABBAAB', 'ABBABA', 'ABBABB', 'AAAABA', 'ABAAAA', 'AAABAA', 'ABAABA', 'ABBBAB', 'AAABBB', 'ABBBBA', 'AAABBA', 'AABBAA', 'ABABAA', 'AAAAAA', 'ABBBBB', 'ABABAB', 'ABBBAA', 'AABBBA', 'AAAABB']
這樣做的基本原理是,如果 'ABAACD' 和 'BABBDC' 屬于同一個等價類,則字符按順序出現的成員是該等價類的唯一代表。
雖然這不是很有效,因此對于更大的類別列表,您可能需要直接構建列表。
添加回答
舉報