Simple String , array and Dictionary
s = "cattcat"
t = "cat"
n = len(s)
nt = len(t)
a={}
for i in range(0,nt):
c = t[i]
for j in range(0,n):
if (s[j] == c):
if c in a:
try:
a[c].append(j+1)
except:
a[c]=[a[c],j+1]
else:
a[c]=j+1
print(a)
for z in range(0,len(a['c'])):
for y in range(0,len(a['a'])):
for x in range(0,len(a['t'])):
if(a['c'][z]<=a['a'][y]<=a['t'][x]):
print(a['c'][z],a['a'][y],a['t'][x])
from itertools import combinations
src='cattcat'
trg='cat'
comb_lst=[idx for el, idx in zip(
combinations(src,len(trg)),
combinations(range(len(src)),len(trg))
) if ''.join(el)==trg]
print(comb_lst)
def get_combos(d, s, i = 0, c = []):
if (r:=''.join(b for _, b in c)) == s:
yield c
elif d:
if s.startswith(r+d[0]):
yield from get_combos(d[1:], s, i = i+1, c=c+[(i, d[0])])
yield from get_combos(d[1:], s, i = i+1, c=c)
print(list(get_combos('cattcat', 'cat')))
您可以使用itertools.combinations获得所有可能组合的列表。使用zip,您不仅可以跟踪角色,还可以跟踪角色的位置。整个过程变成一个单一的列表理解练习,应该是相当有效的
输出:
可以使用递归生成器函数:
输出:
出于演示的目的,原始源字符串中每个字符的索引都包含在输出中
相关问题 更多 >
编程相关推荐