I am trying to write a recursive function in order to find the max integer in a list of list. I know how to write a func for list of ints. Can anyone give me some tips for this?I I am thinking doing it with no Max function. ex. a = [1, [2,3], 4, [[2], 1]] find_max(a) ->4
Asked
Active
Viewed 2,474 times
2 Answers
1
I decided to tackle this with pure recursion, no loops. The following seems to do the trick for me:
def find_max(a_list):
l = len(a_list)
if l > 1: # if there are multiple elements...
l /= 2 # find the midpoint
m1 = find_max(a_list[:l]) # find the max in the first half
m2 = find_max(a_list[l:]) # find the max in the second half
if m1 > m2: # pick between them
return m1
else:
return m2
elif l < 1: # deal with empty lists
return None
else: # we're down to one element...
if isinstance(a_list[0], list): # ...but it may be a list
return find_max(a_list[0]) # if so, find its max
else:
return a_list[0] # otherwise, a single element is trivially the max of its subset
Note that by splitting the subproblems in half rather than reducing by 1, this implementation should be robust against stack overflows even with large lists.
Now revised to deal with empty lists.

pjs
- 18,696
- 4
- 27
- 56
-
its really helpful!!! i was trying to write the function in this way, but i failed. XD – bxlt Feb 21 '16 at 21:40
-
0
You can iterate through your list and call the MAX()
function if data type is a list:
l = [[54,65,464,656,5],[568,49,7,8,4,3,3515],[312,64,598,46]]
def MAX(l):
mx = None
for item in l:
if isinstance(item, list):
tmp = MAX(item)
else:
tmp = item
if mx < tmp:
mx = tmp
return mx

Kenly
- 24,317
- 7
- 44
- 60
-
@bxlt I am glad to help you.Feel free to accept one answer (for the community). – Kenly Feb 21 '16 at 20:35
-
This will return -1 if all the numbers in the list are negative values below -1. – pjs Feb 22 '16 at 12:54
-
@pjs His list contain only positive numbers.Thank you for this observation. – Kenly Feb 22 '16 at 13:06
-
1@WoLy His *example* list contained only positive numbers. His description said "ints", not positive ints. A valid algorithm should deal with all cases. Yours can be fixed, but isn't general as-written. – pjs Feb 22 '16 at 13:08
-
@pjs Thank you for this reply.Please if you have time help us to fix it. – Kenly Feb 22 '16 at 13:48