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

PSP LAB MANUAL-First Semester-2024

This document is a laboratory certificate template for CMR University, Bangalore, certifying the completion of experiments in a specified course during the academic year 2024-2025. It includes a table of contents listing various Python programming exercises along with their aims, algorithms, and sample code. The exercises cover topics such as finding minimum values in lists, sorting algorithms, and mathematical computations.

Uploaded by

sebesoh535
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

PSP LAB MANUAL-First Semester-2024

This document is a laboratory certificate template for CMR University, Bangalore, certifying the completion of experiments in a specified course during the academic year 2024-2025. It includes a table of contents listing various Python programming exercises along with their aims, algorithms, and sample code. The exercises cover topics such as finding minimum values in lists, sorting algorithms, and mathematical computations.

Uploaded by

sebesoh535
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

LaboratoryCertificate

This is to certify that bearing the register number belonging to _________semester


___________________________has satisfactorily completed the experiments/laboratory
work in the course __________and the course code prescribed by CMR University,
Bangalore during the academic year 2024-2025.

CIE-Marks
Max. Marks MarksAwarded

FacultyIn-Charge& Signature/Date: ____________________

Dr. Gyanappa A. Walikar


Associate Professor,
Dept of CSE,
CMR University, Bengaluru
Program Coordinator

Examiners

1. ………………………………………….

2. ………………………………………….

Date of Examination: / /2025.


Table of Contents
Sl.No Program Name Page No

01 Find minimum in a List

02 To insert a number in a sorted list


03 Guess an integer number in a range

04 Towers of Hanoi

05 Exchange the values of two variables

06 Find circulating ‘n’ values

07 Calculate distance between two points

08 Find the square root of number(Newtons method)

09 Compute GCD of two numbers

10 Exponentiation (power of a number)

11 Program to print the sum of all elements in an array

12 To write a Python program to sort the elements using selection sort

13 To write a Python program to sort the elements using insertion sort

14 To write a Python program to sort elements using merge sort method

15 Write a Python program to create a histogram from a given list of


integers.

16 Write a Python program to accessing data members

17 Write a Python program class method to create a person object by birth


year, _call- method in a class.

Program 1: Find minimum in a List


Aim: To write the python program for finding the minimum number in a
list.

Algorithm:
Step 1: Start
Step 2: Declare a list with set of number values
Step 3: Use the sort() in-built function to sort the list in ascending order
Step 4: Display the smallest element by indexing the first element in the
sorted list

Step 6: End
Program:

# Python program to find smallest number in a list


# list of numbers
list1 = [10, 20, 4, 45, 99]
# sorting the list
list1.sort()
# printing the first element
print("Smallest element is:", list1[0])

Output:

Smallest element is: 4


Program 2:To insert a number in a sorted list
Aim: To write the python program to insert a number in a sorted
list. Algorithm:
Step 1: start
Step 2: Define the function for inserting an element in a list Step 3:
Use the for loop for searching the correct position in the list Step
4: Then insert the element in the right position
Step 5: Write the driver function to call the defined function and to print
the list
Step 6: Stop
Program:
# Python3 program to insert an element into sorted list
# Function to insert element
index = len(list)
# Searching for the position
for i in range(len(list)):
if list[i] > n:
index = i
break
# Inserting n in the list
if index == len(list):
list = list[:index] + [n]
else:
list = list[:index] + [n] + list[index:]
return list
# Driver function
list = [1, 2, 4]
n=3
print(insert(list, n))
Output:

[1, 2, 3, 4]
Program 3: Guess an integer number in a range.
Aim: To write the python program for Guessing game – guessing a
number with in a range of numbers.
Algorithm:
Step 1: Start
Step 2: Read n.
Step 3: Read a guess number.
Step 4: If guess > n
Step 5: Print “Your guess is too high”
Step 6: If guess < n
Step 7: Print “Your guess is too low”
Step 8: Else
Step 9: If guess = n
Step 10: Print “Good job” else print “no”
Step 11: Stop
Program:
n=10
guess=int(input("Guess the number: "))
if(guess>n):
print("Your is too high")
elif(guess==n):
print("Good Job")
else:
print("Your is too low")
Output:
Guess the number: 10
Good Job
Guess the number: 4
Your is too low
Guess the number: 23
Your is too high

Program 4: Towers of Hanoi


Aim: To write the python program for Tower of Hanoi problem. (Tower’s
of Hanoi: A Tower’s of Hanoi is a children’s playing game, played with
three poles and a number of different sized disks which is stacked on the
poles. The disks are stacked on the left most pole in ascending order
initially. ie) The largest on the bottom and the smallest on the top.

Rules to be followed:
a) Only one disk can be moved among the towers at any given time.
b) Only the “top” disk can be removed.
c) No large disk can sit over a small disk.
The objective is to transfer the disks from the left most pole to the right
most pole by using the center pole as the temporary pole.
The steps are:
a) Move the top n-1 disks from the left pole to the centre pole, n is the
number of disks.
b) Move the nth largest disk to the right pole. Move the n-1 disks on
the centre pole to the right pole.
c) The total number of moves will be 2n – 1, where n is the number of
disks.)
Algorithm:

1. Start
2. Read disk, source, dest, aux
3. Call the function Hanoi(disk, source, dest, aux)
4. Stop
Algorithm for function Hanoi(disk, source, dest,
aux): 1. Start
2. If disk=1
Move disk from source to dest
3. Else
Hanoi(disk-1, source, aux, dest)
Move disk from source to dest Hanoi(disk1,aux, dest,source)
4. Return

Pseudo code:
BEGIN
READ disk, source, dest, aux
FUNCTION Hanoi (disk, source, dest, aux) END
Pseudo code for function Hanoi (disk, source, dest, aux)
BEGIN
IF disk=1 THEN
Move disk from source to dest
ELSE
Hanoi (disk-1, source, aux, dest)
Move disk from source to dest
Hanoi (disk-1, aux, dest, source)
ENDIF
END
Program :

# Recursive Python function to solve tower of


hanoi def TowerOfHanoi(n, from_rod, to_rod,
aux_rod): if n == 0:
return
TowerOfHanoi(n-1,, aux_rod, to_rod)
print("Move disk", n, "from rod",, "to rod", to_rod)
TowerOfHanoi(n-1, aux_rod, to_rod,)
# Driver code
N=3
# A, C, B are the name of rods
TowerOfHanoi(N, 'A', 'C', 'B')
Output:
Move disk 1 from rod A to rod C
Move disk 2 from rod A to rod B
Move disk 1 from rod C to rod B
Move disk 3 from rod A to rod C
Move disk 1 from rod B to rod A
Move disk 2 from rod B to rod C
Move disk 1 from rod A to rod C
Program 5: Exchange the values of two variables
Aim: To write the python program for exchange the value of two
variables.
Algorithm:
Step 1: Start
Step 2: Declare variables a, b and input the two number using input ()
function
Step 3: Use the third variable temp
Step 4: Assign temp=a,a==temp
Step 5: Display a and b using print ()
Step 6: End

Program:
a = int( input("Please enter value for a: "))
b = int( input("Please enter value for b: "))
# we will user third variable which is a temporary variable
temp = a
a=b
b = temp

print ("The Value of P after swapping: ", a)


print ("The Value of Q after swapping: ", b)

Output:

Please enter value for a: 4


Please enter value for b: 6
The Value of P after swapping: 6
The Value of Q after swapping: 4
Program 6: Find circulating ‘n’ values
Aim: To write a Python program to find circulating ‘n’
values Algorithm:
Step 1.Start
Step 2. Define a List named a[]
Step 3. Get the input ‘n’ value to rotate the
values. Step 4. Perform the following step till
b=a[n:]+a[:n], using slice operator
Step 5. Print the rotated values.
Step 6. Stop
Program:
a=[1,2,3,4,5,6,7,8,9,10]
print("Enter the n for circulate:")
n=int(input())
b=a[n:]+a[:n]
print(b)

Output:
Enter the n for circulate:
4
[5, 6, 7, 8, 9, 10, 1, 2, 3, 4]
Program 7: Calculate distance between two points

Aim: To write a python program to calculate distance between two points


taking input from the user

Algorithm:
Step 1: Start
Step 2: Declare variables x1, x2, y1 and y2, then input them using input ()
function
Step 3: Declare the third variable for storing results and
assign result= ((((x2 - x1 )**2) + ((y2-y1)**2)
)**0.5)
Step 5: Display result using print ()
Step 6: End

Program:
x1=int(input("enter x1 : "))

x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))

y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)

print("distance between",(x1,x2),"and",(y1,y2),"is : ",result)

Output:
Enter x1 : 6
Enter x2 : 6
Enter y1 : 7
Enter y2 : 8
Distance between (6, 6) and (7, 8) is : 1.0
Program 8: Find the square root of number(Newtons method)

Aim: To Write a Python program to find the square root of a number


(Newton’s method)

Algorithm:
Step 1: Start
Step 2: The first parameter is the value whose square root will be
approximated.
Step 3: The second is the number of times to iterate the calculation
yielding a better result from the user.
Step 4: Calculate better = ½*(approx.+n/approx.)
Step 5: Print the final result
Step 6: Stop

Program:
n=int(input("Enter a number:"))
newton_squareroot= 0.5*((0.5*n)+n/(0.5*n))
print (newton_squareroot)

Output:
Enter a number: 4 2.0

Result:
Thus the Python program to find the square root of a number
(Newton’s method) was created and executed successfully.
Program 9: Compute GCD of two numbers

Aim: To Write a Python program to compute the GCD of two numbers.

Algorithm:
Step 1: Start
Step 2: Take two numbers from the user as input
Step 3: Calculate the remainder a%b
Step 4: While the remainder is not equal to 0.
Step 5: print the GCD
Step 9: Stop

Program:
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
print ("The GCD of the two numbers is",gcd(a,b))

Output:
Enter the first number:15 Enter the second number:5
The GCD of the two numbers is 5

Result:
Thus the Python program to compute the GCD of two numbers was
created and executed successfully.
Program 10: Exponentiation (power of a number)
Aim: To Write a Python program to find the exponentiation (Power of a
number)

Algorithm:
Step 1: Start
Step 2: r->n
Step 3: Read Base Number n
Step 4: Read Exponent Number e
Step 5: FOR i-> 1 to e
Step 5.1: Compute r->n*r
Step 6: Print ‘Exponent’
Step 7: Stop

Program:
n=int(input("Enter a n value:"))
e=int(input("Enter a power value:"))
r=n
for i in range(1,e):
r=n*r
print ("Exponent",r)

Output:
Enter a number:3
Enter a number:2
Exponent :9
Result:
Thus the a Python program to find the exponentiation (Power of a
number) was created and executed successfully.
Program 11: Program to print the sum of all elements in an array Aim:
To write python program to print the sum of all elements in an array

Algorithm:
Step1: Start
Step2: Declare and initialize an array
Step3: The variable sum will be used to calculate the sum of the elements.
Initialize it to 0
Step4: Loop through the array and add each element of the array to the
variable sum as sum = sum + arr[i]
Step5: Print the sum value
Step6: Stop

Program:
arr = [1, 2, 3, 4, 5]
sum = 0
#Loop through the array to calculate sum of elements
for i in range(0, len(arr)):
sum = sum + arr[i]
print("Sum of all the elements of an array: " + str(sum))

Output:
Sum of all the elements of an array: 15
Program 12: Selection sort
Aim: To write a Python program to sort the elements using selection
sort.

Algorithm:
Step 1: Start
Step 2: Declare list []
Step 3: Set MIN to location 0
Step 4: Search the minimum element in the list. Step 5: Swap with value
at location MIN
Step 6: Increment MIN to point to next element Step 7: Repeat until list is
sorted.
Step 8: Stop
Program:
def selectionSort(a):
for i in range(len(a)):
least=i
for k in range(i+1,len(a)):
if a[k]<a[least]:
least=k
if least !=i:
temp=a[i]
a[i]=a[least]
a[least]=temp
return a
a=[50,30,10,20,40,70,60]
print ("Original list",a)

selectionSort(a)
print("Selection Sort:",a)

Output:
Original list: [50, 30, 10, 20, 40, 70, 60]
Selection Sort: [10, 20, 30, 40, 50, 60, 70]
Program 13: Insertion sort
Aim: To write a Python program to sort the elements using insertion
sort. Algorithm:
Step 1: Start
Step 2: Get the elements from the user
Step 3a: The second element in the list is compared with the elements that
appear before it (only first element in this case).
Step 3b: If the second element is smaller than first element, second element
is inserted in the position of first element. After first step, first two elements
of an array will be sorted.
Step 3c: Pick next element
Step 4: Repeat step 3 until all the elements in the list is sorted Step 5: Stop

Program:
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >= 0 and key < arr[j] :
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
n=int(input("Enter the no. of element"))
i=0
arr=[i for i in range(n)]
for i in range(0,n):
arr[i]=int(input("enter the array element"))
insertionSort(arr)
print("Sorted element are")
for i in range(len(arr)):
print ("% d" % arr[i])

Output:
Enter the no. of element:5
Enter the array element :7
Enter the array element :8
Enter the array element :5
Enter the array element :7
Enter the array element :9
Sorted element are
5
7
7
8
9

Result:

Thus a Python program to sort the elements using selection sort method
was created and executed successfully

Program 14: Merge sort


Aim: To write a Python program to sort elements using merge sort
method.

Program:
def mergeSort(nlist):
print("Splitting ",nlist)
if len(nlist)>1:
mid = len(nlist)//2
lefthalf = nlist[:mid]
righthalf = nlist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=j=k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
nlist[k]=lefthalf[i]
i=i+1
else:
nlist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
nlist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
nlist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",nlist)
nlist =
[14,46,43,27,57,41,45,21,70]
mergeSort(nlist)
print(nlist)

Output:
Splitting [14, 46, 43, 27, 57, 41, 45, 21, 70]
Splitting [14, 46, 43, 27]
Splitting [14, 46]
Splitting [14]
Merging [14]
Splitting [46]
Merging [46]
Merging [14, 46]
Splitting [43, 27]
Splitting [43]
Merging [43]
Splitting [27]
Merging [27]
Merging [27, 43]
Merging [14, 27, 43, 46]
Splitting [57, 41, 45, 21, 70]
Splitting [57, 41]
Splitting [57]
Merging [57]
Splitting [41]
Merging [41]
Merging [41, 57]
Splitting [45, 21, 70]
Splitting [45]
Merging [45]
Splitting [21, 70]
Splitting [21]
Merging [21]
Splitting [70]
Merging [70]
Merging [21, 70]
Merging [21, 45, 70]
Merging [21, 41, 45, 57, 70]
Merging [14, 21, 27, 41, 43, 45, 46, 57, 70]
[14, 21, 27, 41, 43, 45, 46, 57, 70]

Result:
Thus a Python programs to sort the element using merge sort method was
created and executed successfully.

Program 15: Write a Python program to create a histogram from a given


list of integers.

Aim: To write a Python program to create a histogram from a given list of


integers.

Program:

def histogram( items ):


for n in items:
output = ''
times = n
while( times > 0 ):
output += '*'
times = times - 1
print(output)
histogram([2, 3, 6, 5])

Output:
**
***
******
*****
Program 16 : Write a Python program to accessing data
members. Aim: Write a Python program to accessing data
members.

Program:
class Person:
def __init__(self, name, age, ssn):
self.name = name # Public attribute
self.age = age # Public attribute
self._ssn = ssn # Private attribute

# Getter method for 'name'


def get_name(self):
return self.name

# Setter method for 'name'


def set_name(self, new_name):
self.name = new_name

# Getter method for 'age'


def get_age(self):
return self.age

# Setter method for 'age'


def set_age(self, new_age):
if new_age >= 0:
self.age = new_age
else:
print("Invalid age! Age cannot be negative.")

# Getter method for 'ssn' (private attribute)


def get_ssn(self):
return self._ssn

# Setter method for 'ssn' (private attribute)


def set_ssn(self, new_ssn):
self._ssn = new_ssn

# Method to display all attributes


def display_info(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
print(f"SSN: {self._ssn}")

# Create an instance of Person


person1 = Person("Alice", 30, "123-45-6789")

# Accessing and modifying public attributes directly


print(f"Initial Name: {person1.name}")
person1.name = "Bob"
print(f"Modified Name: {person1.name}")

# Accessing and modifying attributes using getter and setter


methods print(f"Initial Age: {person1.get_age()}")
person1.set_age(35)
print(f"Modified Age: {person1.get_age()}")

# Accessing and modifying private attributes using


methods print(f"Initial SSN: {person1.get_ssn()}")
person1.set_ssn("987-65-4321")
print(f"Modified SSN: {person1.get_ssn()}")

# Display all attributes


person1.display_info()

Explanation:

Class Definition:
The Person class is defined with an __init__ method that initializes the
name, age, and a private attribute _ssn.
Public attributes name and age can be accessed directly. Private
attribute _ssn is meant to be accessed through getter and setter methods.
Methods:

Getters: get_name, get_age, and get_ssn return the values of name, age,
and _ssn, respectively.

Setters: set_name, set_age, and set_ssn modify the values of name, age,
and _ssn, respectively.The display_info method prints all attributes of the
instance.

Creating an Instance:

An instance person1 of the Person class is created with initial


values. Accessing and Modifying Attributes:

The program demonstrates how to access and modify the name attribute
directly.It shows how to use getter and setter methods to access and
modify the age and ssn attributes.

Program 17 :Write a Python program class method to create a person


object by birth year, _call- method in a class.

Aim: Write a Python program class method to create a person object by


birth year, _call- method in a class.

Program:

from datetime import datetime

class Person:
def __init__(self, name, age, ssn):
self.name = name # Public attribute
self.age = age # Public attribute
self._ssn = ssn # Private attribute

# Getter method for 'name'


def get_name(self):
return self.name

# Setter method for 'name'


def set_name(self, new_name):
self.name = new_name

# Getter method for 'age'


def get_age(self):
return self.age

# Setter method for 'age'


def set_age(self, new_age):
if new_age >= 0:
self.age = new_age
else:
print("Invalid age! Age cannot be negative.")

# Getter method for 'ssn' (private attribute)


def get_ssn(self):
return self._ssn

# Setter method for 'ssn' (private attribute)


def set_ssn(self, new_ssn):
self._ssn = new_ssn

# Class method to create an instance from birth year


@classmethod
def(cls, name, birth_year, ssn):
current_year = datetime.now().year
age = current_year - birth_year
return cls(name, age, ssn)

# __call__ method to make an instance callable


def __call__(self, message):
print(f"{self.name} says: {message}")

# Method to display all attributes


def display_info(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
print(f"SSN: {self._ssn}")

# Example usage

# Create a Person object using the class method


person2 = Person.from_birth_year("Charlie", 1990, "123-45-6789")
print("Created using class method:")
person2.display_info()

# Using the __call__ method


print("\nCalling the instance as a function:")
person2("Hello, World!")

# Create another Person instance normally


person3 = Person("Dana", 25, "987-65-4321")
print("\nCreated using __init__:")
person3.display_info()

# Using the __call__ method for another instance


print("\nCalling another instance as a function:")
person3("Goodbye, World!")

Explanation

1. Class Method ():

∙ This method is a class method, denoted by the @classmethod


decorator.
∙ It takes the class cls as its first argument, followed by name,
birth_year, and ssn.
∙ It calculates the age based on the current year using
datetime.now().year.
∙ It returns an instance of the Person class using cls(name, age, ssn).
2.__call__ Method:
∙ The __call__ method is a special method that makes an instance
callable like a function.
∙ When called, it prints a message with the format: "{name} says:
{message}".

Example Usage:

∙ The example demonstrates creating a Person object using the class


method from_birth_year and another object using the regular __init__
method.
∙ It shows calling the __call__ method to print a custom message.

You might also like