【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)


猜你喜欢

转载自blog.51cto.com/14825302/2507000