【问题标题】:python program to print all possible sub-sequences with no repetition of characterspython程序打印所有可能的子序列,不重复字符
【发布时间】:2022-01-15 17:02:06
【问题描述】:
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)

【问题讨论】:

  • 你能添加预期的输出吗?
  • 问题是什么?

标签: python string


【解决方案1】:

您可以使用itertools.permutations

返回可迭代对象中元素的连续 r 长度排列。

如果 r 未指定或为 None,则 r 默认为可迭代的长度,并生成所有可能的全长排列。

根据输入可迭代的顺序,排列元组以字典顺序发出。因此,如果输入的可迭代对象已排序,则组合元组将按排序顺序生成。

元素根据它们的位置而不是它们的值被视为唯一的。因此,如果输入元素是唯一的,则每个排列中不会有重复值。

由于入参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)

输出:

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

【讨论】:

    【解决方案2】:

    子序列依赖于原始顺序,因此它们不是组合。

    您可以使用一个集合来逐步增加每个字符的先前序列(仅从尚未包含该字符的序列扩展):

    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)
    

    输出:

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

    【讨论】:

      猜你喜欢
      • 2019-08-06
      • 2018-08-22
      • 2016-01-02
      • 1970-01-01
      • 2020-02-16
      • 2020-03-29
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多