[英]How to find longest intersection between two strings in python?
I'm trying to write a program that would find the longest intersection between two strings.我正在尝试编写一个程序来找到两个字符串之间最长的交集。 The conditions are:
条件是:
My code has a problem with this last condition, how could I change it so it works as expected?我的代码在这最后一个条件下有问题,我该如何更改它以使其按预期工作?
def intersection(v, w):
if not v or not w:
return ""
x, xs, y, ys = v[0], v[1:], w[0], w[1:]
if x == y:
return x + intersection(xs, ys)
else:
return max(intersection(v, ys), intersection(xs, w), key=len)
print(intersection('programme', 'grammaire'))
cant find the issue with your code, but i solved it like this找不到您的代码的问题,但我这样解决了
def longest_str_intersection(a: str, b: str):
# identify all possible character sequences from str a
seqs = []
for pos1 in range(len(a)):
for pos2 in range(len(a)):
seqs.append(a[pos1:pos2+1])
# remove empty sequences
seqs = [seq for seq in seqs if seq != '']
# find segments in str b
max_len_match = 0
max_match_sequence = ''
for seq in seqs:
if seq in b:
if len(seq) > max_len_match:
max_len_match = len(seq)
max_match_sequence = seq
return max_match_sequence
longest_str_intersection('programme', 'grammaire')
-> 'gramm'
also interested to see if you found a more elegant solution!也有兴趣看看您是否找到了更优雅的解决方案!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.