Question: Python Write a function index_last(elem, seq) that takes as inputs an element elem and a sequence seq, and that uses recursion (i.e., that calls itself

Python

Write a function index_last(elem, seq) that takes as inputs an element elem and a sequence seq, and that uses recursion (i.e., that calls itself recursively) to find and return the index of the last occurrence of elem in seq. The sequence seq can be either a list or a string. If seq is a string, elem will be a single-character string; if seq is a list, elem can be any value. Dont forget that the index of the first element in a sequence is 0.

Important notes:

  • If elem is not an element of seq, the function should return -1.

  • You may not use the in operator in this function.

  • Your index_last function must call itself recursively. You must not write a separate helper function to perform the recursion.

Here are some examples:

>>> index_last(5, [4, 10, 5, 3, 7, 5]) result: 5 >>> index_last('hi', ['well', 'hi', 'there']) result: 1 >>> index_last('b', 'banana') result: 0 >>> index_last('n', 'banana') result: 4 >>> index_last('i', 'team') result: -1 >>> index_last('hi', ['hello', 111, True]) result: -1 >>> index_last('a', '') # the empty string result: -1 >>> index_last(42, []) # the empty list result: -1 

Hints:

  • You will need more than one base case for this function.

  • When making the recursive call, it will be helpful to take a different approach than weve typically taken when recursively processing a string. Ask yourself: How could I reduce the problem in such a way that I could easily find the last occurrence of elem in seq?

  • Here again, we encourage you to begin by considering concrete cases. Ask yourself the types of design questions that we have asked in lecture and lab, and use the answers to those questions to determine what the function should do.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!