所以我有这种递归算法(用于学术练习),并希望绘制其时间复杂度。
def strToInt(s):
if s:
return (ord(s[-1]) - ord('0')) + 10 * strToInt(s[:-1])
else:
return 0
如何在Python 3中绘制它?我确实尝试过,但想出了一个非常不规则和起伏的图表,这个图表并不符合任何已知的时间复杂度。
这就是我现在得到的
以下是我用来计算时间的代码:
from matplotlib import pyplot
import numpy as np
import timeit
from functools import partial
import random
def strToInt(s):
if s:
return (ord(s[-1]) - ord('0')) + 10 * strToInt(s[:-1])
else:
return 0
def plotTC(fn, nMin, nMax, nInc, nTests):
"""
Run timer and plot time complexity
"""
x = []
y = []
for i in range(nMin, nMax, nInc):
N = i
testNTimer = timeit.Timer(partial(fn, N))
t = testNTimer.timeit(number=nTests)
x.append(i)
y.append(t)
p1 = pyplot.plot(x, y, 'o')
#pyplot.legend([p1,], [fn.__name__, ])
# main() function
def main():
print('Analyzing Algorithms...')
plotTC(stringToInt, 10, 10000, 10, 10)
# enable this in case you want to set y axis limits
#pyplot.ylim((-0.1, 0.5))
# show plot
pyplot.show()
# call main
if __name__ == '__main__':
main()