python/numpy versatile max function -
in python (possibly including numpy) there various maximum
, max
, amax
functions, extent covered in stackoverflow questions, none of them seems solve rather obvious need of computing the maximum of mixed arguments, i.e. matching following requirements:
- any argument iterable (tuple, list, numpy array) or number
- ... , recursively, i.e. iterable in turn contain numbers , iterables
- iterables turning out empty, , none items, should not affect max
- only if arguments empty output should given default
- if arguments contain nan, should propagated (i think automatic)
i seeking solution versatile, compact , proper pythonic point of view.
nb. tried code myself little success. not attach many attempts because ugly, , don't work either, , above all, believe misleading , time waste of possibly can help. question long.
anyway, here 1 of attempts, doesn't work:
<!-- language: python --> def flexmax1(aa): ''' works on 1 argument, breaks into: - empties: eliminated - single numbers: replace max (or none) - iterables (if any): deal recursively, don't forget add prev calc max ''' # progressively replaces iterables max (or none if no iterables) m=none while aa: if m not none: aa=aa.append(m) # eliminates empties , none, preserves true zeros aa= [a in aa if or a==0] try: # max of non iterables m=max( in aa if not iterable(a) ) except valueerror: # empty sequence # there weren't bare numbers, iterables, reduce them aa=[ flexmax1(a) in aa if iterable(a) ] else: # same, append max of iterables aa=[ (flexmax1(a)) in aa if iterable(a) ] return m if __name__ == '__main__': print(flexmax1([1])) print(flexmax1([1,2])) print(flexmax1([1,[2,3]]))
ps. know that, standpoint, maximum of items should 1 of items, , solved using max
's key=function
optional argument. need return overall maximum number
you can first flatten down , compute max of that:
import collections def flatted(data): if isinstance(data, collections.iterable): element in data: yield flatted(data) else: yield data def versatile_max(data, max_function=max): max_function(flatted(data))
Comments
Post a Comment