此代码只是在另一个字符串中查找一个字符串,并返回搜索字符串中出现的最后一个位置,如果未找到,则返回 -1。
考虑到 pos
是 next_y
计算的输入,我不明白为什么我的变量 next_y
没有更新。我的想法是,如果我更新 pos
那么 next_y
也应该更新。相反,pos
会更新并永远保留在循环中。
def find_last(x,y):
if x.find(y) == -1:
return -1
pos = x.find(y)
next_y = x.find(y, pos + 1)
while next_y != -1:
pos = pos + next_y
return pos
search = 'tom ran up but tom fell down'
target = 'tom'
print(find_last(search,target))
您没有在 while 循环中更改 next_y 的值,因此它的值不会更新。 next_y 的值计算一次并永远比较(或仅比较一次)。要更新此值,您应该在循环中调用“next_y = x.find(y, pos + 1)”。
def find_last(x,y):
if x.find(y) == -1:
return -1
pos = x.find(y)
next_y = x.find(y, pos + 1)
while next_y != -1:
pos = pos + next_y
next_y = x.find(y, pos + 1)
return pos
search = 'tom ran up but tom fell down'
target = 'tom'
print(find_last(search,target))
我是一名优秀的程序员,十分优秀!