gpt4 book ai didi

python - 合并列表中重叠的字符串序列

转载 作者:行者123 更新时间:2023-12-05 05:54:44 26 4
gpt4 key购买 nike

我想弄清楚如何将列表中的重叠字符串合并在一起,例如

['aacc','accb','ccbe'] 

我会得到

['aaccbe']

下面的代码适用于上面的示例,但是在以下情况下它没有提供我想要的结果:

s = ['TGT','GTT','TTC','TCC','CCC','CCT','CCT','CTG','TGA','GAA','AAG','AGC','GCG','CGT','TGC','GCT','CTC','TCT','CTT','TTT','TTT','TTC','TCA','CAT','ATG','TGG','GGA','GAT','ATC','TCT','CTA','TAT','ATG','TGA','GAT','ATT','TTC']
a = s[0]
b = s[-1]
final_s = a[:a.index(b[0])]+b

print(final_s)
>>>TTC

我的输出显然不对,我不知道为什么在这种情况下它不起作用。请注意,我已经组织了列表,其中重叠的字符串彼此相邻。

最佳答案

您可以使用 trie 来存储正在运行的子字符串并更有效地确定重叠。当出现重叠的可能性时(即对于输入字符串,在 trie 中存在一个字符串以输入字符串的开头或结尾的字母),进行广度优先搜索以找到最大可能的重叠,然后剩余的字符串位被添加到 trie 中:

from collections import deque
#trie node (which stores a single letter) class definition
class Node:
def __init__(self, e, p = None):
self.e, self.p, self.c = e, p, []
def add_s(self, s):
if s:
self.c.append(self.__class__(s[0], self).add_s(s[1:]))
return self

class Trie:
def __init__(self):
self.c = []
def last_node(self, n):
return n if not n.c else self.last_node(n.c[0])
def get_s(self, c, ls):
#for an input string, find a letter in the trie that the string starts or ends with.
for i in c:
if i.e in ls:
yield i
yield from self.get_s(i.c, ls)
def add_string(self, s):
q, d = deque([j for i in self.get_s(self.c, (s[0], s[-1])) for j in [(s, i, 0), (s, i, -1)]]), []
while q:
if (w:=q.popleft())[1] is None:
d.append((w[0] if not w[0] else w[0][1:], w[2], w[-1]))
elif w[0] and w[1].e == w[0][w[-1]]:
if not w[-1]:
if not w[1].c:
d.append((w[0][1:], w[1], w[-1]))
else:
q.extend([(w[0][1:], i, 0) for i in w[1].c])
else:
q.append((w[0][:-1], w[1].p, w[1], -1))
if not (d:={a:b for a, *b in d}):
self.c.append(Node(s[0]).add_s(s[1:]))
elif (m:=min(d, key=len)):
if not d[m][-1]:
d[m][0].add_s(m)
else:
t = Node(m[0]).add_s(m)
d[m][0].p = self.last_node(t)

综合考虑

t = Trie()
for i in ['aacc','accb','ccbe']:
t.add_string(i)

def overlaps(trie, c = ''):
if not trie.c:
yield c+trie.e
else:
yield from [j for k in trie.c for j in overlaps(k, c+trie.e)]

r = [j for k in t.c for j in overlaps(k)]

输出:

['aaccbe']

关于python - 合并列表中重叠的字符串序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69587008/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com