[英]python program to print all possible sub-sequences with no repetition of characters
def countGoodSubsequences(word): combs=[] for i in range(1, len(word)+1): combs.append(list(itertools.combinations(word,i))) l2=[] for c in combs: for t in c: l2.append(''.join(t)) return l2 wordi= "abca" l3=countGoodSubsequences(wordi) print(l3)
您可以使用itertools.permutations
。
返回可迭代中元素的連續 r 長度排列。
如果 r 未指定或為 None,則 r 默認為可迭代的長度,並生成所有可能的全長排列。
根據輸入可迭代的順序,排列元組以字典順序發出。 因此,如果輸入的可迭代對象已排序,則組合元組將按排序順序生成。
元素根據其 position 而非其值被視為唯一。 因此,如果輸入元素是唯一的,則每個排列中不會有重復值。
由於輸入參數word
中存在同一個元素a
,會導致重復結果,所以使用一個集合進行去重。
import itertools
def countGoodSubsequences(word):
combs = set()
for i in range(1, len(word)+1):
combs.update(itertools.permutations(word, r=i))
return [''.join(c) for c in combs]
wordi= "abca"
l3=countGoodSubsequences(wordi)
print(l3)
Output:
['aca', 'cab', 'acab', 'caa', 'c', 'aac', 'caba', 'abca', 'ac', 'abac', 'caab', 'aabc', 'aacb', 'ba', 'aba', 'baa', 'bca', 'baca', 'cbaa', 'bcaa', 'baac', 'b', 'ab', 'a', 'cb', 'aab', 'aa', 'ca', 'acba', 'abc', 'bc', 'acb', 'cba', 'bac']
子序列依賴於原始順序,因此它們不是組合。
您可以使用一個集合來逐步增加每個字符的先前序列(僅從尚未包含該字符的序列擴展):
def subseqs(word):
result = set() # resulting sequences (distinct)
for c in word: # add each character to previous sequences
result.update([ss+c for ss in result if c not in ss]) # new sequences
result.add(c) # add character itself
return sorted(result,key=len,reverse=True)
output:
for ss in subseqs('abca'): print(ss)
abc
bca
ab
ca
ac
bc
ba
b
c
a
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.