[英]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.