Question: Python Write a function index(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(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 first 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 function must call itself recursively. You must not write a separate helper function to perform the recursion.
Here are some examples:
>>> index(5, [4, 10, 5, 3, 7, 5]) result: 2 >>> index('hi', ['well', 'hi', 'there']) result: 1 >>> index('b', 'banana') result: 0 >>> index('a', 'banana') result: 1 >>> index('i', 'team') result: -1 >>> index('hi', ['hello', 111, True]) result: -1 >>> index('a', '') # the empty string result: -1 >>> index(42, []) # the empty list result: -1
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
