【问题标题】:Combine two sentences with some words missing in both or any one [closed]将两个句子与两个或任何一个中缺少的一些单词结合起来[关闭]
【发布时间】:2020-11-18 00:57:58
【问题描述】:
Input 1 - 'My name is Mayank'
Input 2 - 'My will name not Mayank'

Output - 'My will name is not Mayank' or 'My will name not is Mayank' 

我想组合两个字符串,它们都可能包含一些额外的单词(另一个缺少)。如果有多个输出,那么请给出任何一个。

请提供 Python 或 C++ 中的任何提示或代码。

更新 - 应保持单词的顺序,并且假设所有常见单词在两个输入中的顺序相同。

【问题讨论】:

  • 你想要一个特定单词顺序的答案吗?
  • 输出对我来说没有意义。你能解释一下吗?
  • @vivek_23 我的意思是单词的顺序......我可以这样回答'是 Mayank 我的名字不会'。
  • @YashShah 我问过 Mayank。
  • 这听起来与“diff”算法所做的非常相似,例如 GNU diff 或 git diff:en.wikipedia.org/wiki/Diff

标签: python c++ string algorithm data-structures


【解决方案1】:

如果你记下每个句子中每个单词之前的一组单词,你会得到

{'My':     set(),
 'name':   {'My', 'will'},
 'is':     {'My', 'name'},
 'Mayank': {'My', 'is', 'name', 'not', 'will'},
 'will':   {'My'},
 'not':    {'My', 'name', 'will'}}

然后您可以在列表上进行迭代,生成其前面的完整单词集已经生成的单词。

这是 Python:

from collections import defaultdict


s1 = 'My name is Mayank'
s2 = 'My will name not Mayank'
s = [s1.strip().split(), s2.strip().split()]

keyaftervalues = defaultdict(set)
for phrase in s:
    for i, this in enumerate(phrase):
        keyaftervalues[this] |= set(phrase[:i])
keyaftervalues = dict(keyaftervalues)

sofar, sofarlist = set(), []
while keyaftervalues:
    consider = []
    for this, preceders in keyaftervalues.items():
        if sofar.issuperset(preceders):
            others = preceders - sofar
            consider.append((this, len(others), len(preceders)))
    if consider:
        consider.sort(key=lambda x:x[1:])
        last = consider[0][0]
        sofar.add(last)
        sofarlist.append(last)
        del keyaftervalues[last]
answer = ' '.join(sofarlist)

print(answer)   # My will name is not Mayank

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 2023-04-03
    相关资源
    最近更新 更多