跳到正文

演算法/查詢最大值/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 ))
華夏公益教科書