算法/查找最大值/Python 方法 1
外观
Python (2.7 和 3.6) 源代码。该代码需要检阅。
def findmax(a):
if len(a) == 0:
return 0
curr_max = a[0]
for i in a:
if i > curr_max:
curr_max = i
return curr_max
函数的使用示例
print(findmax([12, 13, 555, 124, 342]))
输出应为:555
该算法的另一种实现
def imax( iterable, key=lambda x: x ):
"""returns largest item, as input could take iterator or sequence
"key" function will be applied on every item, before comparison is made
>>> imax( [12,3,4, 89, 90,88] )
90
"""
current_max = None
for x in iterable:
if current_max is None or key(x) > key( current_max ):
current_max = x
return current_max
函数的使用示例
print(imax( [12, 13, 555, 124, 342] ))
print(imax( [12, 13, 555, 124, 342], lambda x: 1.0/x ))