# Data Structures and Algorithms with Python

The main difference between bad programmers and good programmers is whether they consider their code or their data structures and algorithms to be more important. Bad programmers worry about code. Good programmers care about data structures and algorithms.

In this article, I’m going to introduce you to the complete knowledge you need about data structures and algorithms with Python to be better with programming and most importantly to crack your interview.

## Why Data Structures and Algorithms are Important?

The data structures and algorithms provide a set of techniques for the programmer to effectively manage data. The programmer should understand the basic concepts of data management. For example, if the programmer wants to collect Facebook user details, the candidate needs to access and manage the data efficiently using data structure and algorithm techniques.

If the programmer does not know the structures of the data and the algorithms, he may not be able to write efficient code to handle the data. The concepts of data structure can be implemented in any programming language. They can write code in any programming language with minimal effort. If the programmer does not know the predefined algorithmic techniques, it may take longer to resolve the problem.

## Data Structures and Algorithms: Data Structures

A data structure is nothing but a format used to store and organize data. Data structures are fundamental to programming and most programming languages ​​come with them built-in.

You already know how to use many of Python’s built-in data structures, such as lists, tuples, and dictionaries. In this section, you will learn how to create two additional data structures: stacks and queues.

### Stacks

A stack is a data structure like a list, you can add and remove items from a stack, except unlike a list, you can only add and remove the last item. If you have the list [1, 2, 3], you can delete any of the items it contains. If you have an identical stack, you can only remove the last item, 3. If you remove 3, your stack looks like [1, 2]. You can now delete the 2.

Once you delete the 2, you can delete the 1 and the stack is empty. Removing an item from a stack is called popping. If you put 1 back on the stack, it looks like . If you put a two on the stack, it looks like [1, 2]. Putting an object on a stack is called pushing. This type of data structure, where the last element inserted is the first element removed, is called a last-in-first-out (LIFO) data structure.

You can imagine LIFO as a stack of dishes. If you stack five dishes on top of each other, you will need to remove all of the other dishes to access the bottom one of the stack. Think of each data item in a stack as a dish, to access it you need to extract the data on top.

Now, let’s see how to build stacks:

```.wp-block-code {
border: 0;
}

.wp-block-code > div {
overflow: auto;
}

.hljs {
box-sizing: border-box;
}

.hljs.shcb-code-table {
display: table;
width: 100%;
}

.hljs.shcb-code-table > .shcb-loc {
color: inherit;
display: table-row;
width: 100%;
}

.hljs.shcb-code-table .shcb-loc > span {
display: table-cell;
}

.wp-block-code code.hljs:not(.shcb-wrap-lines) {
white-space: pre;
}

.wp-block-code code.hljs.shcb-wrap-lines {
white-space: pre-wrap;
}

.hljs.shcb-line-numbers {
border-spacing: 0;
counter-reset: line;
}

.hljs.shcb-line-numbers > .shcb-loc {
counter-increment: line;
}

.hljs.shcb-line-numbers .shcb-loc > span {
}

.hljs.shcb-line-numbers .shcb-loc::before {
border-right: 1px solid #ddd;
content: counter(line);
display: table-cell;
text-align: right;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
white-space: nowrap;
width: 1%;
}
```class Stack:
def __init__(self):
self.items = []

def is_empty(self):
return self.items == []

def push(self, item):
self.items.append(item)

def pop(self):
return self.items.pop()

def peek(self):
last = len(self.items)-1
return self.items[last]

def size(self):
return len(self.items)
``````

If you will create a new stack, it will be empty and the is_empty method will return True:

``````stack = Stack()
print(stack.is_empty())``````

Output: True

When you add a new item to the stack, is_empty returns False:

``````stack = Stack()
stack.push(1)
print(stack.is_empty())``````
`Output: False`

Call the pop method to remove an item from the stack, and is_empty will return True:

``````stack = Stack()
stack.push(1)
item = stack.pop()
print(item)
print(stack.is_empty())``````
`Output: 1True`

Finally, you can take a look at the contents of the stack and get its size:

``````stack = Stack()

for i in range(0, 6):
stack.push(i)

print(stack.peek())
print(stack.size())``````
`Output:56`

### Queues

A queue is another data structure. A queue is also like a list; you can add and remove items from it. A queue is also like a stack because you can only add and remove items in a certain order. Unlike a stack, where the first item put in is the last item out, a queue is a first-in-first-out (FIFO) data structure: the first item added is the first item removed.

Imagine FIFO as a data structure representing a line of people waiting to buy movie tickets. The first person in line is the first person to get tickets, the second person in line is the second person to get tickets, and so on.

Let’s see how we can implement Queues with Python:

``````class Queue:
def __init__(self):
self.items = []

def is_empty(self):
return self.items == []

def enqueue(self, item):
self.items.insert(0, item)

def dequeue(self):
return self.items.pop()

def size(self):
return len(self.items)
``````

If you create a new empty queue, the is_empty method returns True:

``````a_queue = Queue()
print(a_queue.is_empty())``````
`Output: True`

To add items and check the queue size:

``````a_queue = Queue()

for i in range(5):
a_queue.enqueue(i)

print(a_queue.size())``````
`Output: 5`

To remove each item from the queue:

``````a_queue = Queue()

for i in range(5):
a_queue.enqueue(i)

for i in range(5):
print(a_queue.dequeue())

print(a_queue.size())``````

With this, we completed the Data Structures and now let’s move to the Algorithms part of Data Structures and Algorithms with Python.

## Data Structures and Algorithms: Algorithms

This section covers the complete knowledge of algorithms. An algorithm is a series of steps that can be taken to solve a problem. The problem may be searching for a list or printing the words to “99 Beer Bottles on the Wall”.

### FizzBuzz Algorithm

It’s finally time to learn how to solve FizzBuzz, the popular interview question designed to eliminate candidates: write a program that prints the numbers from 1 to 100. But for the multiples of 3, print “Fizz” instead of number, and multiples of five print “Buzz.” For multiples of three and five, print “FizzBuzz”.

To solve this problem, you need a way to check if a number is a multiple of three, a multiple of five, both, or neither. If a number is a multiple of three, if you divide it by three, there is no remainder.

The same applies to five. The modulo (%) operator returns the remainder. You can solve this problem by going through the numbers and checking if each number is divisible by three and five, only three, only five, or none:

``````def fizz_buzz():
for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)

fizz_buzz()``````

### Sequential Search Algorithm

A search algorithm finds information in a data structure such as a list. A sequential search is a simple search algorithm that checks each item in a data structure to see if the item matches what it is looking for.

If you were playing cards and looking for a specific card in the deck, you probably searched sequentially to find it. You went through each map in the game one by one, and if the map wasn’t the one you were looking for, you moved on to the next map.

When you finally got to the map you wanted, you stopped. If you went through the entire deck without finding the map, you also stopped because you realized the map was not there. Here is an example of a sequential search in Python:

``````def ss(number_list, n):
found = False
for i in number_list:
if i == n:
found = True
break
return found

numbers = range(0, 100)
s1 = ss(numbers, 2)
print(s1)
s2 = ss(numbers, 202)
print(s2)``````

### Palindrome Algorithm

A palindrome is a word spelt the same way forward and backwards. You can write an algorithm that checks if a word is a palindrome by reversing all the letters in the word and testing whether the reversed word and the original word are the same. If they are, the word is a palindrome:

``````def is_palindrome(word):
word = word.lower()
return word[::-1] == word

print(is_palindrome("Mother"))
print(is_palindrome("Mom"))``````

### Anagram Algorithm

An Anagram is a word which is created by rearrange of the letters of another word. The word iceman is an anagram of cinema because you can rearrange the letters of either word to form the other. You can determine if two words are anagrams by sorting the letters in each word alphabetically and testing whether they are the same:

``````def is_anagram(w1, w2):
w1 = w1.lower()
w2 = w2.lower()
return sorted(w1) == sorted(w2)

print(is_anagram("iceman", "cinema"))
print(is_anagram("leaf", "tree"))``````

### Count Character Occurrences

To count character occurrences, you’ll write an algorithm that returns the number of times each character appears in a string. The algorithm will iterate character by character through the string and keep track of the number of times each character appears in a dictionary:

``````def count_characters(string):
count_dict = {}
for c in string:
if c in count_dict:
count_dict[c] += 1
else:
count_dict[c] = 1
print(count_dict)

count_characters("Dynasty")``````

So this is probably everything you need to know about data structures and algorithms to master your programming skills and to crack your interview. I hope you liked this article on Data Structures and Algorithms with Python. Feel free to ask your valuable questions in the comments section below.

Also, Read – Decorators in Python Tutorial. 