【问题标题】:finding all possible subsequences in a given string查找给定字符串中所有可能的子序列
【发布时间】:2019-12-20 01:23:42
【问题描述】:

我已经编写了这段代码,它打印给定字符串的所有子字符串,但我希望它打印所有可能的子序列。

from itertools import combinations_with_replacement
s = 'MISSISSIPPI'
lst = []
for i,j in combinations_with_replacement(range(len(s)), 2):
        print(s[i:(j+1)])

【问题讨论】:

  • 不清楚您的要求。你能举一个简短的具体例子吗?
  • 如果需要子序列,为什么要使用combinations_with_replacement 而不是combinations

标签: python combinations subsequence


【解决方案1】:

使用combinations 获取子序列。这就是combinations 的用途。

from itertools import combinations

def all_subsequences(s):
    out = set()
    for r in range(1, len(s) + 1):
        for c in combinations(s, r):
            out.add(''.join(c))
    return sorted(out)

例子:

>>> all_subsequences('HELLO')
['E', 'EL', 'ELL', 'ELLO', 'ELO', 'EO', 'H', 'HE', 'HEL', 'HELL', 'HELLO', 'HELO',
 'HEO', 'HL', 'HLL', 'HLLO', 'HLO', 'HO', 'L', 'LL', 'LLO', 'LO', 'O']
>>> all_subsequences('WORLD')
['D', 'L', 'LD', 'O', 'OD', 'OL', 'OLD', 'OR', 'ORD', 'ORL', 'ORLD', 'R', 'RD',
 'RL', 'RLD', 'W', 'WD', 'WL', 'WLD', 'WO', 'WOD', 'WOL', 'WOLD', 'WOR', 'WORD',
 'WORL', 'WORLD', 'WR', 'WRD', 'WRL', 'WRLD']

【讨论】:

    【解决方案2】:

    这样做的一个简单方法是验证您正在制作的列表是否已经包含您正在迭代的案例。如果您已经看过它,请跳过它,如果没有,则将其附加到您看过的组合列表中。

    from itertools import combinations_with_replacement
    
    s = 'MISSISSIPPI'
    lst = []
    
    for i,j in combinations_with_replacement(range(len(s)), 2):
        if s[i:(j+1)] not in lst:
            lst.append(s[i:(j+1)]) # save new combination into list
            print(lst[-1]) # print new combination
    

    为了确保涵盖所有情况,绘制循环将要遍历的组合图确实很有帮助。假设一个通用字符串,其中字母由它们在 python 列表中的位置表示,例如 0 到 3。

    这是“combinations_with_replacement”生成的数字

    00, 01, 02, 03,
    11, 12, 13,
    22, 23,
    33

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 2012-04-20
    • 2015-06-18
    • 2017-05-26
    • 2022-12-07
    • 2019-03-29
    • 2016-04-20
    相关资源
    最近更新 更多