Question
Write a function index(elem, seq) that takes as inputs an element elem and a sequence seq, and that uses a loop to find and return
Write a function index(elem, seq) that takes as inputs an element elem and a sequence seq, and that uses a loop 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. YOU MUST ONLY USE LOOP
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 to test for the presence of elem in seq. (However, you are welcome to use in as part of the header of a for loop.) In addition, you may not use any built-in methods (i.e., functions like find or index that are found inside of string or list objects). However, you may use built-in functions like len and range.
Here are some examples:
>>> index(5, [4, 10, 8, 5, 3, 5]) 3 >>> index('hi', ['well', 'hi', 'there']) 1 >>> index('b', 'banana') 0 >>> index('a', 'banana') 1 >>> print(index('n', 'banana')) 2 >>> index('i', 'team') -1 >>> index(8, [4, 10, 5, 3]) -1
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started