Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 21, 2022 07:12 am GMT

Introduction to Data Structures and Algorithms With Python

Image description
Data Structures are a collection of data values, the relationships among them, and the functions or operations that can be applied to the data.

Data Structures allows you to organize your data in such a way that enables you to store collections of data, relate them and perform operations on them accordingly.

Data algorithms are sets of well-defined instructions to solve a particular problem. It takes a set of input and produces a desired output.

Types of data structures

Image description

1. Lists

This is an ordered and changeable collection of item that also allows duplicate items. It can contain different data types.
Lists are created through square brackets[] or list() constructor.
For example:

my_list=["melon","apple","mango"]

List Methods
Python has a set of built-in methods that you can use on lists.

#access a list itemprint(my_list[2])#append()  Adds an element at the end of the listmy_list.append("orange")#clear()  Removes all the elements from the listmy_list.clear()#copy()  Returns a copy of the listmy_list.copy()#extend()Adds list items to the end of the current list my_list.extend(another_list)#insert()  Adds an element at the specified position\indexmy_list.insert(3,"guava")#pop()  Removes the element at the specified position\indexmy_list.pop(1)#remove()  Removes the item with the specified valuemy_list.remove("apple")#reverse()  Reverses the order of the listmy_list.reverse()#sort()  Sorts the list alphanumerically, ascending, by default:my_list.sort()

2. Tuples

These are unchangeable,ordered data structures that allows duplicates.
They are created through () or tuple() constructor.

#create a tuplenumber=(45,34,678)#access a tuple itemnumber[0]#delete a tupledel number

Once you have created a tuple you can not change it, that is you can not add, edit or remove any of the items in it. Not unless you change it to a mutable data structure like lists then back to a tuple.

y=list(number)#add the list method you want performed e.g sort()y.sort()number=tuple(y)

3. Dictionary

Dictionaries are used to store data values in key:value pairs.
They are changeable and do not allow duplicate keys and are written with curly brackets {}

dog = {'name':'Cara','color':'Brown','gender':'Female'}

Dictionary methods

#keys()  prints out all the keysfor i in dog.keys():   print(i)#values()  prints out all the valuesfor i in dog.values():   print(i)#items() prints out the key:value pairfor i in dog.items():   print(i)

Output

namecolorgenderCaraBrownFemale('name', 'Cara')('color', 'Brown')('gender', 'Female')

Its tedious to check whether a key exists in a dictionary before accessing that keys value. Fortunately, dictionaries have a get() method that takes two arguments: the key of the value to retrieve and a fallback value to return if that key does not exist.

print(dog.get('sound',0))

Output

0

4. Sets

Unlike dictionaries,sets are unchangeable and also do not support duplicates.

myset = {"apple", "banana", "cherry"}

5. Stacks

A stack is a linear data structure that follows the principle of Last In First Out (LIFO). This means the last element inserted inside the stack is removed first.
In programming terms, putting an item on top of the stack is called push and removing an item is called pop.
Image description

# Creating a stackdef create_stack():    stack = []    return stack# Creating an empty stackdef check_empty(stack):    return len(stack) == 0# Adding items into the stackdef push(stack, item):    stack.append(item)    print("pushed item: " + item)# Removing an element from the stackdef pop(stack):    if (check_empty(stack)):        return "stack is empty"    return stack.pop()stack = create_stack()push(stack, str(1))push(stack, str(2))push(stack, str(3))push(stack, str(4))print("popped item: " + pop(stack))print("stack after popping an element: " + str(stack))

Output

pushed item: 1pushed item: 2pushed item: 3pushed item: 4popped item: 4stack after popping an element: ['1', '2', '3']

6. Queues

A queue is a linear type of data structure used to store the data in a sequentially and it follows the First In First Out (FIFO) rule - the item that goes in first is the item that comes out first.
Enqueue is adding an element to the end of the queue while
Dequeue is removing an element from the front of the queue.
Image description

# Queue implementation in Pythonclass Queue:    def __init__(self):        self.queue = []    # Add an element    def enqueue(self, item):        self.queue.append(item)    # Remove an element    def dequeue(self):        if len(self.queue) < 1:            return None        return self.queue.pop(0)    # Display  the queue    def display(self):        print(self.queue)    def size(self):        return len(self.queue)q = Queue()q.enqueue(1)q.enqueue(2)q.enqueue(3)q.enqueue(4)q.enqueue(5)q.display()q.dequeue()print("After removing an element")q.display()

Output

[1, 2, 3, 4, 5]After removing an element[2, 3, 4, 5]

7. Linked lists

A linked list is a linear data structure that includes a series of connected nodes. Each node stores the data and the address of the next node.
The first node is called the head, and its used as the starting point for any iteration through the list. The last node must have its next reference pointing to None to determine the end of the list. Heres how it looks:
Image description

# Linked list implementation in Pythonclass Node:    # Creating a node    def __init__(self, item):        self.item = item        self.next = Noneclass LinkedList:    def __init__(self):        self.head = Noneif __name__ == '__main__':    linked_list = LinkedList()    # Assign item values    linked_list.head = Node(1)    second = Node(2)    third = Node(3)    # Connect nodes    linked_list.head.next = second    second.next = third    # Print the linked list item    while linked_list.head != None:        print(linked_list.head.item, end=" ")        linked_list.head = linked_list.head.next

Output

1 2 3 

So what makes them different from normal lists? Linked lists differ from lists in the way that they store elements in memory. While lists use a contiguous memory block to store references to their data, linked lists store references as part of their own elements.

The above concepts can be overwhelming ,so just take your time.
Happy coding!!


Original Link: https://dev.to/hannahmwende/introduction-to-data-structures-and-algorithms-with-python-2fm9

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To