Python While Loop - Variable Not Updating?

扶醉桌前 提交于 2019-12-11 19:39:02

问题


This code simply looks for a string in another string and returns the last postion of the occurance in the search string or -1 if its is not found.

I don't understand why my variable next_y is not updating considering that pos is an input into computation of next_y. My thought that is that if I update pos then next_y should also update. Instead pos gets updated and remains in the loop forever.

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))

回答1:


You don't change the value of next_y in the while loop, so its value isn't updated. Value of next_y is calculated once and compared for ever (or only once). To update this value you should call 'next_y = x.find(y, pos + 1)' in the loop.

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))



回答2:


As mentioned in the comments, if you want to update next_y, you need to do it explicitly:

while next_y != -1:
    pos = pos + next_y
    next_y = x.find(y, pos + 1)


来源:https://stackoverflow.com/questions/33588406/python-while-loop-variable-not-updating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!