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?
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.
curList = items
if curList:
largest = items[0]
while curList is not None:
if (curList[0] > largest):
largest = curList[0]
curList = curList[1]
print largest
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With