我试图找到一种最快的方法来计算以下三个函数中一个月的天数。
def f1():
t=time.time()
for month in range(1,13):
for year in range(10001):
leap_year=(year%4==0 and year%100!=0) or year%400==0
n=[29,31,28,31,30,31,30,31,31,30,31,30,31][month-2*leap_year*(month==2)]
return time.time()-t1
def f2():
t=time.time()
for month in range(1,13):
for year in range(10001):
leap_year=(year%4==0 and year%100!=0) or year%400==0
n=[31,28,31,30,31,30,31,31,30,31,30,31][month-1]+leap_year*(month==2)
return time.time()-t
def f3():
t=time.time()
for month in range(1,13):
for year in range(10001):
leap_year=(year%4==0 and year%100!=0) or year%400==0
n={1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}[month]+leap_year*(month==2)
return time.time()-t
print(sum(f1() for i in range(100)))
print(sum(f2() for i in range(100)))
print(sum(f3() for i in range(100)))
我期待带字典的算法速度最快。但是,我得到了这个:
3.7855005264282227
3.625513792037964
9.0009183883667
显然,我错了。有人可以解释为什么dict算法速度最慢?它应该花费最少的时间,O(1),并且列表算法应该采用O(n),这与我得到的结果相矛盾。我是编程新手。谢谢!
答案 0 :(得分:3)
您每次迭代都会构建一个列表/字典。 如果你只构建一次(因为你还没有改变它),f3()方法是最快的,列表和字典的访问时间是O(1)。
def f1():
t=time.time()
m=[29,31,28,31,30,31,30,31,31,30,31,30,31]
for month in range(1,13):
for year in range(10001):
leap_year=(year%4==0 and year%100!=0) or year%400==0
n=m[month-2*leap_year*(month==2)]
return time.time()-t
def f2():
t=time.time()
m=[31,28,31,30,31,30,31,31,30,31,30,31]
for month in range(1,13):
for year in range(10001):
leap_year=(year%4==0 and year%100!=0) or year%400==0
n=m[month-1]+leap_year*(month==2)
return time.time()-t
def f3():
t=time.time()
m={1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
for month in range(1,13):
for year in range(10001):
leap_year=(year%4==0 and year%100!=0) or year%400==0
n=m[month]+leap_year*(month==2)
return time.time()-t
print(sum(f1() for i in range(100)))
print(sum(f2() for i in range(100)))
print(sum(f3() for i in range(100)))