Skip to content

Commit 9de99c5

Browse files
author
Flor Silvestre
committed
Data Structures: from lists to maps
1 parent d6a8b78 commit 9de99c5

File tree

9 files changed

+349
-60
lines changed

9 files changed

+349
-60
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
__pycache__/
33
*.py[cod]
44
*$py.class
5+
.vscode
56

67
# C extensions
78
*.so

data-structures/data-structures.md

Lines changed: 87 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ The data in the data structures are processed by certain operations. The particu
2121
* Sorting
2222
* Merging
2323

24-
## Array Data Structure
24+
## [Array](arrays.py)
2525

2626
![Array](assets/array-2.png)
2727

@@ -59,22 +59,6 @@ deletion: O(n)
5959

6060
*Python has a set of built-in methods that you can use on lists/arrays.*
6161

62-
Create:
63-
```
64-
cars = ["Ford", "Volvo", "BMW"]
65-
```
66-
67-
Access element:
68-
```
69-
x = cars[0]
70-
```
71-
72-
Loop:
73-
```
74-
for x in cars:
75-
print(x)
76-
```
77-
7862
| Method | Description |
7963
|:-: | --- |
8064
| append() | Adds an element at the end of the list |
@@ -87,29 +71,87 @@ for x in cars:
8771
| pop() | Removes the element at the specified position |
8872
| remove() | Removes the first item with the specified value |
8973
| reverse() | Reverses the order of the list |
90-
| sort() | Sorts the list |
74+
| sort() | Sorts the list |
75+
76+
## [Matrix](matrix.py)
77+
78+
![Matrix](assets/matrix-9.png)
79+
80+
A matrix represents a collection of numbers arranged in an order of rows and columns. It is necessary to enclose the elements of a matrix in parentheses or brackets.
81+
82+
Matrix is a special case of two dimensional array where each data element is of strictly same size. So every matrix is also a two dimensional array but not vice versa. Matrices are very important data structures for many mathematical and scientific calculations. As we have already discussed two dimnsional array data structure in the previous chapter we will be focusing on data structure operations specific to matrices in this chapter.
83+
84+
We also be using the numpy package for matrix data manipulation.
85+
86+
## [List](lists.py)
87+
88+
It is similar to array with the exception that the data elements can be of different data types. You can have both numeric and string data in a python list.
89+
90+
## [Tuple](tuples.py)
91+
92+
Tuples are similar to lists but they are immutable which means the values in a tuple cannot be modified they can only be read.
93+
94+
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
95+
96+
## [Dictionary](dictionary.py)
97+
98+
The dictionary contains Key-value pairs as its data elements.
99+
100+
In Dictionary each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.
101+
102+
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
103+
104+
- More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins.
105+
106+
- Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed.
107+
108+
## [Sets](sets.py)
109+
110+
Mathematically a set is a collection of items not in any particular order. A Python set is similar to this mathematical definition with below additional conditions.
111+
112+
* The elements in the set cannot be duplicates.
113+
* The elements in the set are immutable(cannot be modified) but the set as a whole is mutable.
114+
* There is no index attached to any element in a python set. So they do not support any indexing or slicing operation.
91115

92-
## Linked list
116+
#### Set Operations
117+
118+
The sets in python are typically used for mathematical operations like union, intersection, difference and complement etc.
119+
120+
We can create a set, access it’s elements and carry out these mathematical operations.
121+
122+
## [Maps](maps.py)
123+
124+
Python Maps also called ChainMap is a type of data structure to manage multiple dictionaries together as one unit. The combined dictionary contains the key and value pairs in a specific sequence eliminating any duplicate keys. The best use of ChainMap is to search through multiple dictionaries at a time and get the proper key-value pair mapping. We also see that these ChainMaps behave as stack data structure.
125+
126+
## [Linked list](linked_lists.py)
93127

94128
![Linked list](assets/Linkedlist.png)
95129

96-
- A **linked list** (also just called *list*) is a linear collection of data elements of any type, called nodes, where each node has itself a value, and points to the next node in the linked list. The principal advantage of a linked list over an array, is that values can always be efficiently inserted and removed without relocating the rest of the list. Certain other operations, such as random access to a certain element, are however slower on lists than on arrays.
130+
- A **linked list** is a linear collection of data elements of any type, called nodes, where each node has itself a value, and points to the next node in the linked list. The principal advantage of a linked list over an array, is that values can always be efficiently inserted and removed without relocating the rest of the list. Certain other operations, such as random access to a certain element, are however slower on lists than on arrays.
131+
132+
Python does not have linked lists in its standard library. We implement the concept of linked lists using the concept of nodes as discussed in the previous chapter. We have already seen how we create a node class and how to traverse the elements of a node.
97133

98-
**Types of Linked List:**
134+
### Types of Linked List:
99135

100136
**Singly Linked List**: In this type of linked list, every node stores address or reference of next node in list and the last node has next address or reference as NULL.
101137

102138
For example 1->2->3->4->NULL
103139

104-
**Doubly Linked List**: Here, here are two references associated with each node, One of the reference points to the next node and one to the previous node.
140+
[**Doubly Linked List**](doubly_linked_list.py): Here, here are two references associated with each node, One of the reference points to the next node and one to the previous node.
141+
* Doubly Linked List contains a link element called first and last.
142+
* Each link carries a data field(s) and two link fields called next and prev.
143+
* Each link is linked with its next link using its next link.
144+
* Each link is linked with its previous link using its previous link.
145+
* The last link carries a link as null to mark the end of the list.
146+
105147
Eg. NULL<-1<->2<->3->NULL
106148

107149
**Circular Linked List**: Circular linked list is a linked list where all nodes are connected to form a circle. There is no NULL at the end. A circular linked list can be a singly circular linked list or doubly circular linked list.
108150

109151
Eg. 1->2->3->1 [The next pointer of last node is pointing to the first]
110152

111153

112-
**How is an Array different from Linked List?**
154+
### **How is an Array different from Linked List?**
113155

114156
- The size of the arrays is fixed, Linked Lists are Dynamic in size.
115157
- Inserting and deleting a new element in an array of elements is expensive, Whereas both insertion and deletion can easily be done in Linked Lists.
@@ -134,7 +176,7 @@ searching: O(n)
134176
insertion: O(1)
135177
deletion: O(1)
136178

137-
## Stack
179+
## [Stack](stacks.py)
138180

139181
![Stack](assets/stack.png)
140182

@@ -164,19 +206,19 @@ Reverse a String using Stack
164206
Implement two stacks in an array
165207
Check for balanced parentheses in an expression
166208

167-
## Queue
209+
## [Queue](queues.py)
168210

169-
![Stack](assets/Queue.png)
211+
![Queues](assets/Queue.png)
170212

171213
A Queue is a linear structure which follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added.
172214

173215
Mainly the following are basic operations on queue: **Enqueue, Dequeue, Front, Rear**
174216

175217
The difference between stacks and queues is in removing. In a stack we remove the item the most recently added; in a queue, we remove the item the least recently added. Both Queues and Stacks can be implemented using Arrays and Linked Lists.
176218

177-
## Binary Tree
219+
## [Binary Tree](binary_tree.py)
178220

179-
![Stack](assets/binary-tree-to-DLL.png)
221+
![Binary tree](assets/binary-tree-to-DLL.png)
180222

181223
A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child.
182224

@@ -186,9 +228,9 @@ A Binary Tree node contains following parts.
186228
- Pointer to left child
187229
- Pointer to right child
188230

189-
### Binary search tree (BST)
231+
### [Binary search tree (BST)](binary_search_tree.py)
190232

191-
![Stack](assets/BSTSearch.png)
233+
![Binary search tree](assets/BSTSearch.png)
192234

193235
Binary Search Tree is a node-based binary tree data structure which has the following properties:
194236

@@ -200,9 +242,9 @@ searching: O(log n)
200242
insertion: O(log n)
201243
deletion: O(log n)
202244

203-
### Heap
245+
### [Heap](heap.py)
204246

205-
![Stack](assets/MinHeapAndMaxHeap.png)
247+
![Heap](assets/MinHeapAndMaxHeap.png)
206248

207249
A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Generally, Heaps can be of two types:
208250

@@ -213,9 +255,18 @@ min/max: O(1)
213255
insertion: O(log n)
214256
deletion: O(log n)
215257

216-
## Hash Tables
258+
## [Hash Tables](hash_tables.py)
217259

218-
![Stack](assets/HashingDataStructure-min-768x384.png)
260+
![Hash Tables](assets/HashingDataStructure-min-768x384.png)
261+
262+
Hash tables are a type of data structure in which the address or the index value of the data element is generated from a hash function. That makes accessing the data faster as the index value behaves as a key for the data value. In other words Hash table stores key-value pairs but the key is generated through a hashing function.
263+
264+
So the search and insertion function of a data element becomes much faster as the key values themselves become the index of the array which stores the data.
265+
266+
In Python, the Dictionary data types represent the implementation of hash tables. The Keys in the dictionary satisfy the following requirements.
267+
268+
* The keys of the dictionary are hashable i.e. the are generated by hashing function which generates unique result for each unique value supplied to the hash function.
269+
* The order of data elements in a dictionary is not fixed.
219270

220271
Hashing is an important Data Structure which is designed to use a special function called the Hash function which is used to map a given value with a particular key for faster access of elements. The efficiency of mapping depends of the efficiency of the hash function used.
221272

@@ -225,34 +276,10 @@ value lookup: O(1)
225276
insertion: O(1)
226277
deletion: O(1)
227278

228-
## Graphs
279+
## [Graphs](graphs.py)
229280

230-
![Stack](assets/undirectedgraph.png)
281+
![Graph](assets/undirectedgraph.png)
231282

232283
A Graph is a non-linear data structure consisting of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes in the graph. More formally a Graph can be defined as,
233284

234285
A Graph consists of a finite set of vertices(or nodes) and set of Edges which connect a pair of nodes.
235-
236-
## Matrix
237-
238-
![Stack](assets/matrix-9.png)
239-
240-
A matrix represents a collection of numbers arranged in an order of rows and columns. It is necessary to enclose the elements of a matrix in parentheses or brackets.
241-
242-
## PYTHON SPECIFIC DATA STRUCTURES
243-
244-
These data structures are specific to python language and they give greater flexibility in storing different types of data and faster processing in python environment.
245-
246-
**List**: It is similar to array with the exception that the data elements can be of different data types. You can have both numeric and string data in a python list.
247-
248-
**Tuple**: Tuples are similar to lists but they are immutable which means the values in a tuple cannot be modified they can only be read.
249-
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
250-
251-
**Dictionary**: The dictionary contains Key-value pairs as its data elements.
252-
In Dictionary each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.
253-
254-
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.
255-
256-
- More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins.
257-
258-
- Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed.

data-structures/doubly_linked_list.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
class Node:
2+
def __init__(self, data):
3+
self.data = data
4+
self.next = None
5+
self.prev = None
6+
7+
8+
class doubly_linked_list:
9+
def __init__(self):
10+
self.head = None
11+
12+
# Adding data elements
13+
def push(self, NewVal):
14+
NewNode = Node(NewVal)
15+
NewNode.next = self.head
16+
if self.head is not None:
17+
self.head.prev = NewNode
18+
self.head = NewNode
19+
20+
# Print the Doubly Linked list
21+
def listprint(self, node):
22+
while (node is not None):
23+
print(node.data)
24+
last = node
25+
node = node.next
26+
27+
def insert(self, prev_node, NewVal):
28+
if prev_node is None:
29+
return
30+
NewNode = Node(NewVal)
31+
NewNode.next = prev_node.next
32+
prev_node.next = NewNode
33+
NewNode.prev = prev_node
34+
if NewNode.next is not None:
35+
NewNode.next.prev = NewNode
36+
37+
def append(self, NewVal):
38+
# Adds the element at the last
39+
NewNode = Node(NewVal)
40+
NewNode.next = None
41+
if self.head is None:
42+
NewNode.prev = None
43+
self.head = NewNode
44+
return
45+
last = self.head
46+
while (last.next is not None):
47+
last = last.next
48+
last.next = NewNode
49+
NewNode.prev = last
50+
return
51+
52+
dllist = doubly_linked_list()
53+
dllist.push(12)
54+
dllist.push(8)
55+
dllist.push(62)
56+
dllist.insert(dllist.head.next, 13)
57+
dllist.listprint(dllist.head)

data-structures/linked_lists.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
"""
2+
Linked list implementation
3+
"""
4+
class Node:
5+
def __init__(self, dataval=None):
6+
self.dataval=dataval
7+
self.nextval=None
8+
9+
class SLinkedList:
10+
def __init__(self):
11+
self.headval=None
12+
13+
def listprint(self):
14+
"""
15+
Print the linked list
16+
"""
17+
printval = self.headval
18+
while printval is not None:
19+
print (printval.dataval)
20+
printval = printval.nextval
21+
22+
def insertAtBegining(self, value):
23+
"""
24+
Insert a new value at the begining of the list
25+
"""
26+
new_node = Node(value)
27+
new_node.nextval = self.headval
28+
self.headval = new_node
29+
30+
def insertAtEnd(self, value):
31+
"""
32+
Insert a new value at the end of the list
33+
"""
34+
new_node = Node(value)
35+
if self.headval is None:
36+
self.headval = new_node
37+
return
38+
last_node = self.headval
39+
40+
while(last_node.nextval):
41+
last_node = last_node.nextval
42+
43+
last_node.nextval = new_node
44+
45+
def insertBetween(self, middle_node, value):
46+
new_node = Node(value)
47+
new_node.nextval = middle_node
48+
middle_node.nextval = new_node
49+
50+
def removeNode(self, key):
51+
head = self.headval
52+
53+
if (head is not None):
54+
if (head.data == key):
55+
self.headval = head.next
56+
head = None
57+
return
58+
59+
while (head is not None):
60+
if head.data == key:
61+
break
62+
prev = head
63+
head = head.next
64+
65+
if (head == None):
66+
return
67+
68+
prev.next = head.next
69+
70+
head = None
71+
72+
list1 = SLinkedList()
73+
list.headval = Node("Mon")
74+
e2 = Node("Tue")
75+
e3 = Node("Wed")
76+
77+
# Link first Node to second node
78+
list1.headval.nextval = e2
79+
80+
# Link second Node to third node
81+
e2.nextval = e3
82+
83+
list1.listprint()
84+
85+
list1.insertAtBegining("Sun")
86+
87+
list1.insertAtEnd("Thu")

0 commit comments

Comments
 (0)