Data Structures Using Python Lab Record: Vishnupur, Narsapur, Medak (District) - 502313

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

B V RAJU INSTITUTE OF TECHNOLOGY

(UGC Autonomous)
Vishnupur, Narsapur, Medak (District) – 502313
(Sri Vishnu Educational Society)

Data Structures using


Python Lab Record

B. TECH
II Year I Sem
Academic Year 2023-24

DEPARTMENT OF
Artificial Intelligence & Data Science (AI&DS)

1|Page
Week 1:
 Write a program to implement the followings:
 Create, concatenate and print a string and accessing sub-string from a given
string
 Create, append, and remove lists
 Demonstrate working with tuples

Description:
Strings are a sequence of characters. A character can be a number, letter, special
character, etc. A string can contain spaces and there is no limit on how many characters it
should contain.

A string is an immutable data type in python that cannot be changed once we declare it in
a program.

Create a string in python Now, we will see how to create a string in python or how to
declare a string in python?

We can declare a string in python in three ways

1- Using single quotes ("")

you can declare a string using single quotes (1. Let's see an example

Example:

print("Hello Python Guides!")

output : Hello Python Guides!

2- Using double quotes ("")

you can declare a string using double quotes (" "). Let's, see an example

Example print("Hello Python Guides!!")

output: Hello python Guides!!

3. Using triple quotes ("" "")

you can declare a string using triple quotes (". Let's, see an example

Example:

2|Page
print("Hello Python Guides!!!")

output: Hello Python Guides!!!

Now let's run all these formats and see the output.

How to concatenate two strings python?


Concatenating two strings refers to merging of both the strings together. Concatenation
of Tutorials" and "Point" will result in "Tutorial Point".

We will be discussing different methods of concatenation two strings in Python.

Using Operator:

Two strings can be concatenated in python using the operator between them. more than
two strings can be concatenated using operator.

Python program to Append, Delete and Display Elements of a List

Python List append () Method

The python List append () method is used for appending and adding elements to the end
of The List

Syntax: list.append(item)

parameters:

Item: an item to be added at the end of the list

Returns: the methos doesn't return any value

Remove an item from a list in python (clear, pop, remove, del)

In Python, use list methods clear(), pop) and remove() to remove items (elements) from a
list. It is also possible to delete items using del statement by specifying the position or range

Using the clear() method:

The clear method removes all elements from a list, leaving an empty list.

Example:

3|Page
my_list=[1, 2, 3, 4, 5]

my_list.clear()

print(my_list) #Output: []

Using the pop() method:

The pop() method removes an item from the end of the list by default, or from a specific
index if provided, and returns the removed item.

Example:

my_list=[1, 2, 3, 4, 5]

removed item=my_list.pop() # Removes the last item from the list

print(removed item) Output: 5

print(my list) # Output: [1, 2, 3, 4]

Using the remove() method:

The remove() method removes the first occurrence of a specified value from the list.
Example:

my_list=[1, 2, 3, 4, 5]

my_list.remove(3) Removes the value 3 from the list

printing, list) Output: (1, 2, 4, 5

Using the del statement:

The del statement can be used to remove an item from a list by its index or a slice of
indices.

Example:

my_list=[1, 2, 3, 4, 5]

del my_list [2] #Removes the item at index 2 from the list

4|Page
print(my_list) # Output: [1, 2, 4, 5]

Note: It's important to be cautious when using these methods to remove items from a list,
as it can affect the indexing of other items in the list. Always double-check your code to
avoid unintended consequences.

Demonstrate working with tuples.

# Creating a tuple
my_tuple = (1, 2, 3, 4, 5)
print("Original Tuple:",my_tuple)
# Accessing elements in a tuple
print("Accessing elements in a tuple:")
print("Element at index 0:", my_tuple[0])
print("Element at index 2:", my_tuple[2])

# Looping over a tuple


print("Looping over a tuple:")
for item in my_tuple:
print(item)
# Tuple methods
my_tuple = (1, 2, 3, 3, 4, 3, 5)
print("Using tuple methods:")
print("Count of occurrences of 3:", my_tuple.count(3))
print("Index of first occurrence of 4:", my_tuple.index(4))

# Tuple concatenation and repetition


tuple1 = (1, 2, 3)
tuple2 = ('a', 'b', 'c')
concatenated_tuple = tuple1 + tuple2
repeated_tuple = tuple1 * 3
print("Tuple concatenation and repetition:")
print("Concatenated tuple:", concatenated_tuple)
print("Repeated tuple:", repeated_tuple)

# packing and unpacking in Python


a = ("MNNIT Allahabad", 5000, "Engineering")

# this lines UNPACKS values


# of variable a
(college, student, type_ofcollege) = a
print("unpacking data:")
# print college name

5|Page
print(college)

# print no of student
print(student)

# print type of college


print(type_ofcollege)

OUTPUT:

Original Tuple: (1, 2, 3, 4, 5)


Accessing elements in a tuple:
Element at index 0: 1
Element at index 2: 3
Looping over a tuple:
1
2
3
4
5
Using tuple methods:
Count of occurrences of 3: 3
Index of first occurrence of 4: 4
Tuple concatenation and repetition:
Concatenated tuple: (1, 2, 3, 'a', 'b', 'c')
Repeated tuple: (1, 2, 3, 1, 2, 3, 1, 2, 3)
unpacking data:
MNNIT Allahabad
5000
Engineering

6|Page
Week 2:
 Write a program to implement the followings:
 Demonstrate working with dictionaries
 Copy contents from one file to another file
 Perform a countdown using single thread.

Description:
Python dictionary is an unordered collection of items. It stores elements
in key/value pairs. Here, keys are unique identifiers that are associated with each value.
Let's see an example.
If we want to store information about countries and their capitals, we can create a
dictionary with country names as keys and capitals as values.

Create a dictionary In Python:

Here's how we can create a dictionary in python.

Example:
capital_City = {"Nepal":"Kathmandu", "Italy":"Rome","England":"London"}
print(capital_City)

output:

{'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}

Note: Here, keys and values both are of String type. We can also have keys and values of
different data types.
Example 1: Python Dictionary
#dictionary with keys and values of different data types
numbers = {1: "One", 2: "Two", 3: "Three"}
print(numbers)
Output:
{1: 'One', 2: 'Two', 3: 'Three'}

7|Page
In the above example, we have created a dictionary named numbers. Here, keys are
of Int type and values are of String type.

Add Elements to a Dictionary


We can add elements to a dictionary using the name of the dictionary with []. For example,
capitalCity = {"Nepal": "Kathmandu", "England": "London"}
print("Initial Dictionary: ",capitalCity)

capitalCity["Japan"] = "Tokyo"

print("Updated Dictionary: ",capitalCity)


print(capitalCity["Japan"])
output:
Initial Dictionary: {'Nepal': 'Kathmandu', 'England': 'London'}
Updated Dictionary: {'Nepal': 'Kathmandu', 'England': 'London', 'Japan': 'Tokyo'}
In the above example, we have created a dictionary named capitalCity. Notice the line,
capitalCity["Japan"]=Tokyo
Here we have a added a element to capital_city with key: Japan and value: Tokyo.

Change Value of Dictionary


We can also use [] to change the value associated with a particular key. For example,
studentID = {111: "Eric", 112: "Kyle", 113: "Butters"}
print("Initial Dictionary: ", studentID)

studentID[112] = "Stan"

print("Updated Dictionary: ", studentID)

output:
Initial Dictionary: {111: 'Eric', 112: 'Kyle', 113: 'Butters'}
Updated Dictionary: {111: 'Eric', 112: 'Stan', 113: 'Butters'}

In the above example, we have created a dictionary named studentID. Initially, the value
associated with the key 112 is "Kyle". Now, notice the line,

studentID[112] = "Stan"

Here, we have changed the value associated with the key 112 to "Stan".

Accessing Elements from Dictionary:

studentID = {111: "Eric", 112: "Kyle", 113: "Butters"}


print(studentID[111])
8|Page
print(studentID[113])
output:
Eric
Butters
in python we use the keys to access their corresponding values for example,
if we try to access the value of a key that does not exist, we will get an error. For Example
studentID = {111: "Eric", 112: "Kyle", 113: "Butters"}
print(studentID[211])

output:
KeyError: 211
Removing Elements From the Dictionary
Example:
student_id = {111: "Eric", 112: "Kyle", 113: "Butters"}
print("Initial Dictionary: ", student_id)
del student_id[111]
print("Updated Dictionary ", student_id)
Output:
Initial Dictionary: {111: 'Eric', 112: 'Kyle', 113: 'Butters'}
Updated Dictionary {112: 'Kyle', 113: 'Butters'}

Here, we have created a dictionary named student_id. Notice the code,

del student_id[111]
The del statement removes the element associated with the key 111.
We can also delete the whole dictionary using the del statement,
Example:
student_id = {111: "Eric", 112: "Kyle", 113: "Butters"}
del student_id
print(student_id)
output:
print(student_id)
NameError: name 'student_id' is not defined

9|Page
We are getting an error message because we have deleted the student_id
dictionary and
student_id doesn't exist anymore.
Python Dictionary Methods:
Methods that are available with a dictionary are tabulated below. Some of them
have already been used in the above examples.
Function Description
all() Return True if all keys of the dictionary are True
(or if the dictionary is empty).
Return True if any key of the dictionary is true.
any() If the dictionary is empty, return False.

len() Return the length (the number of items) in the


dictionary.
sorted() Return a new sorted list of keys in the dictionary.

clear() Removes all items from the dictionary.


keys() Returns a new object of the dictionary's keys.

values() Returns a new object of the dictionary's values

Dictionary Membership Test:


We can test if a key is in a dictionary or not using the keyword in. Notice that the
membership test is only for the keys and not for the values.
Example:
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Membership Test for Dictionary Keys
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

# Output: True
print(1 in squares) # prints True
print(2 not in squares) # prints True
# membership tests for key only not value
print(49 in squares) # prints false

Output:
True
True
False
Iterating Through Dictionary:
We can iterate through each key in a dictionary using a for loop.

10 | P a g e
Example:
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])

Output:
1
9
25
49
81
Here, we have iterated through each key in the squares dictionary using the for
loop.

Copy Content of One File to Another in Python

To copy the content of one file to another in Python, you have ask from user to
enter the name of two files. The first file referred as a source, whereas the second
file referred as a target file. That is, the content of source file gets copied to the target
file as shown in the program given below:

The question is, write a Python program to copy one file to another entered
by user at run-time. Here is its answer:

Example: print("Enter the Name of Source File: ")


sFile = input()
print("Enter the Name of Target File: ")
tFile = input()

fileHandle = open(sFile, "r")


texts = fileHandle.readlines()
fileHandle.close()

fileHandle = open(tFile, "w")


for s in texts:
fileHandle.write(s)
fileHandle.close()
print("\nFile Copied Successfully!")

Perform a countdown using single thread


Example:
import time

11 | P a g e
# define the countdown func.
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
print('Fire in the hole!!')
# input time in seconds
t = input("Enter the time in seconds: ")
# function call
countdown(int(t))
Output:
Enter the time in seconds: 0910
15:10
15:09
15:08

Approach:

In this project, we will be using the time module and its sleep() function. Follow
the below steps to create a countdown timer:

Step 1: Import the time module.


Step 2: Then ask the user to input the length of the countdown in seconds.
Step 3: This value is sent as a parameter ‘t’ to the user-defined function
countdown(). Any variable read using the input function is a string. So, convert
this parameter to ‘int’ as it is of string type.
Step 4: In this function, a while loop runs until time becomes 0.
Step 5: Use divmod() to calculate the number of minutes and seconds. You
can read more about it here.
Step 6: Now print the minutes and seconds on the screen
using the variable
12 | P a g e
timeformat.
Step 7: Using end = ‘\r’ we force the cursor to go back to the start of the
screen (carriage return) so that the next line printed will overwrite the previous
one.
Step 8: The time.sleep() is used to make the code wait for one sec.
Step 9: Now decrement time so that the while loop can converge.
Step 10: After the completion of the loop, we will print “Fire in the hole” to
signify the end of the countdown.

13 | P a g e
Week3:
Write a program to implement the followings:
 Print all of the unique words in the text file in alphabetical order
 Python program that passes data between two processes using queue

Description:
File handling in python
In Python, a file is a named sequence of bytes that is stored on a file system,
such as the hard disk of a computer. Files can be used to store and retrieve data,
and they are a common way to read and write data in Python programs.
There are two main types of files in Python:
Text files: These files contain human-readable text data, such as plain text,
CSV, JSON, XML, or other text-based formats. Text files can be opened and
read using Python's built-in open() function, and data can be written to text files
using the file object's write() method.
Example of opening a text file for reading:
# Open a text file for reading
with open('example.txt', 'r') as file:
# Read the contents of the file
contents = file.read()
print(contents)

output:
Assuming that the file example.txt exists in the same directory as the Python
script or notebook where this code is executed, and it contains the following text:

hello world
this is AIDS department

Binary files: These files contain binary data, such as images, audio files, video
files, or other non-text data. Binary files can be opened and read using Python's
built-in open() function with a binary mode ('rb' for reading binary, 'wb' for writing
binary), and data can be written to binary files using the file object's write() method.
Example of opening a binary file for reading:
#Open a binary file for reading
with open('image.jpg', 'rb') as file:
# Read binary data from the file

14 | P a g e
data = file.read()
# Process the binary data as needed
print(data)
Output:
Note that the output will depend on the contents of the "image.jpg" file. If the
file contains non-text binary data, decoding it as a string may not produce
meaningful results. In that case, you may need to use appropriate libraries or
methods to process the binary data based on its specific format or purpose, such as
image processing libraries for image files, audio processing libraries for audio files,
etc.

Print all of the unique words in the text file in alphabetical order
Assume that the example file named example.txt contains the following
contents: This is a sample text file.

It contains some words that are repeated. We need to find unique words and
sort them.
Example:
from string import whitespace

def sorted_words_file(fileName):
try:
# Open the file in a with statement to ensure it is properly closed
with open(fileName, 'r') as f:
lines = f.read()

# Split the text into words


wordList = lines.split()

# Remove surrounding whitespace and drop empty strings (if any)


wordList = [w.strip(whitespace) for w in wordList if w.strip(whitespace)]

# Get unique words and sort them


words = sorted(set(wordList))

print("Words in alphabetical order are:", words)

except FileNotFoundError:
print("File not found. Please enter a valid file name.")
except Exception as e:
print("An error occurred:", str(e))
15 | P a g e
# Get the input file name from the user
fileName = input("Enter the input file name: ")
sorted_words_file(fileName)

output:
Enter the input file name: example.txt
Words in alphabetical order are: ['AIDS', 'department', 'hello', 'is', 'this', 'world']

Python program that passes data between two processes using queue

Process in python:
In Python, a process refers to an instance of a running program that is separate from other
running programs. A process has its own memory space, resources, and execution context,
and it can communicate with other processes through inter-process communication (IPC)
mechanisms such as pipes, sockets, or queues. Python provides the multiprocessing module,
which allows for the creation, management, and communication of processes within a
Python program. Processes are useful for parallelizing tasks, improving performance, and
achieving concurrent execution of tasks. They can be used to perform tasks in the
background, handle multiple tasks simultaneously, or distribute tasks across multiple CPU
cores.

Multiprocessing in python:
In Python, multiprocessing is a technique that allows for concurrent execution of
multiple tasks in separate processes. It leverages the power of modern CPUs with multiple
cores to
execute tasks in parallel, thereby increasing the overall performance and efficiency of the
program. It enables Python programs to take advantage of multi-core processors and
perform tasks concurrently, resulting in faster execution times for CPU-bound or
parallelizable tasks. Python provides a built-in multiprocessing module that makes it easy
to implement multiprocessing in Python programs, allowing for efficient parallel
processing of tasks for improved performance.

Output:
Producer: Putting 0 into the queue
Consumer: Got 0 from the queue
Producer: Putting 1 into the queue
Consumer: Got 1 from the queue
Producer: Putting 2 into the queue
Consumer: Got 2 from the queue
16 | P a g e
Producer: Putting 3 into the queue
Consumer: Got 3 from the queue
Producer: Putting 4 into the queue
Consumer: Got 4 from the queue
Producer: Exiting
Consumer: Exiting

17 | P a g e
Week4:
Write a program to implement the followings:
 Find whether or not the triangle is a right triangle
 Define module to find Fibonacci Numbers & import the module to
another program
 Define a module and import a specific function in that module to another
program
Description:
 A right triangle is a type of triangle in which one of the interior angles
measures 90 degrees (π/2 radians). The side opposite to this angle is called the
hypotenuse, while the other two sides are called the legs. The Pythagorean theorem is a
fundamental concept in mathematics that applies to right triangles. It states that in a right
triangle, the square of the length of the hypotenuse is equal to the sum of the squares of
the lengths of the other two sides.
 If we have a triangle with side lengths a, b, and c, where c is the length of the
hypotenuse, we can determine whether or not it is a right triangle by verifying if the
following equation holds true:
c^2= a^2+ b^2
 If this equation is true, then the triangle is a right triangle. If it is not true, then
the triangle is not a right triangle.
Program:
def is_right_triangle(a, b, c):
# Sort the sides in ascending order
sides = [a, b, c]
sides.sort()

# Check the Pythagorean theorem


if sides[0]**2 + sides[1]**2 == sides[2]**2:
return True
else:
return False

# Example usage:
a = float(input("Enter the length of side a: "))
b = float(input("Enter the length of side b: "))
c = float(input("Enter the length of side c: "))

if is_right_triangle(a, b, c):
print("The triangle is a right triangle.")
else:
print("The triangle is not a right triangle.")
Output:

18 | P a g e
Enter the length of side a: 3
Enter the length of side b: 4
Enter the length of side c: 5
The triangle is a right triangle.

Define module to find Fibonacci Numbers & import the module to another
program
# Function for nth Fibonacci number

def Fibonacci(n):
if n<= 0:

print("Incorrect input")
# First Fibonacci number is 0
elif n == 1:

return 0
# Second Fibonacci number is 1
elif n == 2:

return 1
else:

return Fibonacci(n-1)+Fibonacci(n-2)

# Driver Program

print(Fibonacci(10))
Output:
34

In Python, a module is a file containing Python definitions and statements that


can be imported and used in other Python programs. A module can contain any
number of functions, classes, variables, or other objects.
To use a function from a module in another program, we first need to import
the module using the import statement. We can then call a specific function from
the module using the dot notation.

module_name.function_name().

19 | P a g e
Here's an example of how to define a module with multiple functions and
how to import a specific function from that module into another program.
def func1():
print("This is function 1.")

def func2():
print("This is function 2.")

def func3():
print("This is function 3.")
In this module, we define three functions: func1, func2, and func3.

main.py program:

python code:

from mymodule import func2 # Example usage func2()

In this program, we use the from keyword to import only the func2 function from the
mymodule module. We then call func2() to execute the function.

When we run this program, it will only execute func2 and output the string
"This is function
2." to the console.

Alternatively, we could import all the functions from the mymodule module using the
* symbol, like this:

Python code

from mymodule import * # Example usage func1() func2() func3()

This code would import all three functions from the mymodule module and
allow us to call them individually. However, it is generally recommended to only
import the specific functions you need to avoid namespace collisions and
improve code readability.

20 | P a g e
21 | P a g e
sWeek 5:
 Write a program to implement the following object oriented concepts:
 Use of Classes and Objects
 Inheritance
 Polymorphism (Overloading & Overriding)

Description:

Python Classes
A class is considered as a blueprint of objects. We can think of the class as a sketch
(prototype) of a house. It contains all the details about the floors, doors, windows, etc.
Based on these descriptions we build the house. House is the object.Since many houses
can be made from the same description, we can create many objects from a class.
Define Python Class:
We use the class keyword to create a class in Python. For example,
Syntax:
class
ClassName:
# class
definition
Python Objects
An object is called an instance of a class. For example, suppose Bike is a class then
we can create objects like bike1, bike2, etc from the class.
Here's the syntax to create
an object. Syntax:
objectName = ClassName()
Example 1: Python Class and Objects
# Define a class named Bike
class Bike:
name = ""
gear = 0

# Create an object of the Bike class


bike1 = Bike()

# Access attributes and assign new values


bike1.gear = 11

22 | P a g e
bike1.name = "Mountain Bike"

# Print the values of the attributes


print(f"Name: {bike1.name}, Gears: {bike1.gear}")

Output:
Name: Mountain Bike, Gears: 11
INHERITANCE:
One of the core concepts in object-oriented programming (OOP) languages is
inheritance. It is a mechanism that allows you to create a hierarchy of classes that share
a set of properties and methods by deriving a class from another class. Inheritance is the
capability of one class to derive or inherit the properties from another class.
It provides the reusability of a code. We don’t have to write the same code again and
again. Also, it allows us to add more features to a class without modifying it.
Single inheritance: When a child class inherits from only one parent class, it is called
single inheritance. We saw an example above.
Code:

Output:

Multiple inheritances: When a child class inherits from multiple parent


classes, it is called multiple inheritances.
Code:

23 | P a g e
Output:

Multilevel inheritance: When we have a child and grandchild relationship.

Example:

24 | P a g e
Output:

Geek1 23 Noida
Hierarchical inheritance: More than one derived class are created from a
single base.

Example:

25 | P a g e
Output:

Hybrid inheritance: This form combines more than one form of inheritance.
Basically, it is a blend of more than one type of inheritance.
Example:

26 | P a g e
Output:

POLYMORPHISM (OVERLOADING & OVER RIDING):

What is Polymorphism: The word polymorphism means having many forms. In


programming, polymorphism means the same function name (but different signatures)
being used for different types. The key difference is the data types and number of
arguments used in function.
Method Overriding
In method overriding we have the same name method with the same number of
arguments but not in the same class so that where the inheritance concept comes into the
picture. The method overriding concept is very much important in software
industries.
Example:

27 | P a g e
Output:

Here, we can see that the methods such as str (), which have not been overridden in
the child classes, are used from the parent class.

28 | P a g e
Due to polymorphism, the Python interpreter automatically recognizes that the fact()
method for object a(Square class) is overridden. So, it uses the one defined in the child
class.
On the other hand, since the fact() method for object b isn't overridden, it is used
from the Parent Shape class.
Method Overloading
Method overloading means a class containing multiple methods with the same name
but may have different arguments. Basically python does not support method
overloading, but there are several ways to achieve method overloading. Though method
overloading can be achieved, the last defined methods can only be usable.
Let’s take an example for better understanding
Let’s consider a class A, within the class we have taken a function show which has a
constructor self and arguments whose default values assigned are None and None. Then
I have created an object and called the function with the object obj.show, but I didn’t pass
any argument though it will print None and None cause in the function part we assigned
the default values.
Example:

Output:
None None
10 20

29 | P a g e
Week 6:
Write A programs to implement the following using an array.
Stack ADT, Queue ADT
Description:
A stack is a data structure that follows the Last-In-First-Out (LIFO) principle, meaning
that the last item added to the stack is the first item to be removed. This data structure is
widely used in computer science and programming, and it has its own abstract data type
(ADT) called the stack ADT.
The stack ADT defines the following operations:
Push: Adds an element to the top of the stack.
Pop: Removes the top element from the stack and returns it. Peek: Returns the top

element of the stack without removing it. Size: Returns the number of elements in the

stack.

IsEmpty: Returns a boolean value indicating whether the stack is empty or not.
The implementation of the stack ADT can be done using arrays or linked lists. Here is
a brief explanation of each implementation:
Array implementation:
In this implementation, we use an array to store the elements of the stack. We maintain
a variable called "top" that stores the index of the top element of the stack. When an
element is pushed onto the stack, we increment the "top" variable and add the element at
that index. Similarly, when an element is popped from the stack, we return the element at
the "top" index and decrement the "top" variable. The size of the stack can be calculated
by subtracting the index of the top element from the size of the array.
Linked list implementation:
In this implementation, we use a singly linked list to store the elements of the stack.
Each node of the linked list contains a data element and a pointer to the next node. The
top of the stack is represented by the head of the linked list. When an element is pushed
onto the stack, we create a new node and make it the new head of the linked list. When
an element is popped from the stack, we return the data element of the head node and
make the next node the new head of the linked list. The size of the stack can be calculated
by traversing the linked list and counting the number of nodes.
Stacks have many real-world applications, including in compilers, operating systems,
and web browsers. They are commonly used to implement function calls and recursion in
programming languages.

30 | P a g e
Code:

Output:

31 | P a g e
32 | P a g e
Queues:
Description:
A Queue ADT (Abstract Data Type) is a collection of elements that supports two basic
operations: enqueue and dequeue. A queue is a data structure where the elements are
stored in a particular order that represents a queue, i.e., the first element added to the
queue is the first one to be removed.
The queue ADT is a powerful tool used in computer programming to help manage
various processes. For example, it is commonly used in operating systems to manage
processes that are waiting for access to resources or in network communications to
manage incoming requests.
The following are the basic operations of a queue ADT
1. enqueue(element): This operation adds an element to the back
of the queue. If the queue is full, it will not allow you to add an
element.
2. dequeue(): This operation removes the element from the front of
the queue. If the queue is empty, it will not allow you to remove
an element.
3. front(): This operation returns the element at the front of the
queue without removing it.
4. size(): This operation returns the number of elements in the queue.
5. isEmpty(): This operation returns True if the queue is empty, and False
otherwise.
In a queue, the elements are stored in a linear order, and the operations are performed
on both ends of the queue. The front end of the queue is called the "head," and the back
end of the queue is called the "tail." Elements are added to the tail end of the queue and
removed from the head end of the queue.
Queues can be implemented using various data structures, such as arrays, linked lists,
or circular buffers. Each implementation has its advantages and disadvantages in terms
of time complexity, space complexity, and ease of use.
For example, a queue implemented using a linked list allows for efficient insertion and
deletion of elements, while a queue implemented using an array allows for constant
time access to elements. A circular buffer can combine the best features of both an
array and a linked list, allowing for efficient insertion and deletion of elements, as well
as constant time access to elements.
Overall, a queue ADT is a fundamental data structure used in computer programming
and is a valuable tool for managing processes and tasks that need to be executed in a

33 | P a g e
specific order.
Example:
class Queue:
# To initialize the object
def __init__(self, c):
self.queue = []
self.front = self.rear = 0
self.capacity = c

# Function to insert an element at the rear of the queue


def queueEnqueue(self, data):
# Check if the queue is full
if self.rear == self.capacity:
print("\nQueue is full")
else:
# Insert element at the rear
self.queue.append(data)
self.rear += 1

# Function to delete an element from the front of the queue


def queueDequeue(self):
# If the queue is empty
if self.front == self.rear:
print("Queue is empty")
else:
# Pop the front element from the list
x = self.queue.pop(0)
self.rear -= 1

34 | P a g e
# Function to print queue elements
def queueDisplay(self):
if self.front == self.rear:
print("\nQueue is Empty")
else:
# Traverse front to rear to print elements
for i in self.queue:
print(i, "<--", end='')

# Print front of the queue


def queueFront(self):
if self.front == self.rear:
print("\nQueue is Empty")
else:
print("\nFront Element is:", self.queue[self.front])

# Driver code
if __name__ == '__main__':
# Create a new queue of capacity 4
q = Queue(4)

# Print queue elements


q.queueDisplay()

# Inserting elements in the queue


q.queueEnqueue(20)
q.queueEnqueue(30)
q.queueEnqueue(40)
q.queueEnqueue(50)

35 | P a g e
# Print queue elements
q.queueDisplay()

# Insert element in the queue


q.queueEnqueue(60)

# Print queue elements


q.queueDisplay()

q.queueDequeue()
q.queueDequeue()
print("\n\nafter two node deletion\n")

# Print queue elements


q.queueDisplay()

# Print front of the queue


q.queueFront()
Output:

36 | P a g e
37 | P a g e
Week 7:
Write programs to implement the following using a singly linked list.
Stack ADT, Queue ADT

Description:

Singly linked list:

A singly linked list in Python is a linear data structure consisting of a sequence of


nodes, where each node contains a value and a reference (or link) to the next node in
the list. The first node in the list is called the "head", and the last node is typically
marked with a reference to None, indicating the end of the list.
In a singly linked list, each node has only one reference, which is to its next node in
the list. This makes traversal of the list possible only in one direction, typically from
the head to the tail. To access a particular node in the list, one must start from the head
and follow the next references until the desired node is reached.

Stacks using singly linked list:


To implement a stack using the singly linked list concept, all the singly linked list
operations should be performed based on Stack operations LIFO(last in first out) and
with the help of that knowledge, we are going to implement a stack using a singly
linked list.
So we need to follow a simple rule in the implementation of a stack which is last in
first out and all the operations can be performed with the help of a top variable. Let us
learn how to perform Pop, Push, Peek, and Display operations.
Example:
class Node:
def __init__(self, value):
self.value = value
self.next = None

38 | P a g e
class Stack:
def __init__(self):
self.head = None
self.size = 0

def is_empty(self):
"""Check if the stack is empty."""
return self.head is None

def push(self, value):


"""Add an element to the top of the stack."""
new_node = Node(value)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
self.size += 1

def pop(self):
"""Remove and return the element from the top of the stack."""
if self.head is None:
raise IndexError("Stack is empty")
popped_value = self.head.value
self.head = self.head.next
self.size -= 1
return popped_value

39 | P a g e
def peek(self):
"""Return the element from the top of the stack without removing it."""
if self.head is None:
raise IndexError("Stack is empty")
return self.head.value

def get_size(self):
"""Return the number of elements in the stack."""
return self.size

if __name__ == '__main__':
# Create a stack object
stack = Stack()

# Push elements onto the stack


stack.push(1)
stack.push(2)
stack.push(3)

# Pop elements from the stack and print them


print("Popped elements from the stack:")
while not stack.is_empty():
print(stack.pop())

# Get the size of the stack


print("Size of the stack:", stack.get_size())
Output:

40 | P a g e
Popped elements from the stack:
3
2
1
Size of the stack: 0
Single linked list using Queues:
Queues in Python are a type of data structure that follows the First-In, First-Out (FIFO)
principle. They allow elements to be inserted at the rear (enqueue) and removed from
the front (dequeue). Queues can be implemented using built-in data structures like lists
or by using specialized queue data structures from the queue module in Python's
standard library. Queues are commonly used in scenarios where elements need to be
processed in the order they are added, such as in message queues, task scheduling, or
job processing systems.

Program:
class Node:
def __init__(self, value):
self.value = value
self.next = None

class Stack:
def __init__(self):
self.head = None
self.size = 0

def is_empty(self):
"""Check if the stack is empty."""
return self.head is None

def push(self, value):


"""Add an element to the top of the stack."""

41 | P a g e
new_node = Node(value)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
self.size += 1

def pop(self):
"""Remove and return the element from the top of the stack."""
if self.head is None:
raise IndexError("Stack is empty")
popped_value = self.head.value
self.head = self.head.next
self.size -= 1
return popped_value

def peek(self):
"""Return the element from the top of the stack without removing it."""
if self.head is None:
raise IndexError("Stack is empty")
return self.head.value

def get_size(self):
"""Return the number of elements in the stack."""
return self.size

if __name__ == '__main__':
# Create a stack object

42 | P a g e
stack = Stack()

# Push elements onto the stack


stack.push(1)
stack.push(2)
stack.push(3)

# Pop elements from the stack and print them


print("Popped elements from the stack:")
while not stack.is_empty():
print(stack.pop())

# Get the size of the stack


print("Size of the stack:", stack.get_size())
Output:
10
20
False
2

43 | P a g e

You might also like