1

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

我不明白为什么我的变量next_y没有更新,因为它pos是计算的输入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))
4

2 回答 2

1

您不会在 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))
于 2015-11-07T22:20:27.643 回答
0

如评论中所述,如果要更新next_y,则需要明确执行:

while next_y != -1:
    pos = pos + next_y
    next_y = x.find(y, pos + 1)
于 2015-11-07T22:19:29.807 回答