Andhra Loyola Institute of Engineering and Technology
Department of Electronics and Communication Engineering
A Hand Book of
Data Structures using Python Lab
II ECE I Semester
Name of the Student :
Roll No :
Year, Branch & Section :
DATA STRUCTURES USING PYTHON
List of Experiments
1. Write a Python program for class, Flower, that has three instance variables of type str,
int, and float that respectively represent the name of the flower, its number of petals,
and its price. Your class must include a constructor method that initializes each
variable to an appropriate value, and your class should include methods for setting the
value of each type, and retrieving the value of each type.
2. Develop an inheritance hierarchy based upon a Polygon class that has abstract
methods area( ) and perimeter( ). Implement classes Triangle, Quadrilateral,
Pentagon, that extend this base class, with the obvious meanings for the area( ) and
perimeter( ) methods. Write a simple program that allows users to create polygons of
the various types and input their geometric dimensions, and the program then outputs
their area and perimeter
3. Write a python program to implement Method Overloading and Method Overriding.
4. Write a Python program to illustrate the following comprehensions: a) List
Comprehensions b) Dictionary Comprehensions c) Set Comprehensions d) Generator
Comprehensions
5. Write a Python program to generate the combinations of n distinct objects taken from
the elements of a given list. Example: Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Combinations of 2 distinct objects: [1, 2] [1, 3] [1, 4] [1, 5] .... [7, 8] [7, 9] [8, 9].
6. Write a program for Linear Search and Binary search.
7. Write a program to implement Bubble Sort and Selection Sort.
8. Write a program to implement Merge sort and Quick sort.
9. Write a program to implement Stacks and Queues.
10. Write a program to implement Singly Linked List.
11. Write a program to implement Doubly Linked list.
12. Write a program to implement Binary Search Tree.
# Python Fundamentals
# 1. Variables and Data Types
# ----------------------------
# Numeric Types
integer_var = 10
float_var = 10.5
complex_var = 2 + 3j
# String Type
string_var = "Hello, Python!"
# Boolean Type
bool_var = True
# None Type
none_var = None
# Collection Types
list_var = [1, 2, 3, 4, 5]
tuple_var = (1, 2, 3, 4, 5)
set_var = {1, 2, 3, 4, 5}
dict_var = {'a': 1, 'b': 2, 'c': 3}
# Printing Variables
print("Integer:", integer_var)
print("Float:", float_var)
print("Complex:", complex_var)
print("String:", string_var)
print("Boolean:", bool_var)
print("None:", none_var)
print("List:", list_var)
print("Tuple:", tuple_var)
print("Set:", set_var)
print("Dictionary:", dict_var)
# 2. Control Structures
# ---------------------
# Conditional Statements
if integer_var < 20:
print("integer_var is less than 20")
elif integer_var == 20:
print("integer_var is equal to 20")
else:
print("integer_var is greater than 20")
# Looping Statements
# While Loop
counter = 0
while counter < 5:
print("Counter:", counter)
counter += 1
# For Loop
for item in list_var:
print("Item:", item)
# Break and Continue
for number in range(10):
if number == 5:
break # Exits the loop
if number % 2 == 0:
continue # Skips the rest of the loop body
print("Number:", number)
# 3. Functions
# ------------
def greet(name):
"""Function to greet a person"""
return f"Hello, {name}!"
print(greet("Alice"))
def add(a, b):
"""Function to add two numbers"""
return a + b
print("Addition:", add(5, 3))
# Lambda Functions
square = lambda x: x * x
print("Square of 5:", square(5))
# 4. Classes and Objects
# ----------------------
class Person:
"""Class representing a person"""
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"My name is {self.name} and I am {self.age} years old."
# Creating an Object
person1 = Person("John", 30)
print(person1.introduce())
# Inheritance
class Employee(Person):
"""Class representing an employee, inheriting from Person"""
def __init__(self, name, age, employee_id):
super().__init__(name, age)
self.employee_id = employee_id
def work(self):
return f"{self.name} is working with employee ID: {self.employee_id}"
employee1 = Employee("Jane", 28, "E12345")
print(employee1.introduce())
print(employee1.work())
# 5. Modules and Packages
# -----------------------
# Importing Modules
import math
print("Square root of 16:", math.sqrt(16))
# Importing Specific Functions
from math import pow
print("2 to the power of 3:", pow(2, 3))
# 6. File Input/Output
# ---------------------
# Writing to a File
with open('example.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("This is a file example.")
# Reading from a File
with open('example.txt', 'r') as file:
content = file.read()
print("File Content:\n", content)
# 7. Exception Handling
# ----------------------
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Error:", e)
finally:
print("This block executes no matter what")
# 8. Comprehensions
# ------------------
# List Comprehension
squares = [x**2 for x in range(10)]
print("Squares:", squares)
# Dictionary Comprehension
square_dict = {x: x**2 for x in range(10)}
print("Square Dictionary:", square_dict)
# 9. Generators
# --------------
def fibonacci(n):
"""Generator for Fibonacci sequence"""
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print("Fibonacci Sequence:", list(fibonacci(10)))
# 10. Decorators
# ---------------
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print(f"Wrapper executed before {original_function.__name__}")
return original_function(*args, **kwargs)
return wrapper_function
@decorator_function
def display():
print("Display function executed")
display()
6-point procedure to run Python code in Google Colab:
1. Visit Google Colab in your web browser.You may need to sign in with your Google account if you
aren't already signed in.
2. Click on the "New Notebook" button, or go to "File" > "New notebook" to create a new Colab
notebook.
3. In the new notebook, click on the code cell (or press Ctrl + M followed by B to insert a new code
cell).Write or paste your Python code into the cell.
4. Click the "Run" button (play icon) on the left side of the code cell, or press Shift + Enter to execute
the code.The output will be displayed below the code cell.
5. If your code requires external libraries, you can install them using pip within a code cell: for
eg: !pip install numpy and then import the library in another code cell or the same.
6.To save your notebook, click on "File" > "Save" or press Ctrl + S.You can share your notebook by
clicking the "Share" button at the top right corner and adjusting the sharing settings.
Sample Questions and Codes:
1. How do you define and print variables of different data types in Python?
# Define variables of different data types
integer_var = 42
float_var = 3.14
string_var = "Hello, World!"
bool_var = True
# Print the variables
print("Integer:", integer_var)
print("Float:", float_var)
print("String:", string_var)
print("Boolean:", bool_var)
2. How do you use conditional statements to check if a number is positive, negative, or zero?
number = 5
if number > 0:
print("The number is positive")
elif number < 0:
print("The number is negative")
else:
print("The number is zero")
3. How do you write a while loop to print numbers from 0 to 4?
counter = 0
while counter < 5:
print("Counter:", counter)
counter += 1
4. How do you define and call a function that adds two numbers?
def add(a, b):
"""Function to add two numbers"""
return a + b
result = add(3, 7)
print("Addition Result:", result)
5. How do you create a class in Python with an initializer and a method, then create an object
of that class?
class Dog:
"""Class representing a dog"""
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} is barking."
# Create an object of the Dog class
my_dog = Dog("Buddy", 5)
print(my_dog.bark())
6. How do you import a module and use a function from it in Python?
import math
# Use the sqrt function from the math module
print("Square root of 16:", math.sqrt(16))
7. How do you read the contents of a file in Python?
with open('example.txt', 'r') as file:
content = file.read()
print("File Content:\n", content)
8. How do you handle a division by zero exception in Python?
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Error:", e)
9. How do you use a list comprehension to create a list of squares of numbers from 0 to 9?
squares = [x**2 for x in range(10)] print("Squares:", squares)
10.How do you define and use a decorator in Python?
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Experiment -1
Write a Python program for class, Flower, that has three instance variables of type str,
int, and float that respectively represent the name of the flower, its number of petals,
and its price. Your class must include a constructor method that initializes each
variable to an appropriate value, and your class should include methods for setting the
value of each type, and retrieving the value of each type.
Python Code:
class Flower:
def __init__(self, name: str, petals: int, price: float):
self._name = name
self._petals = petals
self._price = price
def set_name(self, name: str):
self._name = name
def set_petals(self, petals: int):
self._petals = petals
def set_price(self, price: float):
self._price = price
def get_name(self) -> str:
return self._name
def get_petals(self) -> int:
return self._petals
def get_price(self) -> float:
return self._price
# Example usage:
# flower = Flower("Rose", 32, 10.5)
# print(flower.get_name()) # Output: Rose
# flower.set_price(12.0)
# print(flower.get_price()) # Output: 12.0
Experiment-2
Develop an inheritance hierarchy based upon a Polygon class that has abstract
methods area( ) and perimeter( ). Implement classes Triangle, Quadrilateral,
Pentagon, that extend this base class, with the obvious meanings for the area( ) and
perimeter( ) methods. Write a simple program that allows users to create polygons of
the various types and input their geometric dimensions, and the program then outputs
their area and perimeter
Python Code:
from abc import ABC, abstractmethod
class Polygon(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Triangle(Polygon):
def __init__(self, base: float, height: float, side1: float, side2: float, side3: float):
self.base = base
self.height = height
self.side1 = side1
self.side2 = side2
self.side3 = side3
def area(self) -> float:
return 0.5 * self.base * self.height
def perimeter(self) -> float:
return self.side1 + self.side2 + self.side3
class Quadrilateral(Polygon):
def __init__(self, side1: float, side2: float, side3: float, side4: float):
self.side1 = side1
self.side2 = side2
self.side3 = side3
self.side4 = side4
def area(self) -> float:
# Assuming it's a rectangle for simplicity
return self.side1 * self.side2
def perimeter(self) -> float:
return self.side1 + self.side2 + self.side3 + self.side4
class Pentagon(Polygon):
def __init__(self, side: float):
self.side = side
def area(self) -> float:
# Assuming regular pentagon
from math import tan, pi
return (5 * self.side ** 2) / (4 * tan(pi / 5))
def perimeter(self) -> float:
return 5 * self.side
# Example usage:
# triangle = Triangle(3, 4, 3, 4, 5)
# print(triangle.area()) # Output: 6.0
# print(triangle.perimeter()) # Output: 12
# quadrilateral = Quadrilateral(4, 5, 4, 5)
# print(quadrilateral.area()) # Output: 20
# print(quadrilateral.perimeter()) # Output: 18
# pentagon = Pentagon(5)
# print(pentagon.area()) # Output: 43.01193501472417
# print(pentagon.perimeter()) # Output: 25
Experiment-3
Write a python program to implement Method Overloading and Method Overriding.
Code:
class MethodOverloading:
def add(self, a: int, b: int, c: int = 0) -> int:
return a + b + c
class Parent:
def display(self):
print("Parent class method")
class Child(Parent):
def display(self):
print("Child class method")
# Example usage:
# overload = MethodOverloading()
# print(overload.add(1, 2)) # Output: 3
# print(overload.add(1, 2, 3)) # Output: 6
# parent = Parent()
# parent.display() # Output: Parent class method
# child = Child()
# child.display() # Output: Child class method
Experiment 4:
Write a Python program to illustrate the following comprehensions: a) List
Comprehensions b) Dictionary Comprehensions c) Set Comprehensions d) Generator
Comprehensions
# a) List Comprehensions
squares = [x**2 for x in range(10)]
# b) Dictionary Comprehensions
square_dict = {x: x**2 for x in range(10)}
# c) Set Comprehensions
square_set = {x**2 for x in range(10)}
# d) Generator Comprehensions
square_gen = (x**2 for x in range(10))
# Example usage:
# print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# print(square_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
# print(square_set) # Output: {0, 1, 4, 36, 9, 16, 49, 25, 64, 81}
# print(list(square_gen)) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Experiment-5
Write a Python program to generate the combinations of n distinct objects taken from
the elements of a given list. Example: Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Combinations of 2 distinct objects: [1, 2] [1, 3] [1, 4] [1, 5] .... [7, 8] [7, 9] [8, 9]
Python code:
from itertools import combinations
def generate_combinations(lst, n):
return list(combinations(lst, n))
# Example usage:
# original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# comb = generate_combinations(original_list, 2)
# print(comb) # Output: [(1, 2), (1, 3), (1, 4), ..., (8, 9)]
Experiment -6
Write a program for Linear Search and Binary search.
Code:
def linear_search(arr, target):
for i, value in enumerate(arr):
if value == target:
return i
return -1
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
# Example usage:
# arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# print(linear_search(arr, 4)) # Output: 3
# print(binary_search(arr, 4)) # Output: 3
Experiment -7
Write a program to implement Bubble Sort and Selection Sort.
Code:
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
# Example usage:
# arr = [64, 34, 25, 12, 22, 11, 90]
# bubble_sort(arr)
# print(arr) # Output: [11, 12, 22, 25, 34, 64, 90]
# arr = [64, 34, 25, 12, 22, 11, 90]
# selection_sort(arr)
# print(arr) # Output: [11, 12, 22, 25, 34, 64, 90]
Experiment 8
Write a program to implement Merge sort and Quick sort.
Code:
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
L = arr[:mid]
R = arr[mid:]
merge_sort(L)
merge_sort(R)
i=j=k=0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
less = [x for x in arr[1:] if x <= pivot]
greater = [x for x in arr[1:] if x > pivot]
return quick_sort(less) + [pivot] + quick_sort(greater)
# Example usage:
# arr = [12, 11, 13, 5, 6, 7]
# merge_sort(arr)
# print(arr) # Output: [5, 6, 7, 11, 12, 13]
# arr = [10, 7, 8, 9, 1, 5]
# sorted_arr = quick_sort(arr)
# print(sorted_arr) # Output: [1, 5, 7, 8, 9, 10]
Experiment 9
Write a program to implement Stacks and Queues.
class Stack:
def __init__(self):
self.stack = []
def is_empty(self):
return len(self.stack) == 0
def push(self, item):
self.stack.append(item)
def pop(self):
if self.is_empty():
raise IndexError("Pop from empty stack")
return self.stack.pop()
def peek(self):
if self.is_empty():
raise IndexError("Peek from empty stack")
return self.stack[-1]
def size(self):
return len(self.stack)
class Queue:
def __init__(self):
self.queue = []
def is_empty(self):
return len(self.queue) == 0
def enqueue(self, item):
self.queue.append(item)
def dequeue(self):
if self.is_empty():
raise IndexError("Dequeue from empty queue")
return self.queue.pop(0)
def size(self):
return len(self.queue)
# Example usage:
# stack = Stack()
# stack.push(1)
# stack.push(2)
# print(stack.pop()) # Output: 2
# print(stack.peek()) # Output: 1
# queue = Queue()
# queue.enqueue(1)
# queue.enqueue(2)
# print(queue.dequeue()) # Output: 1
# print(queue.size()) # Output: 1
Experiment-10
Write a program to implement Singly Linked List.
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
def display(self):
current = self.head
while current:
print(current.data, end=' ')
current = current.next
print()
# Example usage:
# sll = SinglyLinkedList()
# sll.append(1)
# sll.append(2)
# sll.append(3)
# sll.display() # Output: 1 2 3
Experiment-11
Write a program to implement Doubly Linked list.
class DNode:
def __init__(self, data=None):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = DNode(data)
if not self.head:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
new_node.prev = last
def display(self):
current = self.head
while current:
print(current.data, end=' ')
current = current.next
print()
# Example usage:
# dll = DoublyLinkedList()
# dll.append(1)
# dll.append(2)
# dll.append(3)
# dll.display() # Output: 1 2 3
Experiment-12
Write a program to implement Binary Search Tree
class DNode:
def __init__(self, data=None):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = DNode(data)
if not self.head:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
new_node.prev = last
def display(self):
current = self.head
while current:
print(current.data, end=' ')
current = current.next
print()
# Example usage:
# dll = DoublyLinkedList()
# dll.append(1)
# dll.append(2)
# dll.append(3)
# dll.display() # Output: 1 2 3