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

2024-05-20 13:36:00 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我试图找出如何将列表中的重叠字符串合并在一起

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

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


Tags: 字符串列表情况final我会atggatcct
2条回答

使用^{}查找重叠并适当连接,然后使用^{}应用整个列表

import difflib
from functools import reduce


def overlap(s1, s2):
    # https://stackoverflow.com/a/14128905/4001592
    s = difflib.SequenceMatcher(None, s1, s2)
    pos_a, pos_b, size = s.find_longest_match(0, len(s1), 0, len(s2))
    return s1[:pos_a] + s2[pos_b:]


s = ['aacc','accb','ccbe']


result = reduce(overlap, s, "")
print(result)

输出

aaccbe

您可以使用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']

相关问题 更多 >