Question

Python Write a function index_last(elem, seq) that takes as inputs an element elem and a sequence...

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. Don’t 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 we’ve 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.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Explanation::

  • Code in PYTHON is given below
  • Please read comments for better understanding of the code
  • Output is given at the end of the code

Code in PYTHON::

'''
Base Case 1: First condition we check is if length of seq is 0 or no
    If 0 then we return -1
Base Case 2: Check if last element of the seq is equal to elem.
    If yes then return the index of last element of th seq
Base Case 3: If element in seq is the only one element then we return -1
    as base case 2 is false.
Base Case 4:
    We call the function index_last() recursively by passing
    the elem and seq without last element 
'''
def index_last(elem,seq):
    if len(seq)==0:
        return -1
    elif seq[len(seq)-1]==elem:
        return len(seq)-1
    elif len(seq)-1==0:
        return -1
    else:
        return index_last(elem,seq[0:len(seq)-1])

print(index_last(5,[4,10,5,3,7,5]))
print(index_last('hi',['well','hi','there']))
print(index_last('b','banana'))
print(index_last('n','banana'))
print(index_last('i','team'))
print(index_last('hi',['hello',111,True]))
print(index_last('a',''))
print(index_last(42,[]))

SCREENSHOT OF THE CODE:


OUTPUT:


Please provide the feedback!!

Thank You!!

Add a comment
Know the answer?
Add Answer to:
Python Write a function index_last(elem, seq) that takes as inputs an element elem and a sequence...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • (1) Implement the countKey(T element) method, which should return a count of the number of times...

    (1) Implement the countKey(T element) method, which should return a count of the number of times that the given key (the element) is found in the list. (2) Implement the indexOf(T element) method, which is similar as the indexOf method in the String class. It returns the index (the position starting from the head node) of the first occurrence of the given element, or -1, if the element does not occur in the list. You will need to track the...

  • In python please 6 annoying_int_sequence(n) In annoying_recursion.py, write the function annoying_int_sequence(n) which takes a single integer...

    In python please 6 annoying_int_sequence(n) In annoying_recursion.py, write the function annoying_int_sequence(n) which takes a single integer parameter (which must be non-negative). It must return a list of intgers. The contents of the integers are defined recursively. Basically, each version of this sequence is made up of the next-smaller one, repeated n times - and with the number n in-between. For instance, the sequence for n = 3 is: ???? 3 ???? 3 ???? Just drop in the the sequence for...

  • Write a method called printReverse() that takes a string and uses recursion to print the contents...

    Write a method called printReverse() that takes a string and uses recursion to print the contents of the string in reverse order. The string itself should not be reversed; it must be left in its original form. The method has the following header:   void printReverse(String s, int i) where s is a reference to the string, and i is an integer parameter that you may use as you see fit. You do not need to code up this method as...

  • Write a C++ function, smallestIndex, that takes as parameters an int array and its size and...

    Write a C++ function, smallestIndex, that takes as parameters an int array and its size and returns the index of the first occurrence of the smallest element in the array. To test your function, write a main that prompts a user for a list of 15 integers and outputs the index and value of the first occurrence of the smallest value. The program should print out Enter 15 integers: The position of the first occurrence of the smallest element in...

  • Write a function count_vowels(s) that takes a string as an argument and returns the number of...

    Write a function count_vowels(s) that takes a string as an argument and returns the number of vowels ('a', 'e', 'i' 'o', 'u') in the string. Should you use a for or while loop? (Implement this as a function, not as a class with a method.) Be sure to include unittest test cases to demonstrate that your code works properly, e.g Part 2: last_occurance(target, sequence) Write a function last_occurance(target, sequence) that takes two arguments: 1. target: A target item to find...

  • python 2..fundamentals of python 1.Package Newton’s method for approximating square roots (Case Study 3.6) in a...

    python 2..fundamentals of python 1.Package Newton’s method for approximating square roots (Case Study 3.6) in a function named newton. This function expects the input number as an argument and returns the estimate of its square root. The script should also include a main function that allows the user to compute square roots of inputs until she presses the enter/return key. 2.Convert Newton’s method for approximating square roots in Project 1 to a recursive function named newton. (Hint: The estimate of...

  • Python 2.7 Write a function cumsum() that takes a list l as argument and returns the...

    Python 2.7 Write a function cumsum() that takes a list l as argument and returns the cumulative sum (also known as the prefix sum) of l, which is a list, say cs of the same length as l such that each element cs[i] is equal to the sum of the first i + 1 elements of l, i.e., cs[i] == l[0] + l[1] + l[2] + ... + l[i] You should not modify the argument list l in any way....

  • Write a generic function int find_lower_bound(T seq[], int n, const T& value). The function returns the...

    Write a generic function int find_lower_bound(T seq[], int n, const T& value). The function returns the index of the largest element in the given sequence that is less than the given value. If multiple elements satisfy, return the one with smallest index. Return -1 if no such element exists. //main.cpp #include<iostream> #include<string> #include<vector> #include<algorithm> using namespace std; #include "source.h" struct Point{    int x,y;    bool operator<(const Point& p) {        return (x<p.x || (x==p.x&&y<p.y));    } }; int...

  • Requirements Write functions isMemberR, a recursive function, and isMemberI, which will use an iterative approach, to...

    Requirements Write functions isMemberR, a recursive function, and isMemberI, which will use an iterative approach, to implement a binary search algorithm to determine whether a given element is a member of a given sequence Each function will have two parameters, aseq, a sorted sequence, and target. isMemberR and isMemberI will return True if target is an element of the sequence, and False otherwise. Your implementations must implement the binary search algorithm described above. When function i sMemberR recursively invokes itself,...

  • Problem 1. Write a Python function times_i_at_odd(L) that takes as arguments a list L and returns...

    Problem 1. Write a Python function times_i_at_odd(L) that takes as arguments a list L and returns a list consisting of the elements of L multiplied by the index number of the element at odd positions. (Use list comprehensions) >>> times_i_at_odd([1,2,3,4,5,6,7,8,9,10]) [2, 12, 30, 56, 90] Problem 2. Write a recursive function sum_cols(grid, n) that takes a list of lists of integers grid and integer n and returns the sum of column n in grid. For example, the call sum_cols([[1,2,3,4], [10,20,30,40],...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT