[英]find the common superstring from given list of strings in python
I have my strings in my input 我在输入中输入了字符串
'ATTAGACCTG', 'CCTGCCGGAA', 'AGACCTGCCG', 'GCCGGAATAC'
In output I want the common shortest superstring. 在输出中,我需要最短的公共超级字符串。
ATTAGACCTGCCGGAATAC
I have completed it using the lambda expression but I want it without lambda expression. 我已经使用lambda表达式完成了它,但是我希望它没有lambda表达式。
from itertools import *
print min((reduce(lambda s,w:(w+s[max(i*(s[:i]==w[-i:])for i in range(99)):],s)[w in s],p)
for p in permutations(input())),key=len)
I tried it without using lambda expression and got wrong output. 我在未使用lambda表达式的情况下进行了尝试,但输出错误。
from itertools import permutations
def solve(*strings):
"""
Given a list of strings, return the shortest string that contains them all.
"""
return min((simplify(p) for p in permutations(strings)), key=len)
def prefixes(s):
"""
Return a list of all the prefixes of the given string (including itself), in ascending order (from shortest to longest).
"""
return [s[:i+1] for i in range(len(s))]
return [(i,s[:i+1]) for i in range(len(s))][::-1]
def simplify(strings):
"""
Given a list of strings, concatenate them wile removing overlaps between
successive elements.
"""
ret = ''
for s in strings:
if s in ret:
break
for i, prefix in reversed(list(enumerate(prefixes(s)))):
if ret.endswith(prefix):
ret += s[i+1:]
break
else:
ret += s
return ret
print solve('ATTAGACCTG', 'CCTGCCGGAA', 'AGACCTGCCG', 'GCCGGAATAC')
My wrong output: 我的错误输出:
ATTAGACCTGCCGGAA
Looks as though 看起来好像
if s in ret:
break
should be 应该
if s in ret:
continue
Think that will fix it. 认为可以解决问题。
Also the second return statement is surplus - doesn't it simulate reversed(list(enumerate(prefixes(s))))
anyway? 另外,第二个return语句是多余的-难道它不模拟reversed(list(enumerate(prefixes(s))))
吗?
Finally, I think I prefer your initial map-reduce solution! 最后,我想我更喜欢您的初始map-reduce解决方案!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.