Data Structures Using Python Lab Record: Vishnupur, Narsapur, Medak (District) - 502313
Data Structures Using Python Lab Record: Vishnupur, Narsapur, Medak (District) - 502313
Data Structures Using Python Lab Record: Vishnupur, Narsapur, Medak (District) - 502313
(UGC Autonomous)
Vishnupur, Narsapur, Medak (District) – 502313
(Sri Vishnu Educational Society)
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?
you can declare a string using single quotes (1. Let's see an example
Example:
you can declare a string using double quotes (" "). Let's, see an example
you can declare a string using triple quotes (". Let's, see an example
Example:
2|Page
print("Hello Python Guides!!!")
Now let's run all these formats and see the output.
Using Operator:
Two strings can be concatenated in python using the operator between them. more than
two strings can be concatenated using operator.
The python List append () method is used for appending and adding elements to the end
of The List
Syntax: list.append(item)
parameters:
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
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: []
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]
The remove() method removes the first occurrence of a specified value from the list.
Example:
my_list=[1, 2, 3, 4, 5]
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.
# 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])
5|Page
print(college)
# print no of student
print(student)
OUTPUT:
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.
Example:
capital_City = {"Nepal":"Kathmandu", "Italy":"Rome","England":"London"}
print(capital_City)
output:
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.
capitalCity["Japan"] = "Tokyo"
studentID[112] = "Stan"
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".
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'}
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.
# 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.
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:
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:
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()
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()
# 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
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:
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
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
22 | P a g e
bike1.name = "Mountain Bike"
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:
23 | P a g e
Output:
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:
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
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='')
# Driver code
if __name__ == '__main__':
# Create a new queue of capacity 4
q = Queue(4)
35 | P a g e
# Print queue elements
q.queueDisplay()
q.queueDequeue()
q.queueDequeue()
print("\n\nafter two node deletion\n")
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:
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 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()
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
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()
43 | P a g e