[go: up one dir, main page]

0% found this document useful (0 votes)
150 views32 pages

PSP Lab Manual1

Thus the program demonstrates use of list for data validation by performing operations like adding elements to a list, adding a list to another list, counting elements inside a list, and finding the index of an element in a list. The output verifies that the program works as expected.

Uploaded by

abhay kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
150 views32 pages

PSP Lab Manual1

Thus the program demonstrates use of list for data validation by performing operations like adding elements to a list, adding a list to another list, counting elements inside a list, and finding the index of an element in a list. The output verifies that the program works as expected.

Uploaded by

abhay kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

I SEMESTER

PROBLEM SOLVING USING PYTHON LABORATORY

LABORATORY MANUAL
ENGINEERING COLLEGE (AUTONOMOUS)
KOMARAPALAYAM-637 303

DEPARTMENT OF

LABORATORY RECORD NOTE BOOK

This is to certify that bonafide record of work done by

. Register No. of the 1st semester

branch during the year

2020-2021 in the Laboratory

Staff In-charge Head of the Department

Submitted for the Practical Examination held on:

Internal Examiner External Examiner


TABLE OF CONTENTS

Ex. Page
Date Name of the Experiment Marks Sign
No No
Write a algorithm & draw flowchart for simple
1
computational problems
Write a program to perform different arithmetic
2
operations on numbers in python.
Write a python program to implement the various
3
control structures
Write a python program for computational problems
4
using recursive function.

5 Demonstrate use of list for data validation.

Develop a python program to explore string


6
functions

7 Implement linear search and binary search.

Develop a python program to implement sorting


8
methods
Develop python programs to perform operations on
9
dictionaries.

10 Write a python program to read and write into a file


Exp No.1 Write a algorithm & draw flowchart for simple computational problems

1a. find the square root of a


number Aim:
To find the square root of a number (Newton’s method)

Algorithm:
1. Read one input value using input function
2. Convert it into float
3. Find the square root of the given number using the formula inputvalue ** 0.5
4. Print the result
5. Exit.:

Flow Chart:

Start

Read an Input value


A

X=float(A)

C=X**0.5

Print the Result

Stop
Program:

number = float(input("enter a number: "))


sqrt = number ** 0.5
print("square root:", sqrt)

Output:
enter a number: 676
square root: 26.0

Using Math Function:


import math
print(math.sqrt(1024))

Output:
32.0

Result

Thus the Flowchart for to find square root of a number is executedsuccessfully and
output is verified.
1b. Compute the GCD of two

numbers Aim:

To compute the GCD of two numbers

Algorithm:

1. Read two input values using input function

2. Convert them into integers

3. Define a function to compute GCD

a. Find smallest among two inputs

b. Set the smallest


c. Divide both inputs by the numbers from 1 to smallest+1
d. Ifthe remainders of both divisions are zero Assign that number to gcd

e. Return the gcd

4. Call the function with two inputs

5. Display the result

Flow Chart:

Start

Read two input


values x,y

Call a Function ComputeGCD(x,y) A

Print Result

Stop
Finding HCF of a number:
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
 
HCF = 1
 
for i in range(2,a+1):
    if(a%i==0 and b%i==0):
        HCF = i
 
print("First Number is: ",a)
print("Second Number is: ",b)
print("HCF of the numbers is: ",HCF)

Output:

first Number is:  12


Second Number is:  18
HCF of the numbers is:6

Result:
Thus the flowchart for compute GCD of two numbers is executed successfully and
outputis verified.
Exp No.2 Write a program to perform different arithmetic operations on numbers in python

Aim:

To write a program to perform different arithmetic operations on numbers in python.

Algorithm:

Step1: Start
Step2: Read the input num1, num2
Step3: calculate the addition, subtraction, multiplication, division from Inputs
Step4: Display the Result
Step6: Stop

Program:
num1 = float(input(" Please Enter the First Value Number 1: "))
num2 = float(input(" Please Enter the Second Value Number 2:
"))

# Add Two Numbers


add = num1 + num2

# Subtracting num2 from num1


sub = num1 - num2

# Multiply num1 with num2


multi = num1 * num2

# Divide num1 by num2


div = num1 / num2

# Modulus of num1 and num2


mod = num1 % num2

# Exponent of num1 and num2


expo = num1 ** num2
print("The Sum of {0} and {1} = {2}".format(num1, num2, add))
print("The Subtraction of {0} from {1} = {2}".format(num2, num1, sub))
print("The Multiplication of {0} and {1} = {2}".format(num1, num2, multi))
print("The Division of {0} and {1} = {2}".format(num1, num2, div))
print("The Modulus of {0} and {1} = {2}".format(num1, num2, mod))
print("The Exponent Value of {0} and {1} = {2}".format(num1, num2, expo))

Output:
>>>
============== RESTART: C:/Users/students/Desktop/arithmetic.py ==============
Please Enter the First Value Number 1: 10
Please Enter the Second Value Number 2: 30
The Sum of 10.0 and 30.0 = 40.0
The Subtraction of 30.0 from 10.0 = -20.0
The Multiplication of 10.0 and 30.0 = 300.0
The Division of 10.0 and 30.0 = 0.3333333333333333
The Modulus of 10.0 and 30.0 = 10.0
The Exponent Value of 10.0 and 30.0 = 1e+30
>>>

Result:
Thus the program to perform different arithmetic operations on numbers is executed
successfully and outputis verified.
Exp No.3 Write a python program to implement the various control structures

Aim:
To find a maximum value in a given list using python program

Algorithm:
STEP 1 Start the program
STEP 2 Read the no of terms in the list as
n STEP 3 Read the list values from 1 to n
STEP 4 Initialize max =0
STEP 5 Initialize i=1 repeat step 6 until n
STEP 6 If list[i]> max
STEP 7 Set max = list[i]
STEP 8 Print Maximum numbers as max
STEP 9 Stop the program.

Program:
#input size and elments of an array
n=int(input("Enter no of terms:"))
list1=[]
print("Enter the Numbers\n")
for i in range(n):
list1.append(int(input()))
#initialize the greatest value
Max =0
#Find the greatest value
for i in range(n):
if list1[i]>Max:
Max=list1[i]
# Print the greatest Number
print("Greatest Number is ", Max)
Output

Result:
Thus the program to find the maximum value in a list is executed successfully and
output isverified.
Exp No.4 Write a python program for computational problems using recursive function

Aim:
To write python program to find Factorial of Number using recursion.

Algorithm:
1. Start the program.
2. Read the number to find the factorial.
3. Declare the recursive function recur_factorial (n).
4. In function fact(n), do the computation n*recur_factorial(n-1)
5. Repeat the step3 until the value n becomes 0.
6. Display the value of n*recur_factorial(n-1) returned from the function recur_factorial (n).
7. Stop the program.

Program:
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
# take input from the user
num = int(input("Enter a number: "))
# check is the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative
numbers") elif num == 0:
print("The factorial of 0 is
1") else:
print("The factorial of",num,"is",recur_factorial(num))
Output:

Result:
Thus the program for computational problems using recursive function is executed
successfully and outputis verified.
Exp No.5 Demonstrate use of list for data validation

Aim:
To demonstrate use of list for data validation.

Program:
Adding Element to a List

# animals list
animals = ['cat', 'dog', 'rabbit']
# 'guinea pig' is appended to the animals
list animals.append('guinea pig')

# Updated animals list


print('Updated animals list: ', animals)

Output

Updated animals list: ['cat', 'dog', 'rabbit', 'guinea pig']

Adding List to a List

# animals list
animals = ['cat', 'dog',
'rabbit'] # list of wild animals
wild_animals = ['tiger', 'fox']
# appending wild_animals list to the animals
list animals.append(wild_animals)

Output

Updated animals list: ['cat', 'dog', 'rabbit', ['tiger', 'fox']]


Count Tuple and List Elements Inside List

# random list
random = ['a', ('a', 'b'), ('a', 'b'), [3, 4]]
# count element ('a', 'b')
count = random.count(('a', 'b'))

# print count
print("The count of ('a', 'b') is:", count)
# count element [3, 4]
count = random.count([3, 4])
# print count
print("The count of [3, 4] is:", count)

Output

The count of ('a', 'b') is:


2 The count of [3, 4] is:
1

Find the index of the element

# vowels list
vowels = ['a', 'e', 'i', 'o', 'i',
'u'] # index of 'e' in vowels
index = vowels.index('e')
print('The index of e:',
index) # element 'i' is
searched
# index of the first 'i' is
returned index =
vowels.index('i') print('The
Output

The index of e:
1 The index of i:
2

Result:
Thus the program for the use of list for data validation is executed successfully and
outputis verified.
Exp No.6 Develop a python program to explore string functions to print reverse words of string

Aim:
To develop a python program to explore string functions to print reverse words of string.

Algorithm:
1. Initialize the string.
2. Split the string on space and store the resultant list in a variable called word.
3.Reverse the list words using reversed function.
4. Convert the result to list.

Program:

#Function to reverse words of string

def rev_sentence(sentence):

# first split the string into words


words = sentence.split(' ')

# then reverse the split string list and join using space
reverse_sentence = ' '.join(reversed(words))

# finally return the joined


string return reverse_sentence

if name == " main ":


input = 'geeks quiz practice
code' print (rev_sentence(input))
Output:

Result:
Thus the program for the use of list for data validation is executed successfully
and
outputis verified.
Exp No.7a Implement linear search and binary search

Aim:

To write a Python Program to perform Linear Search.

Algorithm:

1. Read n elements into the list

2. Read the element to be searched

3. If alist[pos]==item, then print the position of the item

4. Else increment the position and repeat step 3 until pos reaches the length of the list

Program:

def search(alist,item):

pos=0

found=False stop=False

while pos<len(alist) and not found and not stop:

if alist[pos]==item:

found=True

print("element found in position",pos)

else:
if alist[pos]>item:

stop=True

else:
pos=pos+1
return found
a=[]
n=int(input("enter upper limit"))
for i in range(0,n):
e=int(input("enter the elements"))
a.append(e)
x=int(input("enter element to search"))
search(a,x)

Output:

Enter upper limit 5

Enter the elements 6

Enter the elements 45

Enter the elements 2

Enter the elements 61

Enter the elements 26


Enter element to search 6
Element found in position 1

Result:

Thus the Python Program to perform linear search is executed successfully and the
output is verified.
Exp No.7b Implement binary search

Aim:

To write a Python Program to perform binary search.

Algorithm:

1. Read the search element

2. Find the middle element in the sorted list

3. Compare the search element with the middle element

i. if both are matching, print element found


ii.else then check if the search element is smaller or larger than the middle element
4. If the search element is smaller than the middle element, then repeat steps 2 and 3 for
the left sublist of the middle element
5. If the search element is larger than the middle element, then repeat steps 2 and 3
for the right sublist of the middle element
6. Repeat the process until the search element if found in the
list
7. If element is not found, loop terminates

Program:

def bsearch(alist,item):

first=0

last=len(alist)-1
found=False
while first<=last and not found:

mid=(first+last)//2

if alist[mid]==item:
found=True
print("element found in position",mid)

else:
if item<alist[mid]:

last=mid-1
else:

first=mid+mid-1

return found
a=[]

n=int(input("enter upper
limit"))

for i in range(0,n):
e=int(input("enter the elements"))
a.append(e)
x=int(input("enter element to search"))
bsearch(a,x)

Output:

enter upper limit 6

enter the elements 2

enter the elements 3

enter the elements 5

enter the elements 7

enter the elements 14

enter the elements 25


enter element to search 5

element found in position 2

Result:

Thus the Python Program to perform binary search is executed successfully and the
output is verified.
Exp No.8 Develop a python program to implement sorting methods

Aim:

To write a Python Program to perform selection sort.

Algorithm:

1. Create a function named selectionsort

2. Initialise pos=0

3. If alist[location]>alist[pos] then perform the following till i+1,

4. Set pos=location

5. Swap alist[i] and alist[pos]

6. Print the sorted list

Program:
def selectionSort(alist):
for i in range(len(alist)-1,0,-1):
pos=0
for location in range(1,i+1):
if alist[location]>alist[pos]:
pos= location
temp = alist[i]
alist[i] = alist[pos]
alist[pos] = temp
alist = [54,26,93,17,77,31,44,55,20]

selectionSort(alist)

print(alist)
Output:

[17, 20, 26, 31, 44, 54, 55, 77, 93]

Result:

Thus the Python Program to perform selection sort is successfully executed and the
output is verified.
Exp No.9 Develop python programs to perform operations on dictionaries

Aim:
To develop python programs to perform operations on dictionaries.

Program:

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Adding elements one at a time


Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Adding set of values


# to a single Key
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)

# Updating existing Key's Value


Dict[2] = 'Welcome' print("\
nUpdated key value: ")
print(Dict)
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}}
print("\nAdding a Nested Key: ")
print(Dict)

Output:

================= RESTART: C:/Users/students/Desktop/dict.py


================= Empty Dictionary:
{}

Dictionary after adding 3 elements:


{0: 'Geeks', 2: 'For', 3: 1}

Dictionary after adding 3 elements:


{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}

Updated key value:


{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}

Adding a Nested Key:


{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'Life', '2': 'Geeks'}}}
>>>

Result:
Thus the program to perform operations on dictionaries is executed successfully and
outputis verified.
Exp No.10 Write a python program to read and write into a file

Aim:

To write a Python program to find the most frequent words in a text read from a file.

Algorithm:

1. Read the filename

2. Open the file in read mode

3. Read each line from the file to count the words

4. Write each line from the file to replace the punctuations

5. Close the file

6. Print the words

Program:
# Program to show various ways to read and
# write data in a file.

L = ["This is Delhi \n","This is Paris \n","This is London \n"]

# \n is placed to indicate EOL (End of Line)

file1.write("Hello \n")

file1.writelines(L)

file1.close()

#to change file access modes

file1 = open("myfile.txt","r+")

print ("Output of Read function is ")

print (file1.read())

print
# seek(n) takes the file handle to the nth

# bite from the beginning.

file1.seek(0)

print ("Output of Readline function is ")

print (file1.readline())

print

file1.seek(0)

# To show difference between read and readline

print ("Output of Read(9) function is ")

print (file1.read(9))

print

file1.seek(0)

print ("Output of Readline(9) function is ")

print (file1.readline(9) )

file1.seek(0)

# readlines function

print ("Output of Readlines function is ")

print (file1.readlines() )

print

file1.close()
Output:

================= RESTART: C:/Users/students/Desktop/dict.py

================= Output of Read function is

Hello

This is Delhi

This is Paris

This is London

Output of Readline function

is Hello

Output of Read(9) function is

Hello

Th

Output of Readline(9) function is

Hello

Output of Readlines function is

['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

>>>

Result:
Thus the program to perform operations on dictionaries is executed successfully and
outputis verified.

You might also like