关于python函数重叠的问题
编写函数overlapping(start, end),对于两个给定的字符串,确定开始结束的字符与结束开始的字符重叠的数量。例如,“hell”和“llo”的重叠为 2,因为第一个以“ll”结尾,第二个以“ll”开头。更多示例在下面的测试单元中。我写的:
def overlapping(start, end):
prefits=set()
postfits=set()
prefitt=set()
postfitt=set()
for i in range(1,len(start)+1):
prefits.add(start[:i])
for i in range(len(start)):
postfits.add(start)
for i in range(1,len(end)+1):
prefitt.add(end[:i])
for i in range(len(end)):
postfitt.add(end)
result=list((prefits&postfitt)|(postfits&prefitt))
if len(result)==0:
return 0
else:
max_overlap=result
max_length=len(result)
for i in range(len(result)):
if len(result)>max_length:
max_length=len(result)
max_overlap=result
return len(max_overlap)
测试:
assert overlapping("hell", "llo") == 2
assert overlapping("abracadabra", "abrasive") == 4
assert overlapping("hello", "goodbye") == 0
assert overlapping("hello", "hell") == 0
assert overlapping("hell", "smell") == 0
请问测试我这个为什么是错的 有start和end之分这里不能为4
>>> overlapping("hello", "hell")
4 你为什么会用集合呢? 集合里元素是唯一的、是去重复的!
>>> set(list('hell'))
{'l', 'e', 'h'}
>>> set(list('hell')) | set(list('lloo'))
{'l', 'e', 'o', 'h'}
>>> set(list('hell')) & set(list('lloo'))
{'l'}
>>>
根据题意,你只需要分别对两个字符串切片(切尾,切头),
切1个 比较看是否相等,相等 就计数器+1,然后继续切到第二个字符,直到不相等而停止。
比如:
>>> s1, s2 = 'hell', 'lloo'
>>> def overlap(s1, s2):
cnt = 0
for i in range(len(s1)):
if s1[-(i+1):] == s2[:i+1]:
cnt += 1
else:
break
return cnt
>>> overlap(s1, s2)
2
>>> overlap('hello', 'good')
0
>>> 看了一下你的需求,是 第一个字符 结束的字符 和 第二个字符 开始的字符重叠的数量吧
那么只需要两个集合,第一个集合存放第一个字符结束所有的情况第二个集合存放第二个字符开始的所有情况
代码如下:
def overlapping(start, end):
postfits=set()
prefitt=set()
for i in range(len(start)):
postfits.add(start)
for i in range(1,len(end)+1):
prefitt.add(end[:i])
result=list(postfits&prefitt)
if len(result)==0:
return 0
else:
max_overlap=result
max_length=len(result)
for i in range(len(result)):
if len(result)>max_length:
max_length=len(result)
max_overlap=result
return len(max_overlap)
print (overlapping("hell", "llo") == 2)
print (overlapping("abracadabra", "abrasive") == 4)
print (overlapping("hello", "goodbye") == 0)
print (overlapping("hello", "hell") == 0)
print (overlapping("hell", "smell") == 0)
运行结果:
True
True
True
True
True
你的错误在于把第一个字符开始的情况,第二个字符结束的情况也纳入进去了
就导致两个字符开始或者结尾只要有重叠的字符串都会被算进去
页:
[1]