Skip to content

Instantly share code, notes, and snippets.

@niftycode
Last active October 12, 2024 07:41
Show Gist options
  • Save niftycode/917bb33be4e91a10b1fffd020f987f94 to your computer and use it in GitHub Desktop.
Save niftycode/917bb33be4e91a10b1fffd020f987f94 to your computer and use it in GitHub Desktop.
big-o-notation graph with Python3
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
MIT License
Copyright (c) 2016-2024 Bodo Schönfeld
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
big-o-notation.py:
Version: 0.2
Python 3.6
Date created: 22/03/2017
'''
# Big-O Name
# 1 Constant
# log(n) Logarithmic
# n Linear
# nlog(n) Log Linear
# n^2 Quadratic
# n^3 Cubic
# 2^n Exponential
import numpy as np
import matplotlib.pyplot as plt
# Stylesheets defined in Matplotlib
plt.style.use('bmh')
# Set up runtime comparisons
n = np.linspace(1, 10, 1000)
labels = ['Constant', 'Logarithmic', 'Linear', 'Log Linear', 'Quadratic', 'Cubic', 'Exponential']
big_o = [np.ones(n.shape), np.log(n), n, n * np.log(n), n**2, n**3, 2**n]
# Plot setup
plt.figure(figsize=(12, 10))
plt.ylim(0, 50)
for i in range(len(big_o)):
plt.plot(n, big_o[i], label=labels[i])
plt.legend(loc=0)
plt.ylabel('Relative Runtime')
plt.xlabel('Input Size')
plt.savefig('big-o-notation.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment