user18457
user18457

Reputation: 29

Least value in nested list

i am thinking to write a program to find the least value in nested list, return the value in same list format

Input

ip = [[[5,4,7],[4,2,1],[1,9,5,4]],[[3,5],[6,5,2]],[2,5,3,7]]

output

op =[[[4], [[1]] , [[1]] ],[[3],[2]],[2]]

i wrote a function which can identify least value from the provided list

def smallest_num_in_list( list ):

    min = list[ 0 ]
    for a in list:
        if a < min:
            min = a
    return min 

this works for normal list now i am trying to write some logic for nested list where i lost

i am trying to create something like this enter image description here please some shed some light on me :-)

thank you

Upvotes: 0

Views: 99

Answers (3)

Tomerikoo
Tomerikoo

Reputation: 19395

Because you don't know exactly how much levels to go each time, recurssion might be a natural selection here.

From here we need the step and the stop condition. I guess they are pretty obvious in that point: The step would be to go down one list level each time, while the stopping condition will be when we reach a "leaf" list - one that has no more nested lists.

In order to detect such list we can use error handling:

def minimize(l):
    try:
        return [minimize(elem) for elem in l]
    except TypeError:
        return [min(l)]

This function iterates on the elements of its list argument and tries to add the recursive call to the result. When we make the recursive call on a leaf list, this call will fail because the elements are not iterable. This will throw us one level up to the leaf list and we return the least value.

This means that this function will work on any number of nesting, even a flat list:

>>> minimize([[[5,4,7],[4,2,1],[1,9,5,4]],[[3,5],[6,5,2]],[2,5,3,7]])
[[[4], [1], [1]], [[3], [2]], [2]]

>>> minimize([5, 4, 3, 2, 1])
[1]

Upvotes: 0

rpoleski
rpoleski

Reputation: 998

Maybe this is what you want:

def fun(in_list):
    if set([type(x) for x in in_list]) == {list}:
        return [fun(x) for x in in_list]
    else:
        return [min(in_list)]

ip = [[[5,4,7],[4,2,1],[1,9,5,4]],[[3,5],[6,5,2]],[2,5,3,7]]

print(fun(ip))
[[[4], [1], [1]], [[3], [2]], [2]]

Upvotes: 1

Renaud
Renaud

Reputation: 2819

I think something like that:

 def inspectList(originalList) :
     ResultList=[] 
     for listItem in originalList:
          if isinstance(listItem, list) :
               MinVal=inspectList(listItem) 
               ResultList.append(MinVal)
          else:
               return min(listItem) 
      return ResultList


 ip = [[[5,4,7],[4,2,1],[1,9,5,4]],[[3,5],[6,5,2]],[2,5,3,7]]
 result =inspectList(ip)
 print(result) 

Upvotes: 0

Related Questions