【发布时间】:2022-08-19 05:04:54
【问题描述】:
我正在尝试实现此功能。看起来很简单,但我的代码失败了,我不知道为什么。
def findall(text,sub):
\"\"\"
Returns the tuple of all positions of substring sub in text.
If sub does not appears anywhere in text, this function returns the empty tuple ().
Examples:
findall(\'how now brown cow\',\'ow\') returns (1, 5, 10, 15)
findall(\'how now brown cow\',\'cat\') returns ()
findall(\'jeeepeeer\',\'ee\') returns (1,2,5,6)
Parameter text: The text to search
Precondition: text is a string
Parameter sub: The substring to search for
Precondition: sub is a nonempty string
\"\"\"
import introcs
result= ()
pos=0
while pos < len(text):
x=text[pos:pos+2]
if x is sub:
result=result+(x, )
pos+1
else:
result=result
pos+1
return result