python - Recursively finding the maximum value in a tuple of mixed types -


i writing function recursively finds maximum value in tuple may contain more tuples or lists. code tracks result, after each recursive call finished, max value sub-list or sub-tuple returned.

how can change global max returned? tried appending values list @ end of each recursive call, not return values @ end.

currently returns 4, 6, 10, , 20 using sample data, want return 20 @ end. edit: code works, append each answer list "result" , return max of "result" @ end.

def maxintuple(t):     results=[]     maxval =0     _max_val(t, maxval, results)     return max(results)  def _max_val(t, maxval, results):     c in t:         if type(c) != int:             _max_val(c, maxval, results)         elif c > result             result =c     results.append(ans)      #return ans  print ( maxintuple(([2, 3, 4], (5, 6), [10, [4, 20]]))) 

here did fix code:

def maxintuple(t):     result = 0     result = _max_val(t, result)     return result def _max_val(t, highest):     c in t:         if type(c) != int:             highest = _max_val(c, highest)         else:             if c > highest:                 highest = c     return highest  print(maxintuple(([2, 3, 4], (5,6),[10,[4,20]]))) 

what did:

had maxintuple function return result got _max_val function. second variable passed _max_val function 0 in case. in _max_val function if wasn't int set highest equal _max_val subset was, example in [2,3,4] make highest = 4. otherwise if c int tested if c > highest, meaning highest changed when c bigger. then, once has finished looping through that, return highest value, in case 20, set result in maxintuple() function, result returned, printed.


Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -