I could suggest separating the unsesting list and reducing min to two separate, well-defined tasks
deepReduce
will reduce the list of lists using the specified reduction functiondeepMin
performs deepReduce
with min
import math
Oh, but you said you want the second smallest number. Recycle this code a bit. Of course, I knew this all the time, but the answer to this question twice allows me to demonstrate the universality of this particular implementation - Changes in bold
def min2 (xs, y): # x1 is the smallest, x2 is second smallest x1, x2 = xs if (y < x1) and (y < x2): return (y, x2) elif y < x2: return (x1, y) else: return (x1, x2) def deepMin 2 (xs): # notice we change to use tuple of math.inf now x1, x2 = deepReduce ( min2 , (math.inf, math.inf ) , xs) return x2 data = [1,2,[7,[6,1,3,[0,4,3]],3,4],2,1] print(deepMin 2 (data)) # 1
I should point out that we donβt need to touch deepReduce
, which is the point - we should be able to do any arbitrary deep operation in our nested list without the need to statically code this behavior in our function.
Now you can write any deep reducer you want and name it with deepReduce
source share