在给定的字符串中查找所有可能的子序列

编程入门 行业动态 更新时间:2024-10-07 14:25:12
本文介绍了在给定的字符串中查找所有可能的子序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I have written this piece of code and it prints all substrings of a given string but I want it to print all the possible subsequences.

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

推荐答案

使用组合获取子序列.这就是组合的用途.

Use combinations to get subsequences. That's what combinations is for.

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

更多推荐

在给定的字符串中查找所有可能的子序列

本文发布于:2023-11-30 07:34:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649189.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   序列

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!