以字符串列表形式给出输入
input = [
'mission statement',
'a quick bite to eat',
'a chip off the old block',
'chocolate bar',
'mission impossible',
'a man on a mission',
'block party',
'eat my words',
'bar of soap'
]
我需要写一个函数来组合一对字符串,它们的最后一个和第一个单词是S1+S2
例如: “执行任务的人”—>;S1 “使命宣言”->;S2
然后输出“一个执行任务的人”
上面的字符串列表的输出是
^{pr2}$这是我用python编写的代码
firstMapper = {}
for val in input:
wordList = val.split()
firstMapper[wordList[0]] = ' '.join([str(x) for x in wordList[1:]])
ans = []
for val in input:
wordList = val.split()
if wordList[-1] in firstMapper:
k = val+" "+firstMapper[wordList[-1]]
if k not in ans:
ans.append(k)
print(ans)
但这只给了我
['a quick bite to eat my words', 'a chip off the old block party', 'chocolate bar of soap', 'a man on a mission impossible']
我需要在O(n)内完成
更新
我设法这样做了
firstMapper = {}
for val in input:
wordList = val.split()
if wordList[0] in firstMapper:
firstMapper[wordList[0]].append(' '.join(wordList[1:]))
else:
temp = []
temp.append(' '.join(wordList[1:]))
firstMapper[wordList[0]] = temp
ans = []
for val in input:
wordList = val.split()
if wordList[-1] in firstMapper:
k = list(map(lambda x : val+" "+x, firstMapper[wordList[-1]]))
if k not in ans:
ans.extend(k)
print(ans)
这能用更好的方式解决吗?在
下面的代码可以满足您的需要。以下是对功能的描述:
collections.defaultdict
可以方便地创建字符串到列表的映射first words -> list of phrases
的映射last word -> list of phrases
的映射set
类型使这两个映射的键相交,以找出哪一个映射是共同的。在它大约是O(n),因为一次传递数据,然后使用了盲目快速的
set
类型。在输出为:
^{pr2}$相关问题 更多 >
编程相关推荐