3

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:

Graphic

William Studart
  • 321
  • 1
  • 3
  • 12

1 Answers1

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)

graph 1

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())

graph 2

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