Chapter 1
Chapter 1
D ATA S T R U C T U R E S A N D A L G O R I T H M S I N P Y T H O N
Miriam Antona
Software Engineer
The importance of algorithms and data structures
Data structures and algorithms enable us to
solve everyday problems
2. Code
queues
graphs
music playlist
remove_at_beginning()
insert_at_end()
remove_at_end()
insert_at()
remove_at()
search()
...
sushi_preparation = LinkedList()
sushi_preparation.insert_at_end("prepare")
sushi_preparation = LinkedList()
sushi_preparation.insert_at_end("prepare")
sushi_preparation.insert_at_end("roll")
sushi_preparation = LinkedList()
sushi_preparation.insert_at_end("prepare")
sushi_preparation.insert_at_end("roll")
sushi_preparation.insert_at_beginning("assemble")
sushi_preparation.search("roll")
True
sushi_preparation.search("mixing")
False
Miriam Antona
Software Engineer
Big O Notation
Measures the worst-case complexity of an algorithm
Time complexity: time taken to run completely
def constant(colors):
print(colors[2])
constant(colors)
blue
def constant(colors):
print(colors[2]) # O(1)
constant(colors)
blue
def linear(colors):
for color in colors:
print(color)
linear(colors)
green
yellow
blue
pink
def linear(colors):
for color in colors:
print(color) # O(4)
linear(colors)
n=4 : 4 operations
def linear(colors):
for color in colors:
print(color) # O(7)
linear(colors)
n=4 : 4 operations
n=7 : 7 operations
...
O(n) complexity
quadratic pattern
O(n2 ) complexity
cubic(colors)
def complex_algorithm(colors):
color_count = 0
print(color_count)
complex_algorithm(colors)
def complex_algorithm(colors):
color_count = 0 # O(1)
print(color_count) # O(1)
complex_algorithm(colors) # O(4
def complex_algorithm(colors):
color_count = 0 # O(1)
print(color_count) # O(1)
complex_algorithm(colors) # O(4 + 2n
def complex_algorithm(colors):
color_count = 0 # O(1)
print(color_count) # O(1)
Miriam Antona
Software Engineer
Stacks
LIFO: Last-In First-Out
Last inserted item will be the first item to
be removed
class Stack:
def __init__(self):
self.top = None
class Stack:
def __init__(self):
self.top = None