我应该使用“节点的极端模式”在节点列表中找到最小值。我不能使用min()
功能。我想我需要使用某种循环或递归。这是数组的“极端模式”:
largest = items[0]
for i in range(0,len(items),1):
if (items[i] > largest):
largest = items[i]
但是这种模式不适用于包含节点的列表:
[1, [23, [53, [54, [5, None]]]]]
如何实现类似的模式来查找列表中的最小值?如上所示?
答案 0 :(得分:3)
curList = items
if curList:
largest = items[0]
while curList is not None:
if (curList[0] > largest):
largest = curList[0]
curList = curList[1]
print largest
答案 1 :(得分:3)
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
修正了@ Blckknght的评论。
答案 2 :(得分:1)
这是@ aw4lly的答案的变体,它将在Python 3中起作用。
def myMin(lst):
smallest = None
for i in lst:
if isinstance(i, list):
i = myMin(i)
if smallest is None or i is not None and i < smallest:
smallest = i
return smallest
这可以处理任何类型的嵌套列表,包括部分或完全为空的列表(出于我们的目的,空列表是除了其他“空”列表之外没有成员的列表)。空列表返回None
作为最小值,这与Python的标准min
函数不完全相同(但它使递归更容易)。
>>> print(myMin([1, 2, 3, [4, [5], [], 0, [6, 7]], [[8], 9]]))
0
>>> print(myMin([[[],[[],[],[[],[]],]],[],[[]]]))
None
答案 3 :(得分:1)
car = lambda lst: lst[0] # value
cdr = lambda lst: lst[1] # next list
lst = items
if lst: # not empty
largest = car(lst)
while lst is not None:
if largest < car(lst):
largest = car(lst)
lst = cdr(lst)
print(largest)