cha*_*ger 0 python combinations subsequence
我已经编写了这段代码,它打印给定字符串的所有子字符串,但我希望它打印所有可能的子序列。
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)])
Run Code Online (Sandbox Code Playgroud)
用于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)
Run Code Online (Sandbox Code Playgroud)
例子:
>>> 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']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8162 次 |
| 最近记录: |