0

I am trying to use a program in Python that using recursion return the highest value in a list. If the list does not have any inner lists it works, however if it has inner lists it stops working.

def max_num_in_list(list):
  max = list[0]
  for j in list:
    if j > max:
      max = j
  return max

print(max_num_in_list([5,8,[78,99],98,25]))
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • FYI you shouldn't call a variable `max` or `list` since that shadows built-in names (aka makes them unreachable because you've overwritten them). – Random Davis Dec 07 '21 at 17:38
  • You need to check if `j` is another list. If so, call your function recursively to get its max. – Barmar Dec 07 '21 at 17:39
  • You are asking two questions. 1) How to deal with embedded lists 2) How to use recursion (you're not using recursion like you say). Which do you care about more? Specifically, why does your lists need to have lists within it? – OneCricketeer Dec 07 '21 at 17:44

1 Answers1

0

To check if a variable x is a list, you can use type(x) is list. same goes for int, tuple, float, str, etc.

To recursively call your function, you have to check if each item in the input list is a list, and if so, call your function on that list. The function will eventually return a value; this is the highest value in that list all sub-lists of that list. You can then check if this returned value is greater than the maximum, and then move on to the next item in the input list.

I can provide the code if necessary but since this is a simple exercise I'll leave that up to you, this is all the info you need.

Random Davis
  • 6,662
  • 4
  • 14
  • 24