Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extreme Pattern for Lists in Python

Tags:

python

I'm supposed to find the smallest value in a list of nodes using the "extreme pattern for nodes." I am not allowed to use the min() function. I think I need to use a loop or recursion of some sort. Here is the "extreme pattern" for arrays:

    largest = items[0]
    for i in range(0,len(items),1):
        if (items[i] > largest):
            largest = items[i]

But this pattern will not work on lists like this one which contains nodes:

    [1, [23, [53, [54, [5, None]]]]]

How do I implement a similar pattern to find the smallest value in a list like the one above?

like image 882
Jared Beach Avatar asked Jun 25 '26 02:06

Jared Beach


2 Answers

def myMin(mylist):
    smallest = float('inf')
    for l in mylist:
        if isinstance(l,list):
            tmp = myMin(l)
            if tmp < smallest:
                smallest = tmp
        elif l < smallest:
            smallest = l
    if smallest == float('inf'):
        return None
    return smallest

Fixed on @Blckknght's comments.

like image 78
aw4lly Avatar answered Jun 26 '26 15:06

aw4lly


curList = items
if curList:
    largest = items[0]
    while curList is not None:
        if (curList[0] > largest):
            largest = curList[0]
        curList = curList[1]
    print largest
like image 21
Faruk Sahin Avatar answered Jun 26 '26 17:06

Faruk Sahin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!