数据结构Python实现-输出从1-N的正整数
第一种办法就是循环顺出
第二种可以使用迭代
def printN(N):
if N>0:
printN(N-1);
print(N);
N=10
printN(N)
输出结果:1,2,3,4,5,6,7,8,9,10
若:
def printN(N):
if N>0:
print(N);
printN(N-1);
N=10
printN(N)
输出结果:10,9,8,7,6,5,4,3,2,1
这里导入Python的time模块来测试递归和循环的运行时间。
from datetime import datetime
begin = datetime.now() # 获取当前datetime
beg_stamp=begin.timestamp() # 把datetime转换为timestamp
def printN(N):
if N>0:
printN(N-1);
print(N);
N=1000
printN(N)
end = datetime.now() # 获取当前datetime
end_stamp=end.timestamp() # 把datetime转换为timestamp
print(end_stamp-beg_stamp)
运行时间为:0.17701101303100586
同理,循环的运行时间为:0.20501112937927246
可见递归的运行时间更短。
注意:Python默认的递归深度为1000,太大的话会报错RecursionError: maximum recursion depth exceeded in comparison