Could someone teach me how to find the last occurrence of a character in string by using recursion/loop instead of build-in function?
I figured out the loop-method(below), but have no clue about recursion...
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"))
returns 42
Many thanks from a python beginner!!
With iteration:
def find_last(line,ch):
last_seen =-1
for i in range(len(line)):
if line[i] == ch:
last_seen=i
return last_seen
With recursion:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.