Python的max函数的效率如何 [英] How efficient is Python's max function

查看:269
本文介绍了Python的max函数的效率如何的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数max(),它返回列表中的最大元素. . . Big O符号的运行时间是多少(在Python 3中)?

The function max() which returns the maximum element from a list . . . what is its running time (in Python 3) in terms of Big O notation?

推荐答案

它是O(n),因为它必须检查每个元素.如果要获得更好的max性能,可以使用 heapq 模块.但是,您必须取反每个值,因为heapq提供了最小堆.将元素插入堆是O(log n).

It's O(n), since it must check every element. If you want better performance for max, you can use the heapq module. However, you have to negate each value, since heapq provides a min heap. Inserting an element into a heap is O(log n).

这篇关于Python的max函数的效率如何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆