对 Niklas B. 评论的长篇回应:
我决定对此进行测试,结果如下。蓝点是你的功能,绿色是马里奥的;y 轴是以秒为单位的运行时间,x 轴是 len(nums)。
正如你所说,两者都是O(n)。你的速度更快,最多可达 45 项;对于超过 100 个项目,他的速度大约是其两倍。
这几乎是无关紧要的——这似乎更像是一个初学者的语法问题——而且,正如你所说,Python 一开始就不是速度恶魔。另一方面,谁不喜欢更快的速度(只要可读性不受影响)?
对于那些感兴趣的人,这是我为测试而编写的代码:
from random import randint
from timeit import Timer
import matplotlib.pyplot as plt
def gt1(nums, n):
# based on Niklas B.'s answer - NOTE comparison is corrected
return n < max(nums)
def gt2(nums, n):
# based on Mario Fernandez's answer
return any(e > n for e in nums)
def make_data(length, lo=0, hi=None):
if hi is None:
hi = lo + length - 1
elif lo > hi:
lo,hi = hi,lo
return [randint(lo, hi) for i in xrange(length)]
def make_args(d):
nums = make_data(d)
n = randint(0,d)
return "{}, {}".format(nums, n)
def time_functions(fns, domain, make_args, reps=10, number=10):
fns = [fn.__name__ if callable(fn) else fn for fn in fns]
data = [[] for fn in fns]
for d in domain:
for r in xrange(reps):
args = make_args(d)
for i,fn in enumerate(fns):
timer = Timer(
setup='from __main__ import {}'.format(fn),
stmt='{}({})'.format(fn, make_args(d))
)
data[i].extend((d,res) for res in timer.repeat(number=number))
return data
def plot_data(data, formats=None):
fig = plt.figure()
ax = fig.add_subplot(111)
if formats is None:
for d in data:
ax.plot([x for x,y in d], [y for x,y in d])
else:
for d,f in zip(data, formats):
ax.plot([x for x,y in d], [y for x,y in d], f)
plt.show()
def main():
data = time_functions([gt1, gt2], xrange(10, 501, 10), make_args)
plot_data(data, ['bo', 'g.'])
if __name__=="__main__":
main()