Data Structures & Algorithms in Python | by Papa Moryba Kouate | Towards Data Science

To develop a complete mind: Study the science of art; Study the art of science. Learn how to see. Realize that everything connects to everything else.
Leonardo da Vinci
The purpose of this article is to give you a panorama of data structures and algorithms in Python. This topic is very important for a Data Scientist in order to help him or her to design and solve machine learning models in a more effective way.
We will see together with practical examples the built-in data structures, the user-defined data structures, and last but not least I will introduce you to some algorithms like traversal algorithms, sorting algorithms, and searching algorithms.
So, let’s get started!
As the name suggests, data structures allow us to organize, store, and manage data for efficient access and modification.
In this part, we are going to take a look at built-in data structures. There are four types of built-in data structures in Python: list, tuple, set, and dictionary.
List
A list is defined using square brackets and holds data that is separated by commas. The list is mutable and ordered. It can contain a mix of different data types.
out:
january['january', 'february', 'march', 'april', 'may', 'june', 'july']['birthday', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
Below there are some useful functions for the list.
out:
Whatisyourfavouritepainting?Who-is-your-favourite-artist-?
out:
['Chagall', 'Kandinskij', 'Dalí', 'da Vinci', 'Picasso', 'Warhol', 'Basquiat']
Tuple
A tuple is another container. It is a data type for immutable ordered sequences of elements. Immutable because you can’t add and remove elements from tuples, or sort them in place.
out:
The dimensions are 7 x 3 x 1
Set
Set is a mutable and unordered collection of unique elements. It can permit us to remove duplicate quickly from a list.
out:
{1, 2, 3, 5, 6}FalseBasquiat
Dictionary
Dictionary is a mutable and unordered data structure. It permits storing a pair of items (i.e. keys and values).
As the example below shows, in the dictionary, it is possible to include containers into other containers to create compound data structures.
out:
In a Sentimental MoodLacrimosa
Now I will introduce you three user-defined data structures: ques, stack, and tree. I assume that you have a basic knowledge of classes and functions.
Stack using arrays
The stack is a linear data structure where elements are arranged sequentially. It follows the mechanism L.I.F.O which means last in first out. So, the last element inserted will be removed as the first. The operations are:
Push → inserting an element into the stack
Pop → deleting an element from the stack
The conditions to check:
overflow condition → this condition occurs when we try to put one more element into a stack that is already having maximum elements.
underflow condition →this condition occurs when we try to delete an element from an empty stack.
out:
5True[10, 23, 25, 27, 11]overflow1127252310underflow
Queue using arrays
The queue is a linear data structure where elements are in a sequential manner. It follows the F.I.F.O mechanism that means first in first out. Think when you go to the cinema with your friends, as you can imagine the first of you that give the ticket is also the first that step out of the line. The mechanism of the queue is the same.
Below the aspects that characterize a queue.
Two ends:
front → points to starting element
rear → points to the last element
There are two operations:
enqueue → inserting an element into the queue. It will be done at the rear.
dequeue → deleting an element from the queue. It will be done at the front.
There are two conditions:
overflow → insertion into a queue that is full
underflow → deletion from the empty queue
out:
[2, 3, 4, 5][3, 4, 5]
Tree (general tree)
Trees are used to define hierarchy. It starts with the root node and goes further down, the last nodes are called child nodes.
In this article, I focus on the binary tree. The binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child. Below you can see a representation and an example of the binary tree with python where I constructed a class called Node and the objects that represent the different nodes( A, B, C, D, and E).
Anyway, there are other user-defined data structures like linked lists and graphs.
The concept of the algorithm has existed since antiquity. In fact, the ancient Egyptians used algorithms to solve their problems. Then they taught this approach to the Greeks.
The word algorithm derives itself from the 9th-century Persian mathematician Muḥammad ibn Mūsā al-Khwārizmī, whose name was Latinized as Algorithmi. Al-Khwārizmī was also an astronomer, geographer, and a scholar in the House of Wisdom in Baghdad.
As you already know algorithms are instructions that are formulated in a finite and sequential order to solve problems.
When we write an algorithm, we have to know what is the exact problem, determine where we need to start and stop and formulate the intermediate steps.
There are three main approaches to solve algorithms:
Divide et Impera (also known as divide and conquer) → it divides the problem into sub-parts and solves each one separately
Dynamic programming → it divides the problem into sub-parts remembers the results of the sub-parts and applies it to similar ones
Greedy algorithms → involve taking the easiest step while solving a problem without worrying about the complexity of the future steps
Tree Traversal Algorithm
Trees in python are non-linear data structures. They are characterized by roots and nodes. I take the class I constructed before for the binary tree.
Tree Traversal refers to visiting each node present in the tree exactly once, in order to update or check them.
There are three types of tree traversals:
In-order traversal → refers to visiting the left node, followed by the root and then the right nodes.
Here D is the leftmost node where the nearest root is B. The right of root B is E. Now the left sub-tree is completed, so I move towards the root node A and then to node C.
out:
DBEAC
Pre-order traversal → refers to visiting the root node followed by the left nodes and then the right nodes.
In this case, I move to the root node A and then to the left child node B and to the sub child node D. After that I can go to the nodes E and then C.
out:
ABDEC
Post-order traversal → refers to visiting the left nodes followed by the right nodes and then the root node
I go to the most left node which is D and then to the right node E. Then, I can go from the left node B to the right node C. Finally, I move towards the root node A.
out:
DEBCA
Sorting Algorithm
The sorting algorithm is used to sort data in some given order. It can be classified in Merge Sort and Bubble Sort.
Merge Sort → it follows the divide et Impera rule. The given list is first divided into smaller lists and compares adjacent lists and then, reorders them in the desired sequence. So, in summary from unordered elements as input, we need to have ordered elements as output. Below, the code with each step described.
out:
input - unordered elements: 15 1 19 93output - ordered elements: [1, 15, 19, 93]
Bubble Sort → it first compares and then sorts adjacent elements if they are not in the specified order.
out:
[1, 3, 9, 15]
Insertion Sort → it picks one item of a given list at the time and places it at the exact spot where it is to be placed.
out:
[1, 3, 9, 15]
There are other Sorting Algorithms like Selection Sort and Shell Sort.
Searching Algorithms
Searching algorithms are used to seek for some elements present in a given dataset. There are many types of search algorithms such as Linear Search, Binary Search, Exponential Search, Interpolation Search, and so on. In this section, we will see the Linear Search and Binary Search.
Linear Search → in a single-dimensional array we have to search a particular key element. The input is the group of elements and the key element that we want to find. So, we have to compare the key element with each element of the group. In the following code, I try to seek element 27 in our list.
out:
'not fund'
Binary Search → in this algorithm, we assume that the list is in ascending order. So, if the value of the search key is less than the element in the middle of the list, we narrow the interval to the lower half. Otherwise, we narrow to the upper half. We continue our check until the value is found or the list is empty.
out:
FalseTrue
Now you have an overview of data structures and algorithms. So, you can start going to a deeper understanding of algorithms.
The beautiful image of the Vitruvian Man I have chosen for this article is not casual. The drawing is based on the correlation of the ideal human body in relation to geometry. In fact, for this representation, Leonardo da Vinci was inspired by Vitruvius who described the man’s body as the ideal body to determine the correct proportion in architecture.
For what concerns algorithms, the Vitruvian Man hides a secret algorithm used by the artists for centuries to certify that their works were inspired by the divine proportion.
Sometimes I like to think that maybe Leonardo da Vinci, through his wonderful works, wanted to define the most important algorithm which is the algorithm of life.
Thanks for reading this. There are some other ways you can keep in touch with me and follow my work:
Subscribe to my newsletter.
You can also get in touch via my Telegram group, Data Science for Beginners.