# Define a procedure, find_last, that takes as input
# two strings, a search string and a target string,
# and returns the last position in the search string
# where the target string appears, or -1 if there
# are no occurrences.
#
# Example: find_last('aaaa', 'a') returns 3
# Make sure your procedure has a return statement.
def find_last(string,str):
last_position=-1
while True:
position=string.find(str,last_position+1)
if position==-1:
return last_position
last_position=position
#print find_last('aaaa', 'a')
#>>> 3
#print find_last('aaaaa', 'aa')
#>>> 3
#print find_last('aaaa', 'b')
#>>> -1
#print find_last("111111111", "1")
#>>> 8
#print find_last("222222222", "")
#>>> 9
#print find_last("", "3")
#>>> -1
#print find_last("", "")
#>>> 0
# two strings, a search string and a target string,
# and returns the last position in the search string
# where the target string appears, or -1 if there
# are no occurrences.
#
# Example: find_last('aaaa', 'a') returns 3
# Make sure your procedure has a return statement.
def find_last(string,str):
last_position=-1
while True:
position=string.find(str,last_position+1)
if position==-1:
return last_position
last_position=position
不能返回position,因为position最终可能是-1.我们要返回最后一个目标出现的位置,应该返回last_position,因为他是前一个position的有效位置传递。当position为-1时,last_position保存了上一个position有效位置。这里先定义last_position初值为-1,从第一个(位置为0)字符开始查询,当没有一个目标位置被检索到时直接返回-1,否则从这个目标的下一个位置继续检索,直到position为-1或者检索结束为止。
下面是测试:
#print find_last('aaaa', 'a')
#>>> 3
#print find_last('aaaaa', 'aa')
#>>> 3
#print find_last('aaaa', 'b')
#>>> -1
#print find_last("111111111", "1")
#>>> 8
#print find_last("222222222", "")
#>>> 9
#print find_last("", "3")
#>>> -1
#print find_last("", "")
#>>> 0