0% found this document useful (0 votes)
200 views

DSAP Lab Manual PDF

The document provides details about the Data Structures and Algorithms using Python laboratory course. It includes 20 experiments on topics like classes and objects, operator overloading, inheritance, linked lists, stacks, queues, trees, graphs, and algorithms. The experiments involve creating classes for student, book, account, product, complex number, and employee. Methods are included to initialize objects, perform operations, and display outputs. Linked lists, stacks, queues, trees and graphs are implemented to perform various traversal and search operations. Sorting algorithms like insertion, selection, and bubble sort are also designed.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
200 views

DSAP Lab Manual PDF

The document provides details about the Data Structures and Algorithms using Python laboratory course. It includes 20 experiments on topics like classes and objects, operator overloading, inheritance, linked lists, stacks, queues, trees, graphs, and algorithms. The experiments involve creating classes for student, book, account, product, complex number, and employee. Methods are included to initialize objects, perform operations, and display outputs. Linked lists, stacks, queues, trees and graphs are implemented to perform various traversal and search operations. Sorting algorithms like insertion, selection, and bubble sort are also designed.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

Department of Electrical, Electronics and Communication Engineering

GITAM School of Technology

DATA STRUCTURES AND ALGORITHMS USING PYTHON8


Laboratory Manual
Code: 19EEC340
Semester: VI
Branch: ECE (AI & ML)
Prepared
By
Dr. P.Raju
Koteswara Rao Naik.R
Assistant Professor
Dept. Of EECE
GST, GITAM
Visakhapatnam

GITAM
(Deemed to be University 3U/S of UGC and Accredited by NAAC with 'A+ ' Grade)
Gandhi Nagar
Visakhapatnam-530045
DATA STRUCTURES AND ALGORITHMS WITH PYTHON LABORATORY

INDEX
List of Practical Experiments:

1. Write a program to create

• Student class with data members student rollno, name,address, course. Include a constructor to initialize data
members. Add a method to print the student details.
• Book class with data members book_id,name,cost and publisher. Include constructor and a method to display
the book details. Create 3 objects and display their details.
• Account class with data members acc_no,name,balance. Include a constructor and methods to perform deposit
and withdraw operations on account. Create account object perform some operations and display the account
details.
• Product class with data members product_id, product_name, price, expiry_date. Include constructor to
initialize data members and a method to print products details.
• Complex_Number with data members real_part and imaginary_part. Include constructor to initialize complex
number. Add a method which adds two complex numbers.
• Employee class with data members eno,ename,sal,designation. Include constructor to initialize employee
details and count the number of employee objects created.

2. Create a class called Distance. A person has to travel a certain distace and he used two cars. Now create two
objects “cardist1” and “cardist2” for the class Distance. Add the two objects distances and put the total distance in the
third object of class Distance “totaldist”. Take one data member, which will accept the distance input in km. Take two
functions, for accepting the distance and the other for displaying. Display the total distance in meters.

3. Develop a program to Perform Python Multi-Level and multiple inheritances.

4. Design a program to overload “+” operator for


• Concatenating two strings
• Adding two complex numbers
5. Develop a program to overload “area” method to calculate area of different polygon
shapes. Write a program to
• Implement Method Overriding
• Perform Linear Search on an array.
• Perform Binary Search on a list stored in an array.
9. Develop a program to implement various sorting techniques
• Insertion sort
• Selection Sort
• Bubble Sort
10. Design a program to create a singly linked list for the following operations
• Insert a Node at Beginning, at Ending and at a given Position
• Delete a Node at Beginning, at Ending and at a given Position
• Search, Count the Number of Nodes and Display
11. Design a program to create a doubly linked list for the following operations
• Insert a Node at Beginning, at Ending and at a given Position
• Delete a Node at Beginning, at Ending and at a given Position
• Search, Count the Number of Nodes and Display
12. Create a Circular singly linked list for adding and deleting a Node.
13. Create a stack and perform various operations on it.
14. Convert the infix expression into postfix form.
15. Perform String reversal using stack
16. Create a queue and perform various operations on it.
17. Construct a binary tree and perform various traversals.
18. Construct a binary search tree and perform search operation.
19. Implement Depth First Search, Breadth First Search traversals on a graph.
20. Implement Dijkstra’s Shortest Path Algorithm

Course Outcomes:
After Completion of this course, the student will be able to:
● Explain various ways of representing data in a computer (L2)
● Demonstrate operations on linear data structures (L2)
● Illustrate the mechanisms for creating, altering and traversing various types of trees (L2)
● Explain the representations, traversals and applications of graphs (L2)
● Analyze common sorting algorithms (L4)
● Choose a data structure that gives the best performance for a given application(L6)
1. Write a program to create

a) Student class with data members student rollno, name,address, course. Include a constructor to initialize
data members. Add a method to print the student details.

class Student:
rollno = 0
name = ""
address = ""
course = ""

def __init__(self,rollno,name,address,course):
self.rollno = rollno
self.name = name
self.address = address
self.course = course

def printDetails(self):
print(self.name,"(Roll no:",self.rollno,"), lives in/at",self.address,"and is enr
olled in",self.course)

student1 = Student(122010404027,"Abhishek","Vizag","ECE(AI&ML)")
student1.printDetails()

Output:
Abhishek (Roll no: 122010404027 ), lives in/at Vizag and is enrolled in ECE(AI&ML)

b) Book class with data members book_id,name,cost and publisher. Include constructor and a method to
display the book details. Create 3 objects and display their details.

class Book:
bookid = ""
name = ""
cost = 0
publisher = ""

def __init__(self,bookid,name,cost,publisher):
self.bookid = bookid
self.name = name
self.cost = cost
self.publisher = publisher

def showDetails(self):
print(self.bookid,self.name,": ₹",self.cost,"from",self.publisher)

harryPotter = Book("978-1408855652","Harry Potter and the Philosopher's Stone",309,"Bloomsbury")


percyJackson = Book("978-0141346809","Percy Jackson and the Lightning Thief",283,"Penguin")
wimpyKid = Book("978-0141324906","Diary Of A Wimpy Kid",251,"Penguin")
harryPotter.showDetails()
percyJackson.showDetails()
wimpyKid.showDetails()

Output:
978-1408855652 Harry Potter and the Philosopher's Stone: ₹ 309 from Bloomsbury
978-0141346809 Percy Jackson and the Lightning Thief: ₹ 283 from Penguin
978-0141324906 Diary Of A Wimpy Kid : ₹ 251 from Penguin

c) Account class with data members acc_no,name,balance. Include a constructor and methods to perform
deposit and withdraw operations on account. Create account object perform some operations and
display the account details.
class Account:
acc_no = 0
name = ""
balance = 0

def __init__(self,acc_no,name,balance):
self.acc_no = acc_no
self.name = name
self.balance = balance

def deposit(self,amount):
self.balance += amount

def withdraw(self,amount):
self.balance -= amount

myAccount = Account(100,"Abhishek",100000)
print(myAccount.balance)
myAccount.deposit(50000)
print(myAccount.balance)
myAccount.withdraw(25000)
print(myAccount.balance)

Output:
100000
150000
125000

d) Product class with data members product_id, product_name, price, expiry_date. Include constructor to
initialize data members and a method to print products details.

class Product:
product_id = 0
product_name = ""
price = 0
expiry_date = ""
def __init__(self,product_id,product_name,price,expiry_date):
self.product_id = product_id
self.product_name = product_name
self.price = price
self.expiry_date = expiry_date

def showProductDetails(self):
print("ID:",self.product_id,self.product_name,"₹",self.price,". Use by:",self.exp
iry_date)

noodles = Product(1,"Maggi",10,"31/12/2022")
biscuit = Product(2,"Hide & Seek",25,"4/4/2023")
cake = Product(3,"Chocolate Cake",100,"12/12/2022")

noodles.showProductDetails()
biscuit.showProductDetails()
cake.showProductDetails()

Output:
ID: 1 Maggi ₹ 10 . Use by: 31/12/2022
ID: 2 Hide & Seek ₹ 25 . Use by: 4/4/2023
ID: 3 Chocolate Cake ₹ 100 . Use by: 12/12/2022

e) Complex_Number with data members real_part and imaginary_part. Include constructor to initialize
complex number. Add a method which adds two complex numbers.
class ComplexNumber:
real_part = 0
imaginary_part = 0

def __init__(self,real_part,imaginary_part):
self.real_part = real_part
self.imaginary_part = imaginary_part

def add(a,b):
c = ComplexNumber(0,0)
c.real_part = a.real_part + b.real_part
c.imaginary_part = a.imaginary_part + b.imaginary_part
return c

a = ComplexNumber(3,4)
b = ComplexNumber(4,5)
sum = add(a,b)
print(sum.real_part,"+ i",sum.imaginary_part)

Output:
7 + i 9

f) Employee class with data members eno,ename,sal,designation. Include constructor to initialize employee
details and count the number of employee objects created.
class Count():
c = 0

count = Count()

class Employee:
eno = 0
ename = ""
sal = 0
designation = ""

def __init__(self,eno,ename,sal,designation):
self.eno = eno
self.ename = ename
self.sal = sal
self.designation = designation
count.c += 1

steve = Employee(0,"Steve Jobs",1,"CEO")


woz = Employee(1,"Steve Wozniak",0,"Co-founder")
phil = Employee(100,"Phil Schiller",100000000,"Fellow")
print(count.c)

Output:
3

2. Create a class called Distance. A person has to travel a certain distace and he used two cars. Now create
two objects “cardist1” and “cardist2” for the class Distance. Add the two objects distances and put the total
distance in the third object of class Distance “totaldist”. Take one data member, which will accept the distance
input in km. Take two functions, for accepting the distance and the other for displaying. Display the total
distance in meters.

class Distance:
distance = 0

def inputDistance(self):
self.distance = input("Enter the distance in km:")

def showDistance(self):
print(self.distance)

cardist1 = Distance()
cardist1.inputDistance()
cardist2 = Distance()
cardist2.inputDistance()

totaldist = Distance()
totaldist.distance = str(int(cardist1.distance)+int(cardist2.distance))
print("Total distance=",int(totaldist.distance)*1000,"m") # converting km to m

Output:
Enter the distance in km:5
Enter the distance in km:7
Total distance= 12000 m

3. Develop a program to Perform Python Multi-Level and multiple inheritances.

#Program to Perform Single, Multiple and Multi-level Inheritance in Python

# Single inheritence
class Apple:
manufacturer = 'Apple Inc'
contact_website = 'www.apple.com/contact'
name = 'Apple'

def contact_details(self):
print('Contact us at ', self.contact_website)

class MacBook(Apple):
def __init__(self):
self.year_of_manufacture = 2018

def manufacture_details(self):
print('This MacBook was manufactured in {0}, by {1}.'
.format(self.year_of_manufacture, self.manufacturer))

macbook = MacBook()
macbook.manufacture_details()

# Multiple inheritence
class OperatingSystem:
multitasking = True
name = 'Mac OS'

class MacTower(OperatingSystem, Apple):


def __init__(self):
if self.multitasking is True:
print('Multitasking system')

# if there are two superclasses with the sae attribute name


# the attribute of the first inherited superclass will be called
# the order of inhertence matters
print('Name: {}'.format(self.name))

mactower = MacTower()

# Multilevel inheritence
class MusicalInstrument:
num_of_major_keys = 12

class StringInstrument(MusicalInstrument):
type_of_wood = 'Tonewood'

class Guitar(StringInstrument):
def __init__(self):
self.num_of_strings = 6
print('The guitar consists of {0} strings,' +
'it is made of {1} and can play {2} keys.'
.format(self.num_of_strings,
self.type_of_wood, self.num_of_major_keys))

guitar = Guitar()

Output:
This MacBook was manufactured in 2018, by Apple Inc.
Multitasking system
Name: Mac OS
The guitar consists of {0} strings,it is made of Tonewood and can play 12 keys.

4. Design a program to overload “+” operator for

a) Concatenating two strings


s1="Tutorials"
s2="Point"
s3=s1+s2
s4=s1+" "+s2
print(s3)
print(s4)

Output:
TutorialsPoint
Tutorials Point

b) Adding two complex numbers


# Python program to add two complex numbers

def addComplex( z1, z2):


return z1 + z2

# Driver's code
z1 = complex(2, 3)
z2 = complex(1, 2)
print( "Addition is : ", addComplex(z1, z2))

Output:
Addition is : (3+5j)

5.Develop a program to overload “area” method to calculate area of different polygon shapes.
# Program for calculating the area of a shapes/polygon
def calculate_area(name):\

# converting all characters


# into lower cases
name = name.lower()

# check for the conditions


if name == "rectangle":
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth: "))

# calculate area of rectangle


rect_area = l * b
print(f"The area of rectangle is {rect_area}.")

elif name == "square":


s = int(input("Enter square's side length: "))
# calculate area of square
sqt_area = s * s
print(f"The area of square is {sqt_area}.")

elif name == "triangle":


h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length: "))

# calculate area of triangle


tri_area = 0.5 * b * h
print(f"The area of triangle is {tri_area}.")

elif name == "circle":


r = int(input("Enter circle's radius length: "))
pi = 3.14

# calculate area of circle


circ_area = pi * r * r
print(f"The area of circle is {circ_area}.")

elif name == 'parallelogram':


b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length: "))

# calculate area of parallelogram


para_area = b * h
print(f"The area of parallelogram is {para_area}.")

else:
print("Sorry! This shape is not available")
# driver code
if __name__ == "__main__" :

print("Calculate Shape Area")


shape_name = input("Enter the name of shape whose area you want to find: ")

# function calling
calculate_area(shape_name)

Output:
Calculate Shape Area
Enter the name of shape whose area you want to find: rectangle
Enter rectangle's length: 3
Enter rectangle's breadth: 5
The area of rectangle is 15.
6)Write a program to Perform Linear Search on an array.

#Linear Search program


def linear_search(alist, key):
"""Return index of key in alist. Return -1 if key not present."""
for i in range(len(alist)):
if alist[i] == key:
return i
return -1

alist = input('Enter the list of numbers: ')


alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))

index = linear_search(alist, key)


if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))

Output:
Case1:
Enter the list of numbers: 4 56 62 73 81 9 17 5
The number to search for: 73
73 was found at index 3.

Case2:
Enter the list of numbers: 4 2 7 9 11 77
The number to search for: 33
33 was not found.

7)Write a program to Perform Binary Search on a list stored in an array.

#Binary Search program


def binary_search(alist, start, end, key):
"""Search key in alist[start... end - 1]."""
if not start < end:
return -1

mid = (start + end)//2


if alist[mid] < key:
return binary_search(alist, mid + 1, end, key)
elif alist[mid] > key:
return binary_search(alist, start, mid, key)
else:
return mid

alist = input('Enter the sorted list of numbers: ')


alist = alist.split()
alist = [int(x) for x in alist]
key = int(input('The number to search for: '))

index = binary_search(alist, 0, len(alist), key)


if index < 0:
print('{} was not found.'.format(key))
else:
print('{} was found at index {}.'.format(key, index))

Output:
Enter the sorted list of numbers: 21 45 57 62 81 93
The number to search for: 45
45 was found at index 1.

8)Write a program to Implement Method Overriding


# Python program to demonstrate
# method overriding
# Defining parent class
class Parent():

# Constructor
def __init__(self):
self.value = "Inside Parent"

# Parent's show method


def show(self):
print(self.value)

# Defining child class


class Child(Parent):

# Constructor
def __init__(self):
self.value = "Inside Child"

# Child's show method


def show(self):
print(self.value)
# Driver's code
obj1 = Parent()
obj2 = Child()

obj1.show()
obj2.show()
Output:
Inside Parent
Inside Child
9. Develop a program to implement various sorting techniques
a) Insertion sort
def insertion_sort(InputList):
for i in range(1, len(InputList)):
j = i-1
nxt_element = InputList[i]
# Compare the current element with next one
while (InputList[j] > nxt_element) and (j >= 0):
InputList[j+1] = InputList[j]
j=j-1
InputList[j+1] = nxt_element
list = [19,2,31,45,30,11,121,27]
insertion_sort(list)
print(list)
Output:
[19, 2, 31, 45, 30, 11, 27, 121]

b) Selection Sort
#Selection Sort program
def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]
alist = input('Enter the list of numbers: ').split()
alist = [int(x) for x in alist]
selection_sort(alist)
print('Sorted list: ', end='')
print(alist)
Output:
Enter the list of numbers: 32 13 28 39 1 5 72 57
Sorted list: [1, 5, 13, 28, 32, 39, 57, 72]
c)Bubble Sort

# Bubble Sort program


def bubblesort(list):
# Swap the elements to arrange in order
for iter_num in range(len(list)-1,0,-1):
for idx in range(iter_num):
if list[idx]>list[idx+1]:
temp = list[idx]
list[idx] = list[idx+1]
list[idx+1] = temp
list = [19,2,31,62,11,33,5,20,100]
bubblesort(list)
print(list)

Output:
[2, 5, 11, 19, 20, 31, 33, 62, 100]
10. Design a program to create a singly linked list for the following operations

a)Insert a Node at Beginning, at Ending and at a given Position


# SLL insertion methods of linked list

# Node class
class Node:

# Function to initialise the node object


def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null

# Linked List class contains a Node object


class LinkedList:

# Function to initialize head


def __init__(self):
self.head = None

# Function to insert a new node at the beginning


def push(self, new_data):

# 1 & 2: Allocate the Node &


# Put in the data
new_node = Node(new_data)

# 3. Make next of new Node as head


new_node.next = self.head

# 4. Move the head to point to new Node


self.head = new_node

# This function is in LinkedList class. Inserts a


# new node after the given prev_node. This method is
# defined inside LinkedList class shown above */
def insertAfter(self, prev_node, new_data):

# 1. check if the given prev_node exists


if prev_node is None:
print("The given previous node must inLinkedList.")
return
# 2. create new node &
# Put in the data
new_node = Node(new_data)

# 4. Make next of new Node as next of prev_node


new_node.next = prev_node.next

# 5. make next of prev_node as new_node


prev_node.next = new_node

# This function is defined in Linked List class


# Appends a new node at the end. This method is
# defined inside LinkedList class shown above */
def append(self, new_data):

# 1. Create a new node


# 2. Put in the data
# 3. Set next as None
new_node = Node(new_data)

# 4. If the Linked List is empty, then make the


# new node as head
if self.head is None:
self.head = new_node
return

# 5. Else traverse till the last node


last = self.head
while (last.next):
last = last.next

# 6. Change the next of last node


last.next = new_node

# Utility function to print the linked list


def printList(self):
temp = self.head
while (temp):
print(temp.data,end=" ")
temp = temp.next

# Code execution starts here


if __name__=='__main__':

# Start with the empty list


llist = LinkedList()

# Insert 6. So linked list becomes 6->None


llist.append(6)

# Insert 7 at the beginning. So linked list becomes 7->6->None


llist.push(7);

# Insert 1 at the beginning. So linked list becomes 1->7->6->None


llist.push(1);

# Insert 4 at the end. So linked list becomes 1->7->6->4->None


llist.append(4)

# Insert 8, after 7. So linked list becomes 1 -> 7-> 8-> 6-> 4-> None
llist.insertAfter(llist.head.next, 8)

print('Created Single linked list is: ')


llist.printList()

Output:
Created Single linked list is:
17864

b)Delete a Node at Beginning, at Ending and at a given Position


# Deletion in singly linked list with class

# Node class

class Node:

# Constructor to initialize the node object


def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None

# Function to insert a new node at the beginning


def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Given a reference to the head of a list and a key,
# delete the first occurrence of key in linked list
def deleteNode(self, key):

# Store head node


temp = self.head

# If head node itself holds the key to be deleted


if (temp is not None):
if (temp.data == key):
self.head = temp.next
temp = None
return

# Search for the key to be deleted, keep track of the


# previous node as we need to change 'prev.next'
while(temp is not None):
if temp.data == key:
break
prev = temp
temp = temp.next

# if key was not present in linked list


if(temp == None):
return

# Unlink the node from linked list


prev.next = temp.next

temp = None

# Utility function to print the linked LinkedList


def printList(self):
temp = self.head
while(temp):
print(" %d" % (temp.data)),
temp = temp.next

# Driver program
llist = LinkedList()
llist.push(7)
llist.push(1)
llist.push(3)
llist.push(2)

print("Created Single Linked List: ")


llist.printList()
llist.deleteNode(1)
print("\nSingle Linked List after Deletion of 1:")
llist.printList()

Output:
Created Single Linked List:
2317

Single Linked List after Deletion of 1:


237

c)Search Number in SLL


# Iterative Python program to search
# an element in linked list

# Node class
class Node:

# Function to initialise the


# node object
def __init__(self, data):

# Assign data
self.data = data

# Initialize next as null


self.next = None

# Linked List class


class LinkedList:
def __init__(self):

# Initialize head as None


self.head = None

# This function insert a new node at the


# beginning of the linked list
def push(self, new_data):

# Create a new Node


new_node = Node(new_data)

# 3. Make next of new Node as head


new_node.next = self.head

# 4. Move the head to point to new Node


self.head = new_node
# This Function checks whether the value
# x present in the linked list
def search(self, x):

# Initialize current to head


current = self.head

# Loop till current not equal to None


while current != None:
if current.data == x:

# Data found
return True

current = current.next

# Data Not found


return False

# Driver code
if __name__ == '__main__':

# Start with the empty list


llist = LinkedList()

# Use push() to construct list


# 14->21->11->30->10
llist.push(10);
llist.push(30);
llist.push(11);
llist.push(21);
llist.push(14);
if llist.search(21):
print("Item found")
else:
print("Item not found")

Output:
Item found
11. Design a program to create a doubly linked list for the following operations
a)Insert a Node at Beginning, at Ending and at a given Position and display
# A program to demonstrate all insertion methods of DLL

class Node:

# Constructor to create a new node


def __init__(self, data):
self.data = data
self.next = None
self.prev = None

# Class to create a Doubly Linked List

class DoublyLinkedList:

# Constructor for empty Doubly Linked List


def __init__(self):
self.head = None
# Given a reference to the head of a list and an
# integer, inserts a new node on the front of list
def push(self, new_data):

# 1. Allocates node
# 2. Put the data in it
new_node = Node(new_data)

# 3. Make next of new node as head and


# previous as None (already None)
new_node.next = self.head

# 4. change prev of head node to new_node


if self.head is not None:
self.head.prev = new_node

# 5. move the head to point to the new node


self.head = new_node

# Given a node as prev_node, insert a new node after


# the given node
def insertAfter(self, prev_node, new_data):

# 1. Check if the given prev_node is None


if prev_node is None:
print("the given previous node cannot be NULL")
return

# 2. allocate new node


# 3. put in the data
new_node = Node(new_data)

# 4. Make net of new node as next of prev node


new_node.next = prev_node.next

# 5. Make prev_node as previous of new_node


prev_node.next = new_node

# 6. Make prev_node ass previous of new_node


new_node.prev = prev_node

# 7. Change previous of new_nodes's next node


if new_node.next:
new_node.next.prev = new_node
# Given a reference to the head of DLL and integer,
# appends a new node at the end
def append(self, new_data):

# 1. Allocates node
# 2. Put in the data
new_node = Node(new_data)

# 3. This new node is going to be the last node,


# so make next of it as None
# (It already is initialized as None)

# 4. If the Linked List is empty, then make the


# new node as head
if self.head is None:
self.head = new_node
return

# 5. Else traverse till the last node


last = self.head
while last.next:
last = last.next

# 6. Change the next of last node


last.next = new_node

# 7. Make last node as previous of new node


new_node.prev = last

return

# This function prints contents of linked list


# starting from the given node
def printList(self, node):

print("\nTraversal in forward direction")


while node:
print(" {}".format(node.data))
last = node
node = node.next

print("\nTraversal in reverse direction")


while last:
print(" {}".format(last.data))
last = last.prev

# Driver code
# Start with empty list
if __name__ == "__main__":
llist = DoublyLinkedList()

# Insert 6. So the list becomes 6->None


llist.append(6)

# Insert 7 at the beginning.


# So linked list becomes 7->6->None
llist.push(7)

# Insert 1 at the beginning.


# So linked list becomes 1->7->6->None
llist.push(1)

# Insert 4 at the end.


# So linked list becomes 1->7->6->4->None
llist.append(4)

# Insert 8, after 7.
# So linked list becomes 1->7->8->6->4->None
llist.insertAfter(llist.head.next, 8)

print(" DLL after Insertion is: ")


llist.printList(llist.head)

Output:
DLL after Insertion is:

Traversal in forward direction


17864

Traversal in reverse direction


46871

b)Delete a Node at Beginning, at Ending and at a given Position


# Program to delete a node in a doubly-linked list

# for Garbage collection


import gc

# A node of the doubly linked list


class Node:

# Constructor to create a new node


def __init__(self, data):
self.data = data
self.next = None
self.prev = None

class DoublyLinkedList:
# Constructor for empty Doubly Linked List
def __init__(self):
self.head = None

# Function to delete a node in a Doubly Linked List.


# head_ref --> pointer to head node pointer.
# dele --> pointer to node to be deleted

def deleteNode(self, dele):

# Base Case
if self.head is None or dele is None:
return

# If node to be deleted is head node


if self.head == dele:
self.head = dele.next

# Change next only if node to be deleted is NOT


# the last node
if dele.next is not None:
dele.next.prev = dele.prev

# Change prev only if node to be deleted is NOT


# the first node
if dele.prev is not None:
dele.prev.next = dele.next
# Finally, free the memory occupied by dele
# Call python garbage collector
gc.collect()

# Given a reference to the head of a list and an


# integer, inserts a new node on the front of list
def push(self, new_data):

# 1. Allocates node
# 2. Put the data in it
new_node = Node(new_data)

# 3. Make next of new node as head and


# previous as None (already None)
new_node.next = self.head

# 4. change prev of head node to new_node


if self.head is not None:
self.head.prev = new_node

# 5. move the head to point to the new node


self.head = new_node

def printList(self, node):


while(node is not None):
print(node.data,end=' ')
node = node.next

# Driver program to test the above functions

# Start with empty list


dll = DoublyLinkedList()

# Let us create the doubly linked list 10<->8<->4<->2


dll.push(2);
dll.push(4);
dll.push(8);
dll.push(10);
dll.push(30);

print ("\n Original Double Linked List",end=' ')


dll.printList(dll.head)

# delete nodes from doubly linked list


dll.deleteNode(dll.head)
dll.deleteNode(dll.head.next)
dll.deleteNode(dll.head.next)
# Modified linked list will be NULL<-8->NULL
print("\n Modified Double Linked List",end=' ')
dll.printList(dll.head)

Output:
Original Double Linked List 30 10 8 4 2
Double Linked List after deletion 10 2
12. Create a Circular singly linked list for adding and deleting a Node.
a) #Circular singly linked list add at beg,end,after
class Node:
def __init__(self, data):
self.data = data
self.next = 0

class CircularLinkedList:
def __init__(self):
self.last = None

# This function is only for empty list


def addToEmpty(self, data):
if (self.last != None):
return self.last
# Creating the newnode temp
temp = Node(data)
self.last = temp
# Creating the link
self.last.next = self.last
return self.last

def addBegin(self, data):


if (self.last == None):
return self.addToEmpty(data)
temp = Node(data)
temp.next = self.last.next
self.last.next = temp
return self.last

def addEnd(self, data):


if (self.last == None):
return self.addToEmpty(data)
temp = Node(data)
temp.next = self.last.next
self.last.next = temp
self.last = temp
return self.last

def addAfter(self, data, item):

if (self.last == None):
return None

temp = Node(data)
p = self.last.next
while p:
if (p.data == item):
temp.next = p.next
p.next = temp

if (p == self.last):
self.last = temp
return self.last
else:
return self.last
p = p.next
if (p == self.last.next):
print(item, "not present in the list")
break

def traverse(self):
if (self.last == None):
print("List is empty")
return
temp = self.last.next
while temp:
print(temp.data, end=" ")
temp = temp.next
if temp == self.last.next:
break
# Driver Code
if __name__ == '__main__':
llist = CircularLinkedList()
last = llist.addToEmpty(6)
last = llist.addBegin(4)
last = llist.addBegin(2)
last = llist.addEnd(8)
last = llist.addEnd(12)
last = llist.addAfter(15, 2)
print("Circular Linked list")
llist.traverse()
Output:
Circular Linked list
2 15 4 6 8 12

b)# Python program to delete a given key from Circular linked list.
# Node of a doubly linked list
class Node:
def __init__(self, next = None, data = None):
self.next = next
self.data = data

# Function to insert a node at the beginning of


# a Circular linked list
def push(head_ref, data):

# Create a new node and make head as next


# of it.
ptr1 = Node()
ptr1.data = data
ptr1.next = head_ref

# If linked list is not None then set the


# next of last node
if (head_ref != None) :

# Find the node before head and update


# next of it.
temp = head_ref
while (temp.next != head_ref):
temp = temp.next
temp.next = ptr1

else:
ptr1.next = ptr1 # For the first node

head_ref = ptr1
return head_ref

# Function to print nodes in a given


# circular linked list
def printList( head):

temp = head
if (head != None) :
while(True) :
print( temp.data, end = " ")
temp = temp.next
if (temp == head):
break
print()

# Function to delete a given node from the list


def deleteNode( head, key) :

# If linked list is empty


if (head == None):
return

# If the list contains only a single node


if((head).data == key and (head).next == head):

head = None

last = head
d = None

# If head is to be deleted
if((head).data == key) :

# Find the last node of the list


while(last.next != head):
last = last.next

# Point last node to the next of head i.e.


# the second node of the list
last.next = (head).next
head = last.next

# Either the node to be deleted is not found


# or the end of list is not reached
while(last.next != head and last.next.data != key) :
last = last.next

# If node to be deleted was found


if(last.next.data == key) :
d = last.next
last.next = d.next

else:
print("no such keyfound")

return head

# Driver code
# Initialize lists as empty
head = None

# Created linked list will be 2.5.7.8.10


head = push(head, 2)
head = push(head, 5)
head = push(head, 7)
head = push(head, 8)
head = push(head, 10)

print("List Before Deletion: ")


printList(head)

head = deleteNode(head, 7)

print( "List After Deletion: ")


printList(head)

Output:
List Before Deletion:
10 8 7 5 2
List After Deletion:
10 8 5 2

13. Create a stack and perform various operations on it.

a)# Stack Push operation program

class Stack:
def __init__(self):
self.stack = []

def add(self, dataval):


# Use list append method to add element
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False
# Use peek to look at the top of the stack
def peek(self):
return self.stack[-1]

AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.peek()
print(AStack.peek())
AStack.add("Wed")
AStack.add("Thu")
AStack.add("Fri")
AStack.add("Sat")
print(AStack.peek())

Output:
Tue
Sat

b)# Stack POP operation program

class Stack:
def __init__(self):
self.stack = []

def add(self, dataval):


# Use list append method to add element
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False

# Use list pop method to remove element


def remove(self):
if len(self.stack) <= 0:
return ("No element in the Stack")
else:
return self.stack.pop()

AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.add("Wed")
AStack.add("Thu")
print(AStack.remove())
print(AStack.remove())

Output:

Thu
Wed

14. Convert the infix expression into postfix form.


# Python program to convert infix expression to postfix
# Class to convert the expression

class Conversion:

# Constructor to initialize the class variables


def __init__(self, capacity):
self.top = -1 self.capacity = capacity
# This array is used a stack
self.array = []
# Precedence setting
self.output = []
self.precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}

# check if the stack is empty


def isEmpty(self):
return True if self.top == -1 else False

# Return the value of the top of the stack


def peek(self):
return self.array[-1]

# Pop the element from the stack


def pop(self):
if not self.isEmpty():
self.top -= 1
return self.array.pop()
else:
return "$"

# Push the element to the stack


def push(self, op):
self.top += 1
self.array.append(op)

# A utility function to check is the given character


# is operand
def isOperand(self, ch):
return ch.isalpha()

# Check if the precedence of operator is strictly


# less than top of stack or not
def notGreater(self, i):
try:
a = self.precedence[i]
b = self.precedence[self.peek()]
return True if a <= b else False
except KeyError:
return False

# The main function that


# converts given infix expression
# to postfix expression
def infixToPostfix(self, exp):

# Iterate over the expression for conversion


for i in exp:
# If the character is an operand,
# add it to output
if self.isOperand(i):
self.output.append(i)

# If the character is an '(', push it to stack


elif i == '(':
self.push(i)

# If the scanned character is an ')', pop and


# output from the stack until and '(' is found
elif i == ')':
while((not self.isEmpty()) and
self.peek() != '('):
a = self.pop()
self.output.append(a)
if (not self.isEmpty() and self.peek() != '('):
return -1
else:
self.pop()

# An operator is encountered
else:
while(not self.isEmpty() and self.notGreater(i)):
self.output.append(self.pop())
self.push(i)

# pop all the operator from the stack


while not self.isEmpty():
self.output.append(self.pop())

print("".join(self.output))

# Driver's code
if __name__ == '__main__':
exp = "a+b*(c^d-e)^(f+g*h)-i"
obj = Conversion(len(exp))

# Function call
obj.infixToPostfix(exp)

Output:
abcd^e-fgh*+^*+i-
15. Perform String reversal using stack
# Python program to reverse a string using stack
# Function to create an empty stack.
# It initializes size of stack as 0

def createStack():
stack = []
return stack

# Function to determine the size of the stack

def size(stack):
return len(stack)

# Stack is empty if the size is 0

def isEmpty(stack):
if size(stack) == 0:
return true

# Function to add an item to stack.


# It increases size by 1

def push(stack, item):


stack.append(item)

# Function to remove an item from stack.


# It decreases size by 1

def pop(stack):
if isEmpty(stack):
return
return stack.pop()

# A stack based function to reverse a string

def reverse(string):
n = len(string)

# Create a empty stack


stack = createStack()

# Push all characters of string to stack


for i in range(0, n, 1):
push(stack, string[i])

# Making the string empty since all


# characters are saved in stack
string = ""

# Pop all characters of string and


# put them back to string
for i in range(0, n, 1):
string += pop(stack)
return string

# Driver program to test above functions


string = "UGUDALAP UJAR"
string = reverse(string)
print("Reversed string is " + string)

Output:
Reversed string is RAJU PALADUGU
16. Create a queue and perform various operations on it.

# Python program to
# demonstrate queue implementation
# using list

# Initializing a queue
queue = []

# Adding elements to the queue


queue.append('a')
queue.append('b')
queue.append('c')

print("Initial queue")
print(queue)

# Removing elements from the queue


print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
#print(queue.pop(0))

print("\nQueue after removing elements")


print(queue)
Output:
Initial queue
['a', 'b', 'c']

Elements dequeued from queue


a
b

Queue after removing elements


['c']

17. Construct a binary tree and perform various traversals.


a) # Program to for tree traversals Binary Tree

class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
# A function to do inorder tree traversal
def printInorder(root):

if root:
# First recur on left child
printInorder(root.left)

# then print the data of node


print(root.val),

# now recur on right child


printInorder(root.right)
# Driver code
if __name__ == "__main__":
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
# Function call
print ("\nInorder traversal of binary tree is")
printInorder(root)

Output:
Inorder traversal of binary tree is
42513

b) # Program to do preorder tree traversal


class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key

# A function to do preorder tree traversal


def printPreorder(root):

if root:

# First print the data of node


print(root.val),

# Then recur on left child


printPreorder(root.left)

# Finally recur on right child


printPreorder(root.right)

# Driver code
if __name__ == "__main__":
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

# Function call
print("Preorder traversal of binary tree is")
printPreorder(root)

Output:
Preorder traversal of binary tree is
12453
c)# A Program to do postorder tree traversal

class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key

# A function to do postorder tree traversal


def printPostorder(root):

if root:

# First recur on left child


printPostorder(root.left)

# the recur on right child


printPostorder(root.right)

# now print the data of node


print(root.val),

# Driver code
if __name__ == "__main__":
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

# Function call
print("\nPostorder traversal of binary tree is")
printPostorder(root)

Output:
Postorder traversal of binary tree is
45231
18. Construct a binary search tree and perform search operation.
# Binary Search Tree operations in Python
# Create a node
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None

# Inorder traversal
def inorder(root):
if root is not None:
# Traverse left
inorder(root.left)

# Traverse root
print(str(root.key) + "->", end=' ')

# Traverse right
inorder(root.right)

# Insert a node
def insert(node, key):

# Return a new node if the tree is empty


if node is None:
return Node(key)

# Traverse to the right place and insert the node


if key < node.key:
node.left = insert(node.left, key)
else:
node.right = insert(node.right, key)
return node

# Find the inorder successor


def minValueNode(node):
current = node

# Find the leftmost leaf


while(current.left is not None):
current = current.left

return current

# Deleting a node
def deleteNode(root, key):

# Return if the tree is empty


if root is None:
return root

# Find the node to be deleted


if key < root.key:
root.left = deleteNode(root.left, key)
elif(key > root.key):
root.right = deleteNode(root.right, key)
else:
# If the node is with only one child or no child
if root.left is None:
temp = root.right
root = None
return temp

elif root.right is None:


temp = root.left
root = None
return temp

# If the node has two children,


# place the inorder successor in position of the node to be deleted
temp = minValueNode(root.right)

root.key = temp.key

# Delete the inorder successor


root.right = deleteNode(root.right, temp.key)
return root

root = None
root = insert(root, 8)
root = insert(root, 3)
root = insert(root, 1)
root = insert(root, 6)
root = insert(root, 7)
root = insert(root, 10)
root = insert(root, 14)
root = insert(root, 4)

print("Inorder traversal: ", end=' ')


inorder(root)

print("\nDelete 10")
root = deleteNode(root, 10)
print("Inorder traversal: ", end=' ')
inorder(root)

Output:
Inorder traversal: 1-> 3-> 4-> 6-> 7-> 8-> 10-> 14->
Delete 10
Inorder traversal: 1-> 3-> 4-> 6-> 7-> 8-> 14->
19.Implement Depth First Search, Breadth First Search traversals on a graph.

a) #Depth First Traversal(DFS)


class graph:
def __init__(self,gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict
# Check for the visisted and unvisited nodes
def dfs(graph, start, visited = None):
if visited is None:
visited = set()
visited.add(start)
print(start)
for next in graph[start] - visited:
dfs(graph, next, visited)
return visited

gdict = {
"a" : set(["b","c"]),
"b" : set(["a", "d"]),
"c" : set(["a", "d"]),
"d" : set(["e"]),
"e" : set(["a"])
}
dfs(gdict, 'a')

Output:
DFS Traversal --- a b d e c

b) #Breadth First Traversal (BFS)


import collections
class graph:
def __init__(self,gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict
def bfs(graph, startnode):
# Track the visited and unvisited nodes using queue
seen, queue = set([startnode]), collections. deque([startnode])
while queue:
vertex = queue.popleft()
marked(vertex)
for node in graph[vertex]:
if node not in seen:
seen.add(node)
queue.append(node)

def marked(n):
print(n)

# The graph dictionary


gdict = {
"a" : set(["b","c"]),
"b" : set(["a", "d"]),
"c" : set(["a", "d"]),
"d" : set(["e"]),
"e" : set(["a"])
}
bfs(gdict, "a")

Output:
BFS Traversal --- a b c d e

20. Implement Dijkstra’s Shortest Path Algorithm

# Python program for Dijkstra's shortest path algorithm. The program is


# for adjacency matrix representation of the graph
class Graph():

def __init__(self, vertices):


self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]

def printSolution(self, dist):


print("Vertex \t Distance from Source")
for node in range(self.V):
print(node, "\t\t", dist[node])

# A utility function to find the vertex with


# minimum distance value, from the set of vertices
# not yet included in shortest path tree
def minDistance(self, dist, sptSet):

# Initialize minimum distance for next node


min = 1e7

# Search not nearest vertex not in the


# shortest path tree
for v in range(self.V):
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v

return min_index

# Function that implements Dijkstra's single source


# shortest path algorithm for a graph represented
# using adjacency matrix representation
def dijkstra(self, src):

dist = [1e7] * self.V


dist[src] = 0
sptSet = [False] * self.V

for cout in range(self.V):

# Pick the minimum distance vertex from


# the set of vertices not yet processed.
# u is always equal to src in first iteration
u = self.minDistance(dist, sptSet)

# Put the minimum distance vertex in the


# shortest path tree
sptSet[u] = True

# Update dist value of the adjacent vertices


# of the picked vertex only if the current
# distance is greater than new distance and
# the vertex in not in the shortest path tree
for v in range(self.V):
if (self.graph[u][v] > 0 and
sptSet[v] == False and
dist[v] > dist[u] + self.graph[u][v]):
dist[v] = dist[u] + self.graph[u][v]

self.printSolution(dist)

# Driver program
g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0], [4, 0, 8, 0, 0, 0, 0, 11, 0], [0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0], [0, 0, 0, 9, 0, 10, 0, 0, 0], [0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6], [8, 11, 0, 0, 0, 0, 1, 0, 7], [0, 0, 2, 0, 0, 0, 6, 7, 0]
]
g.dijkstra(0)

Output:
Consider source node as “0”
Vertex Distance from Source
0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
Python Example programs
1. Write a program to demonstrate different number datatypes in python.

Source code:
i=7 c=24+8j
f=701
s='HELLO EVERYONE!!\nThis is john\'s python programming..'
# NOTE: boolean has truth values that are case sensitive Ex: True (T is caps!)
b= True
print("the value of c is:",i,'\nits type is:',type(i))
print("the value of c is:",f,'\nits type is:',type(f))
print("the value of c is:",c,'\nits type is:',type(c))
print("the value of c is:",s,'\nits type is:',type(s))
rint("the value of c is:",b,'\nits type is:',type(b))
print('NOTE: boolean has truth values that are case sensitive Ex: True (T is caps!)')

Output:
2. Write a program to perform different arithmetic operations on numbers in python.

Source code:

a=10; b=3

print("addition of a:",a,"&b:",b,"is:",a+b)

print("substraction of a:",a,"&b:",b,"is:",a-b)

print("multiplication of a:",a,"&b:",b,"is:",a*b)

print("division of a:",a,"&b:",b,"is:",a/b)

print("floor divison of a:",a,"&b:",b,"is:",a//b)

print("moduli of a:",a,"&b:",b,"is:",a%b)

print("exponent of a:",a,"&b:",b,"is:",a**b)

Output:
3. Write a program to create, concatenate and print a string and accessing sub-string from
a given string.

Source code:

pi=3.14

s= "Venkata"

v= "Subhramanyam"
print("the value of s is:",s)
print("the value of v is:",v)
string_add = s+v
print("after concatenating s and v the string is:",s+v)

text = 'The value of pi is ' + str(pi)

print("NOTE: variables after '+' operator must be converted to string before using them as strings\n
otherwise value will be considered as its class type")

print(text)

Output:
4. Write a python script to print the current date in following format
“SunMay 29 02:26:23 IST 2017”

Source code:

import time
import datetime
x =datetime.datetime.now()
print(x.strftime("%c"))

Output:
5. Write a python program to create, append and remove lists in python.

Source code:

# creating list with college names..

colleges = ["SIIET", "GNIT", "AVN"]

print(colleges)

# appending new college in collges list

colleges.append("MVSR")
#checking if its added or not
print(colleges)
#adding a new college at a positon
colleges.insert(1,"BHARAT") print(colleges)
#remove a name from colleges
colleges.remove("BHARAT") print(colleges)
#remove a name with an index value

del colleges[1]

# NOTE: index starts from 0 so 2nd value in list will be removed

print(colleges)

Output:
6. Write a program to demonstrate working with tuples in python

Source code:

# creating tuples with college names..

colleges = ("SIIET","BHARAT","GNIT", "AVN")

print("the lists in colleges tuple is",colleges)

print("we can\'t add or remove new elements in a tuple")


print("length of the tuple colleges is:",len(colleges))
# checking whether 'SIIET' is present in the tuple or not

if "SIIET" in colleges:

print("Yes, 'SIIET' is in the colleges tuple")

Output:
7. Write a program to demonstrate working with dictionaries in python

Source code:
# creating a dictionary
for SIIET college = {
"name": "siiet",
"code": "INDI",
"id": "x3"

}
print(college)
#adding items to dictionary
college["location"] = "IBP"
print(college)
#changing values of a key
college["location"] = "sheriguda"
print(college)
# to remove items use
pop()
college.pop("code")
print(college)
#know the length using len() print("length
of college is:",len(college))#to copy the
same dictionary use copy() mycollege=
college.copy() print(mycollege)

Output:
8. Write a python program to find largest of three numbers

Source code:
# user-defined function to know which number is
larger def bigOf3(a,b,c):
if(a>b):
if(a>c):
print("a is greater than b and c")
else:
print("c is greater than a and b")
elif(b>c):
print("b is greater than a and c")
else:
print("c is greater than a and b")
txt= input("enter a,b,c values:") a,b,c=
txt.split()
bigOf3(int(a),int(b),int(c)) #calling the function

Output:
9. Write a python program to convert temperature to and from Celsius to fahrenheit.

Source code:
while(1):
print("1.CELSIUS TO FAHRENHEIT\n2.FAHRENHEIT TO CELSIUS\n3.EXIT\n")
choice=input("ENTER YOUR CHOICE:")
ch=int(choice)
if(ch==1):
c=int(input("ENTER TEMPERATURE IN CELSIUS:"))
f=((9*c)/5)+32
print("converted temperature is:",f)
elif(ch==2):
f=int(input("ENTER TEMPERATURE IN FAHRENHEIT:"))
c=((f-32)/9)*5
print("converted temperature is:",c)
elif(ch==3):
exit()else:
print("wrong choice")

Output:
10. Write a python program to construct the following pattern using nested for
loop:
*
**
***
****
*****

*****
****
***
**

Source code:

n=int(input("ENTER A VALUE:"))

fo
r
x
i
n
r
a
n
g
e
(
0
,
n
+
1
,
1
)
:
p
r
i
n
t
(
x
*
'
*
'
)
if(x==n):

for x in range(n,0,-1): print(x*'*')

Output:
***********************
ALL
THE
BEST
***********************

You might also like