python - Python 3.x -> 使用递归和循环查找字符串中最后出现的字符
问题描述
有人可以教我如何通过使用递归/循环而不是内置函数来查找字符串中最后一次出现的字符吗?
我想出了循环方法(如下),但对递归一无所知......
def find_last(line,ch):
if line == None or len(line)==0:
return -1
else:
found_at = 0
index= 0
for ch_line in line:
if ch_line == ch:
found_at = index
index+=1
return found_at
print(find_last("The quick brown fox jumps over the lazy dog", "g"))
返回 42
非常感谢python初学者!
解决方案
随着迭代:
def find_last(line,ch):
last_seen =-1
for i in range(len(line)):
if line[i] == ch:
last_seen=i
return last_seen
使用递归:
def find_last_rec(line,ch,count):
if count==line(len)-1:
return -1
elif line[count] ==ch:
return max(count, find_last_rec(line,ch,count+1))
else:
return find_last_rec(line,ch,count+1)
def find_last(line,ch):
return find_last_rec(line,ch,0)
推荐阅读
- python - 如何使用正则表达式(Python)提取荷兰邮政编码
- database - 如何根据其他列过滤值?
- c# - 覆盖 CreateMap - Automapper
- javascript - 如何在 event.clientX 鼠标位置 50vw 上显示 div
- tensorflow - 使用具有多个输入的自定义 rnn 单元格的正确方法
- reactjs - 有没有办法通过道具传递接口?
- c# - 不挥发多长时间?在这种情况下我应该使用 volatile 吗?
- python - ModuleNotFoundError:请求参数化查询时没有名为“google”的模块
- python - Cant navigate between different html pages in django
- firebase - How to add a parameter for purchased item to Firebase in_app_purchase event?