everyone!
I have a following task: "Write a recursive function that uses a list as an argument and returns the maximum value. Non-integer elements are to be ignored!"
I have written the following code:
def recursion(listOne):
if(len(listOne) == 1):
return listOne[0]
else:
maximum = recursion(listOne[1:])
if(isinstance(listOne[0], int)) or (isinstance(listOne[0], float)):
if(maximum > listOne[0]):
return maximum
else:
return listOne[0]
else:
return listOne[0]
listOne = ["apple", 7, 10, (5, 4)]
x = recursion(listOne)
print("Max number in the list is: ", x)
It works for a list containing numbers only; the output says:" Max number in the list is: apple".
I would appreciate if someone were to help me with solving this :)
P.S. I am new at python and come from a C/C background, so please understand my lack of python-specific knowledge.
CodePudding user response:
That's one way to fit the requirements of your task:
def recursion(lst, maxi=float("-inf")):
if len(lst) == 1:
return lst[0] if isinstance(lst[0], int) and lst[0] > maxi else maxi
if isinstance(lst[0], int):
maxi = maxi if maxi > lst[0] else lst[0]
return recursion(lst[1:], maxi)
list_one = ["apple", 7, 10, (5, 4)]
res = recursion(list_one)
print("Max number in the list is: ", res)