首页 > 解决方案 > 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初学者!

标签: 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)

推荐阅读