In: Computer Science
Python.
Write a function last_occur(s, e) that takes as inputs a sequence (i.e., a string or list) s and an element e, and that calls itself recursively to find and return the index of the last occurrence of e in s. If s is a string, e will be a single-character string; if s is a list, e can be any value. Don’t forget that the index of the first element in a sequence is 0.
Important notes:
If e is not an element of s, the function should return -1.
You may not use the in operator in this function. In addition, you may not use your num_occur function or any other helper function except the len function.
Your last_occur function must call itself recursively. You must not write a separate helper function to perform the recursion.
#function which returns the last index in s where
s[index]=e
def last_occur(s, e):
#if length of s is 0 then return -1 i.e, not found e
if len(s)==0:
return -1
#if last character/element of s is e then return length of s -
1.
if s[-1]==e:
return len(s)-1
#otherwise call last_occur() recursively for s without last
element/character i.e, s[:-1]
else:
return last_occur(s[:-1], e)
#test case 1
print(last_occur("abcdbefefefeeg","f"))
#test case 2
print(last_occur("abcdbefefefeeg","h"))
#test case 3
print(last_occur([1,2,3,4,5,6,7,6,5,4,3,2,1],"f"))
#test case 4
print(last_occur([1,2,3,4,5,6,7,6,5,4,3,2,1],7))
10
-1
-1
6
CODE and INPUT/OUTPUT
So if you have any doubt regarding this solution then please feel free to ask in the comment section below and if it is helpful then please upvote this solution, THANK YOU.