gpt4 book ai didi

Python While 循环 - 变量未更新?

转载 作者:太空宇宙 更新时间:2023-11-03 17:16:50 24 4
gpt4 key购买 nike

此代码只是在另一个字符串中查找一个字符串,并返回搜索字符串中出现的最后一个位置,如果未找到,则返回 -1。

考虑到 posnext_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))

关于Python While 循环 - 变量未更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33588406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com