【python】Python面試題:求列表當中最大的三個元素

在牛客網https://www.nowcoder.com/上刷題遇到如何從list中取得最大的三個值:自己寫的方法複雜度太高,放上大牛的方法,複雜度很低。看了好幾遍才體會到大概的精髓。

 

'''
從list中取出最大的三個值
__author__:無名
'''
 
 
def FindList3MaxNum(foo):
    max1, max2, max3 = None, None, None
 
    for num in foo:
        if max1 is None or max1 < num:
            max1, num = num, max1
        if num is None:
            continue
        if max2 is None or num > max2:
            max2, num = num, max2
        if num is None:
            continue
        if max3 is None or num > max3:
            max3 = num
 
    return max1, max2, max3
 
 
if __name__ == '__main__':
    foo = [78, 23, 10, 56, 4, 103, 89, 14]
    max1, max2, max3 = FindList3MaxNum(foo)
    print(max1, max2, max3)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章