1

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))
2
  • No, this assumption isn't true: "My thought that is that if I update pos then next_y should also update." You need to explicitly assign to next_y, i.e. next_y = <insert something here> Commented Nov 7, 2015 at 22:15
  • 1
    x.find() returns a number, the result of the computation when you run it. If you want to compute that value again you need to call it again. Commented Nov 7, 2015 at 22:16

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.