In: Computer Science
Write a recursive function, max_in_list(my_list), which takes an non-empty list, my_list, of integers as a parameter. This function calculates and returns the largest value in the list. The base case will probably deal with the scenario where the list has just one value. The recursive case will probably call the function recursively using the original list, but with one item removed.
Note: This function has to be recursive; you are not allowed to use loops to solve this problem!
Test | Result |
---|---|
lst = [1, 4, 5, 9] print(max_in_list(lst)) |
9 |
And
Write a recursive function, max_even_list(my_list), which takes a list, my_list, of integers as a parameter. This function calculates and returns the largest even number in the list. 0 is returned if there is no even number in the list.
Note: This function has to be recursive; you are not allowed to use loops to solve this problem!
Test | Result |
---|---|
lst = [1, 4, 5, 9] print(max_even_list(lst)) |
4 |
Answer 1:
def max_in_list(myList):
if len(myList) == 1:
return myList[0]
else:
max = max_in_list(myList[1:])
if myList[0] > max:
return myList[0]
else:
return max
lst = [1, 4, 5, 9]
print(max_in_list(lst))
def max_in_list(myList):
if len(myList) == 1 :
#return if it is even only
if(myList[0]%2==0):
return myList[0]
else:
return -1
else:
max = max_in_list(myList[1:])
if myList[0] > max and myList[0]%2==0:
return myList[0]
else:
return max
lst = [1, 4, 5, 9]
print(max_in_list(lst))
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me