Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 21, 2022 07:39 pm GMT

Introduction to Data Structures and Algorithms in Python.

Introduction
Data structuresare simply the different ways of organizing and storing data in our computers so as to perform operations on the data.

Bult-in Data Structures

Data structures allow us to organize, store, and manage data for efficient access and modification.

List
A list is defined using square brackets and holds data that is separated by commas. It is a type of data used to represent/ store a list of objects in a single variable . It can contain a mix of different data types. We useprint()function to print the output on the terminal.
Lists are indexed from 0
Example of a list in Python is as shown below.

mylist=["Faith",32,"Kenya"]print (mylist)

Output:

[Faith,32,Kenya]

Theappend()method adds an item to the end of the list.

mylist.append(3)print(mylist)

The insert() method adds an item at a specific place in the list

mylist.insert(0, 38)

The pop() method removes last element from list

numbers.pop()print(mylist)

To access an element on the list

print(numbers[0])

To check index of an item

fruits = ['apple', 'banana', 'orange', 'grape']index = fruits.index('banana')print(index)

Tuple
Atupleis an ordered collection of items. It is a data type for immutable ordered sequences of elements I.e
you cant add and remove elements from tuples, or sort them in place
A tuple is used to store a sequence of objects.
Tuples are indexed from 0.
We can create tuples using the method below:

positions = (4,9,18)print(positions)

To access tuples using their index we use the method shown below:
print(positions [2])

To create a list of tuples we use the method shown below:
positions = [(4,9,18), (30,15, 19)]

Set

Set is a mutable and unordered collection of unique elements. It can permit us to remove duplicate quickly from a list.
A set is mutable, it can be changed or modified once created.

Removing duplicates from a list

numbers = [9, 16, 3, 4, 9, 3]unique_numbers = set(numbers)print(unique_numbers)

Union of sets

first_set = {3, 4}second_set = {5, 6}print(first | second)

Intersection of sets
print(first_set & second_set)

Difference between two sets
print(first_set - second_set)

Symmetric difference
print(first_set ^ second_set)

Iterating over elements in a set

numbers = {3, 7}for x in numbers:    print(x)

output

37

Dictionary

Dictionary is a mutable and unordered data structure. It permits storing a pair of items (i.e. keys and values).
We can use strings, numbers or tuples as keys.
The value can be any data type.
We can assign one value to multiple keys.
We can create dictionaries usingdict()method.

Creating a dictionary

user = {"name": "Faith", "age":32, "hobbies": ["cooking", "singing"]}print(user)

Accessing a specific key

print(user["name"])

Specifying a default value for keys that do not exist
print(user.get("email", "Invalid key"))

Adding a key to the dictionary

user["email"] = "[email protected]"print(user.get("email"))

Changing value of a key

user[name] = "Liam"print(user)

To modify several or all values

user.update({"name": "David", "age": 21, "email": "[email protected]"})

To delete a key

del user["hobbies"]print(user)

Looping through keys and values

for key, value in user.items():    print(key, value)

User-defined data structures

These are data structures that are not supported by Python, but can be programmed by the user to function similarly to Python built-in data structures.
We will look at stacks, queues and linked lists.

Stack

A stack is a linear data structure that follows the LIFO(Last In First Out) principle.. 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.

Stacks in Python can be implemented using lists, Collections.deque, queue.LifoQueue

Functions we can perform on stacks

append/push()-to add an item on top of the stack.
pop()-to remove an item on top of the stack.
peek/top()- to view the top element of the stack.
size()-returns the size of the stack.
[-1]-to get the item that is on top of the stack. It only works if our stack is not empty.
empty()-to return whether the stack is empty.

Queue

A queue is a linear data structure that follows FIFO(First In First Out) principle.
Insertion and deletion in queues happens on the rear-end and front-end.
In Python, queues can be implemented using lists, collection.deque, queue.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

Linked list

A linked list is a data structure for storing a collection of items.
A linked list can be visualized as several boxes connected to each other.
The data used in linked lists can be strings, numbers, characters, etc.
Linked lists can be used to implement stacks, queues and graphs.

Algorithms

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.
Algorithmsare also the operations that we can perform on different data structures and the set of instructions for executing them.

To learn more about algorithms click here

You can also read this article to learn more about data structures.


Original Link: https://dev.to/k_faithk/introduction-to-data-structures-and-algorithms-in-python-54jk

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