简体   繁体   中英

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 .

Return successive r length permutations of elements in the iterable.

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.

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

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']

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:

for ss in subseqs('abca'): print(ss)
abc
bca
ab
ca
ac
bc
ba
b
c
a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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