Python | Visualizing O(n) using Python
Last Updated :
17 Sep, 2019
Introduction
Algorithm complexity can be a difficult concept to grasp, even presented with compelling mathematical arguments. This article presents a tiny Python program that shows the relative complexity of several typical functions. It can be easily adapted to other functions.
Complexity. Why it matters?
Computational complexity is a venerable subject in Computer Science. It can be defined as the amount of time and space that an algorithm needs to solve an instance of a problem.
The underpinnings of computational complexity are mathematical, but its implications very practical. There are problems that are "intractable". They are not impossible (i.e. undecidable) but no efficient algorithm is known for them. That is: they are very difficult to solve with today technology, and even with the foreseeable one.
Usually, worst-case is the best
The most popular analysis in computational complexity is the worst-case scenario. Despite its pessimism, it is very reasonable: the size of the problems willing to be solved increases as time goes. We want to process petabytes of data, instead of megabytes. So, size is an all-important factor in algorithm complexity.
Consider the input size as the independent variable, and the growth rate is the dependent variable, and try to analyze its performance as the input size grows to infinity. This analysis is called
big-Oh and has many rules that you can consult in any good algorithmic textbook. The most important one is that constants do not affect algorithmic performance for large inputs. The reason, again, is that the size of the input is the most important factor and constants do not depend on the input size.
Comparing function growths in Python
Newcomers to the theory of computation often get confused by the fact that exponential functions like
e^{n} are worse than polynomial functions like, say
n^{100}. This is clear from the mathematical definition of the Big-Oh function, but it is not easy to see unless we think that we account for very large
n.
The following Python code visualizes the growth as the problem instance (N) increases of several functions:
log n, n, n^{3}, e^{n}. Note that
n^{3} is considered a bad performance as it takes
10^{9} operations to process 1000 inputs. In general,
n^{k} is considered bad for k>=2.
The code uses the libraries NumPy and MatPlotLib and employs a functional programming technique called currying to compute
n^{k} for constant
k. It is easy to compute other functions by modifying the list FUNCTIONS.
Code : Python code explaining asymptotic behaviour of several functions.
Python3 1==
# Python code that compares the
# asymptotic behaviour of several functions
import numpy as np
import matplotlib.pyplot as plt
# Returns a function that computes x ^ n for a given n
def poly(n):
def polyXN(x):
return x**n
return polyXN
# Functions to compare and colors to use in the graph
FUNCTIONS = [np.log, poly(1), poly(2), poly(3), np.exp]
COLORS = ['c', 'b', 'm', 'y', 'r']
# Plot the graphs
def compareAsymptotic(n):
x = np.arange(1, n, 1)
plt.title('O(n) for n ='+str(n))
for f, c in zip(FUNCTIONS, COLORS):
plt.plot(x, f(x), c)
plt.show()
compareAsymptotic(3)
compareAsymptotic(5)
compareAsymptotic(10)
compareAsymptotic(20)
The results are not surprising: the exponential function has the worst performance, as it grows very quick given the input size. For N=20, the other functions are insignificant compared with the exponential.
The logarithm is shown in cyan, the polynomials in blue, magenta and yellow and the exponential in red.
Similar Reads
Sorting algorithm visualization : Heap Sort
An algorithm like Heap sort can be understood easily by visualizing. In this article, a program that visualizes the Heap Sort Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach: Generate random array and fill the pygame window wi
4 min read
Python String Input Output
In Python, input and output operations are fundamental for interacting with users and displaying results. The input() function is used to gather input from the user and the print() function is used to display output.Input operations in PythonPythonâs input() function allows us to get data from the u
3 min read
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Memory Consumption: Strings vs Lists
Programming memory use is an important consideration, particularly when working with big datasets or resource-intensive programs. Writing effective Python code requires knowing how various data structures affect memory utilization. This article examines how lists and strings use memory differently i
5 min read
Python Program to Swap Two Variables
The task of swapping two variables in Python involves exchanging their values without losing any data . For example, if x = 10 and y = 50, after swapping, x becomes 50 and y becomes 10. Using Tuple UnpackingTuple unpacking is the most efficient method as it eliminates the need for extra memory or te
3 min read
Find the size of a Set in Python
A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Pythonâs set class represents the mathematical notion of a set. The size of a set means the amount of memory (in bytes) occupied by a set object. In this article, we will learn various ways to get th
2 min read
Find the Size of a Tuple in Python
There are several ways to find the "size" of a tuple, depending on whether we are interested in the number of elements or the memory size it occupies. For Example: if we have a tuple like tup = (10, 20, 30, 40, 50), calling len(tup) will return 5, since there are five elements in the tuple.Using len
3 min read
Python for Kids - Fun Tutorial to Learn Python Programming
Python for Kids - Python is an easy-to-understand and good-to-start programming language. In this Python tutorial for kids or beginners, you will learn Python and know why it is a perfect fit for kids to start. Whether the child is interested in building simple games, creating art, or solving puzzle
15+ min read
Python program to find the power of a number using recursion
Given a number N and power P, the task is to find the power of a number ( i.e. NP ) using recursion. Examples: Input: N = 2 , P = 3Output: 8 Input: N = 5 , P = 2Output: 25 Approach: Below is the idea to solve the above problem: The idea is to calculate power of a number 'N' is to multiply that numbe
3 min read
Get Size of a Dictionary - Python
We are given a dictionary in Python and our task is to find the memory size that the dictionary occupies. This can be important when you need to know how much memory your data structures are consuming especially for large dictionaries. For example, if we have a dictionary like this: {'a': 1, 'b': 2,
2 min read