连接带有重叠词的输入句子

Connecting input sentences with overlapping words

任务是连接重叠的输入句子。我的问题是如何正确删除重叠部分。

输入:第一行是要连接的句子数。 接下来的几行是句子。 输出:连接句子

示例:

输入:

2
The harder you work for something, the
something, the greater you?ll feel when you achieve it.

输出:

The harder you work for something, the greater you?ll feel when you achieve it.

我的代码:

def connect(sentence1,sentence2):
  x= None
  y= None
  for i in range(len(sentence2)):
    if sentence2[:len(sentence2)-i] in sentence1 and len(sentence2[:len(sentence2)-i]) != 1:
        y =(sentence1+' '+sentence2[len(sentence2)-i:].strip())
        x =True
        break
  return x,y
n = int(input())
lst = []
for i in range(n):
  a = input()
  lst.append(a)
for i in lst:
  for j in lst:
    if i ==j:
        pass
    elif True in connect(i,j):
        lst.remove(i)
        lst.remove(j)
        lst.append(connect(i,j)[1])
print(lst[0])

输入 1:

3
The fool doth think he is wise,
wise man knows himself to be a fool.
wise, but the wise

输出 1:不正确

The fool doth think he is wise, man knows himself to be a fool. but the wise

预期输出 1:

The fool doth think he is wise, but the wise man knows himself to be a fool.

输入 2:

7
afraid of greatness.
Be not afraid
some achieve greatness,
greatness thrust upon them.
greatness. Some
Some are born great, some
greatness, and others have greatness

输出 2:错误

line 21, in 
    lst.remove(i)
ValueError: list.remove(x): x not in list

预期输出 2:

Be not afraid of greatness. Some are born great, some achieve greatness, and others have greatness thrust upon them.

您需要跟踪重叠的长度(结束-开始或开始-结束),以便从您连接的部分之一中剪切适当数量的字符:

sentences = """afraid of greatness.
Be not afraid
some achieve greatness,
greatness thrust upon them.
greatness. Some
Some are born great, some
greatness, and others have greatness""".split("\n")

result = sentences.pop(0) # start with any part, and take it out

while sentences:
    for s in list(sentences):
        atEnd   = next((p for p in range(1,len(s)) if result[-p:]==s[:p]),0)
        if atEnd:                        # length of overlapping end-start
            result = result + s[atEnd:]  # append to end, cut starting overlap
            sentences.remove(s)
            continue
        atStart = next((p for p in range(1,len(s)) if result[:p]==s[-p:]),0)
        if atStart:                      # length of overlapping start-end
            result = s[:-atStart]+result # insert at start, cut ending overlap
            sentences.remove(s)

print(result)

Be not afraid of greatness. Some are born great, some achieve greatness, and others have greatness thrust upon them.