I have a very interesting assignment for class of Analysis of Algorithms, which I should make a graphic comparison of a famous problem (such as the Knapsack problem) using different approaches, such as Dynamic Programming and Greedy. I wanted to know if there is a library or a tool that I could use to help the visualization (mainly for the time complexity) in Python that I could use. The idea would be a simple graphic, such as the one shown below:
Asked
Active
Viewed 1,524 times
3
-
1I Think [`matplotlib`](http://matplotlib.org/) will be great – ᴀʀᴍᴀɴ Jan 26 '17 at 21:51
1 Answers
3
First, you have to calculate actual time complexity of your algorithm. This can be done either with timeit.timeit
(the actual wall time) or by manually calculating the number of operations.
Here is an example for bubble sort algorithm:
def bubble_sort(a):
not_sorted = True
operations = 0
while not_sorted:
not_sorted = False
for i in range(len(a)-1):
operations += 1
if a[i] > a[i+1]:
a[i], a[i+1] = a[i+1], a[i]
not_sorted = True
return operations
Now you can feed this function with arrays of different sizes, collect the number of operations needed each time and make a graph.
import matplotlib.pyplot as plt
from random import sample
# assuming we are in Jupyter:
%matplotlib inline
ns = range(10, 1000, 10)
ops = []
for n in ns:
my_list = sample(range(n), n)
ops.append(bubble_sort(my_list))
plt.plot(ns, ops)
You can even check the asymptotics with some statistics like this:
from statsmodels.formula.api import ols
import pandas as pd
df = pd.DataFrame(dict(n=ns, ops=ops))
model = ols('ops ~ n + I(n**2)', df)
model = model.fit()
plt.plot(ns, ops)
plt.plot(ns, model.predict())
To find an actual wall time, just use
from timeit import timeit
time = timeit('bubble_sort(a)', number=10, globals=globals())

Ilya V. Schurov
- 7,687
- 2
- 40
- 78
-
Thank you so much, that was a very clear answer that will definitely help me in this assignment! – William Studart Jan 26 '17 at 23:56