简体   繁体   English

python 程序打印所有可能的子序列,不重复字符

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

You can use itertools.permutations .您可以使用itertools.permutations

Return successive r length permutations of elements in the iterable.返回可迭代中元素的连续 r 长度排列。

If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated.如果 r 未指定或为 None,则 r 默认为可迭代的长度,并生成所有可能的全长排列。

The permutation tuples are emitted in lexicographic ordering according to the order of the input iterable.根据输入可迭代的顺序,排列元组以字典顺序发出。 So, if the input iterable is sorted, the combination tuples will be produced in sorted order.因此,如果输入的可迭代对象已排序,则组合元组将按排序顺序生成。

Elements are treated as unique based on their position, not on their value.元素根据其 position 而非其值被视为唯一。 So if the input elements are unique, there will be no repeat values in each permutation.因此,如果输入元素是唯一的,则每个排列中不会有重复值。

Since the same element a exists in the input parameter word , it will cause duplicate results, so use a set for deduplication.由于输入参数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: 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']

Sub-sequences are dependent of the original order so they are not combinations.子序列依赖于原始顺序,因此它们不是组合。

You could use a set to progressively augment previous sequences with each character (extending only from sequences that don't already contain the character):您可以使用一个集合来逐步增加每个字符的先前序列(仅从尚未包含该字符的序列扩展):

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: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM