Problem Solving and Python Programming Laboratory
Problem Solving and Python Programming Laboratory
I SEMESTER
Regulation – 2019
0 04 2
1COURSE OBJECTIVES:
LIST OF PROGRAMS
PLATFORM NEEDED
Python 3 interpreter for Windows/Linux
TOTAL: 60 PERIODS
7. How to create, slice, change, delete and index elements using Tuple. 21
9. How to create, slice, change, add, delete and index elements using list. 25
13. Find the most frequent words in a text read from a file 32
A. Additional Exercises 41
B. Viva Questions 54
AIM:
ALGORITHM :
Step1: Start
Step2: read two numbers to find the GCD n1,n2.
Step3: rem=n1%n2
Step4: while rem!=0
n1=n2
n2=rem
rem=n1%n2
Step5: print GCDisn2.
Step6: Stop
PROGRAM/SOURCE CODE :
n1=int(input("Enter a number:"))
rem=n1%n2
while rem!=0 :
n1=n2
n2=rem
rem=n1%n2
Enter a number:54
Enter another number:24
GCD of given number is: 6
RESULT:
Thus the program to find the GCD of two numbers is executed and the output is obtained.
AIM:
To write a python program to find the square root of a number (Newton’s method)
ALGORITHM :
Step 1: Define a function for Newton square root with two arguments.
PROGRAM/SOURCE CODE :
def newtonSqrt(n, howmany):
approx = 0.5 * n
for i in range(howmany):
approx = betterapprox
returnbetterapprox
RESULT:
Thus the program to find the square root(Newton’s method) is executed and the output is
obtained.
AIM:
ALGORITHM :
Step 1: Start.
return(base*power(base,exp-1))
Step 7: Stop.
PROGRAM/SOURCE CODE:
if (exp==1):
return (base)
if (exp!=1):
return (base*power(base,exp-1))
print("Result:",power(base, exp))
Thus the program to find the exponentiation of a number is executed and the output is
obtained.
AIM:
ALGORITHM :
Step 1: Start.
PROGRAM/SOURCE CODE:
a=[ ]
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
Enter element: 3
Enter element:2
Enter element:1
Enter element:5
Enter element:4
RESULT:
Thus the program to find the Maximum of a List of numbers is executed and the output is
obtained.
AIM:
ALGORITHM:
Step 1: Start.
Step 8: Search the element with using for loop until length of list
PROGRAM/SOURCE CODE :
a=[ ]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
OUTPUT 1:
OUTPUT 2:
RESULT:
Thus the program to perform linear Search is executed and the output is obtained.
BINARY SEARCH
AIM:
ALGORITHM:
Exit
Go to Step:1
Go to Step:2
Else:
Exit
def Binary_search(arr,start_index,last_index,element):
mid =int((start_index+last_index)/2)
if (element>arr[mid]):
start_index = mid+1
elif (element<arr[mid]):
last_index = mid-1
return mid
else:
return -1
arr =[ ]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:")) # inputs must be in ascending order
arr.append(b)
print(arr)
element = int(input("Enter the element to be searched"))
start_index=0
last_index = len(arr)-1
found = Binary_search(arr,start_index,last_index,element)
if (found == -1):
print ("element not present in array")
OUTPUT 2:
Enter number of elements:7
Enter element:11
Enter element:15
Enter element:20
Enter element:25
Enter element:30
Enter element:40
Enter element:50
[11, 15, 20, 25, 30, 40, 50]
Enter the element to be searched 22
element not present in array
RESULT:
Thus the program to perform Binary Search is executed and the output is obtained.
SELECTION SORT
AIM:
ALGORITHM :
Step 1: Read the number of elements for the list from the user.
Step 4: Using the swap method the elements are sorted accordingly.
PROGRAM/SOURCE CODE:
RESULT:
Thus the program to perform Selection Sort is executed and the output is obtained.
INSERTION SORT
AIM:
ALGORITHM :
Step 1: Read the number of elements for the list from the user.
Step 5: If the condition is true swap the values by changing the position.
PROGRAM/SOURCE CODE :
def insertionSort(alist):
currentvalue = alist[index]
position = index
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
OUTPUT :
RESULT:
Thus the program to perform Insertion Sort is executed and the output is obtained.
AIM:
To write a python program to create, slice, change, delete and index elements using Tuple.
ALGORITHM :
PROGRAM/SOURCE CODE :
my_tuple = ('p','e','r','m','i','t')
print("Tuple indexing",my_tuple[0])
print("Tuple slicing",my_tuple[1:4])
my_tuple[4][1] = 9
print("Tuple changing",my_tuple)
del my_tuple
print("Tuple Delete",my_tuple)
Tuple indexing p
RESULT:
Thus the program to create, slice, change, delete and index elements using Tuple and the
output is obtained.
AIM:
ALGORITHM:
Step1: Take in the upper limit for the range and store it in a variable.
Step 2: Let the first for loop range from 2 to the upper limit.
Step4: Let the second for loop range from 2 to half of the number (excluding 1 and the number
itself).
Step 5: Then find the number of divisors using the if statement and increment the count variable
each time.
Step 6: If the number of divisors is lesser than or equal to 0, the number is prime.
PROGRAM/SOURCE CODE :
x = int (input ("Enter the number:")) # upto what you want to print the prime numbers
for k in range (1, (x+1)):
c=0
for j in range (1, (k+1)):
a = k%j
if (a= =0):
c = c+1
if (c= =2):
print (k)
RESULT:
Thus the program to find first n prime numbers is executed and the output is obtained.
AIM:
To write a python program to create, slice, change, delete and index elements using Tuple
ALGORITHM :
Step 3: Silicing an element from the List by using the slicing operator - colon ":"
PROGRAM/SOURCE CODE :
list = ['p','e','r','m','i','t']
print("List Created",list)
print("List indexing",list[0])
print("List slicing",list[1:4])
list = ['p','e','r','m','i','t']
print("Given list",list)
list[0]=2
print("List Changing",list)
list[1:4]=[1,2,3]
print("List Changing",list)
list = ['p','e','r','m','i','t']
list.append(['add','sub'])
print("List appending",list)
list = ['p','e','r','m','i','t']
print("Given list",list)
list.remove('p')
print("List Removing",list)
list = ['p','e','r','m','i','t']
print("Given list",list)
list[2:5] = []
print("List Delete",list)
List indexing p
List appending ['p', 'e', 'r', 'm', 'i', 't', ['add', 'sub']]
Given list ['p', 'e', 'r', 'm', 'i', 't']
RESULT:
Thus program to create, slice, change, delete and index elements using List is executed ant
the output is obtained.
AIM:
ALGORITHM :
Step 1: Start
Step 5: Stop
PROGRAM/SOURCE CODE :
def LenOfStr(s):
count=0
for i in s:
count=count+1
return count
OUTPUT :
Enter a string: SRM VALLIAMMAI
The number of character in original string is : 14
RESULT:
Thus the program to count the words is executed and the output is obtained.
AIM:
ALGORITHM :
PROGRAM/SOURCE CODE :
def reverse(s):
str = " "
for i in s:
str = i + str
return str
OUTPUT :
Enter a string:PYTHON PROGRAMMING
The original string is : PYTHON PROGRAMMING
The reversed string(using loops) is : GNIMMARGORP NOHTYP
RESULT:
Thus the program to reverse a string is executed and the output is obtained.
AIM:
To write a python program to to change, delete, add and remove elements in Dictionary
ALGORITHM :
PROGRAM/SOURCE CODE :
my_dict[5] = 25
my_dict[6] = 36
del my_dict[6]
RESULT:
Thus program to change, delete, add and remove elements in Dictionary is executed and the
output is obtained.
AIM:
To write a python program to find the most frequent words from a file.
ALGORITHM :
Step 5: Print the frequent words that are used in the file.
PROGRAM/SOURCE CODE :
handle=open('sample.txt','w')
handle.write("hi hello hello how are you")
handle.close()
name=input ("Enter file name:")
handle = open(name, 'r')
text = handle.read()
words = text.split()
counts = dict()
counts[word] = counts.get(word,0) + 1
bigcount = None
bigword = None
bigword = word
print(bigword, bigcount)
OUTPUT :
RESULT:
Thus the program to find the most frequent words in a text is executed and the output is
obtained.
AIM:
ALGORITHM :
Step 1: Import the necessary header files for the implementation of this pygame.
white=(255,255,255)
blue=(0,0,255)
yellow=(255,255,0)
gray=(200,200,200)
black=(0,0,0)
Step 4: Set the radius for sun, moon and their orbit.
Step 9: Reset the screen and draw the stars, sun, moon and the earth.
import pygame
import random
import math
pygame.init()
screen=pygame.display.set_mode((700,700))
white=(255,255,255)
blue=(0,0,255)
yellow=(255,255,0)
gray=(200,200,200)
black=(0,0,0)
sun_radius=50
center=(350,350)
earth_x=50
earth_y=350
earth_orbit=0
moon_orbit=0
clock=pygame.time.Clock()
running=True
while running:
if event.type==pygame.QUIT:
running=False
earth_x=math.cos(earth_orbit)*300+350
earth_y=-math.sin(earth_orbit)*300+350
moon_y=-math.sin(moon_orbit)*50+earth_y
earth_orbit+=0.002
moon_orbit+=0.01
screen.fill(black)
x,y=star[0],star[1]
pygame.draw.line(screen,white,(x,y),(x,y))
pygame.draw.circle(screen,yellow,center,sun_radius)
pygame.draw.circle(screen,blue,(int(earth_x),int(earth_y)),15)
pygame.draw.circle(screen,gray,(int(moon_x),int(moon_y)),5)
pygame.display.flip()
clock.tick(60)
pygame.quit()
OUTPUT :
Thus the simulation of elliptical curve orbit using pygameis executed and the output is
obtained.
AIM:
Step 3: Now set the display mode for the pygame to bounce
pygame.display.set_caption(“Bounce”)
BLACK=(0,0,0)
WHITE=(255,255,255)
RED=(255,0,0)
GREEN=(0,255,0)
BLUE=(0,0,255)
importpygame,sys,time
import random
frompygame.locals import *
pygame.init()
windowSurface=pygame.display.set_mode((500,400),0,32)
pygame.display.set_caption("Bounce")
BLACK=(0,0,0)
WHITE=(255,255,255)
RED=(255,0,0)
GREEN=(0,255,0)
BLUE=(0,0,255)
info=pygame.display.Info()
sw=info.current_w
sh=info.current_h
y=0
direction=1
while True:
windowSurface.fill(BLACK)
pygame.draw.circle(windowSurface,GREEN,(250,y),13,0)
sleep(0.006)
y+=direction
if y>=sh:
direction=-1
elif y<=100:
39 LM- 1901009 [PSPPL]
direction=1
pygame.display.update()
if event.type==QUIT:
pygame.quit()
sys.exit()
OUTPUT :
RESULT:
Thus the program to simulate bouncing ball using pygameis executed and the output is
obtained.
A1.TOWER OF HANOI
AIM:
ALGORITHM:
Step 3:Move a tower of height-1 to an intermediate pole, using the final pole.
Step 5: Move the tower of height-1 from the intermediate pole to the final pole using the original
pole.
if height >= 1:
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
defmoveDisk(fp,tp):
moveTower(3,"A","B","C")
RESULT:
Thus the program for Tower of Hanoi scenario is executed and the output is obtained.
AIM:
To write a program to find given number is Armstrong or not.
ALGORITHM
1. Start
2. Declare variables
3. Read the Input number.
4. Calculate sum of cubic of individual digits of the input.
5. Match the result with input number.
6. If match, Display the given number is Armstrong otherwise not.
7. Stop
SOURCE CODE
num = 1634
# initialize sum
sum = 0
digit = temp % 10
sum += digit **
else:
OUTPUT
Result:
Thus the program to find the Armstrong number is executed successfully.
AIM:
To write a program on bubble sort algorithm.
ALGORITHM
1. Start
2. Declare variables and create an array
3. Read the Input for number of elements and each element.
4. Develop a function bubblesort to sort the array
5. Compare the elements in each pass till all the elements are sorted.
6. Display the output of the sorted elements .
7. Stop
SOURCE CODE
def shortBubbleSort(alist):
exchanges = True
passnum = len(alist)-1
exchanges = False
for i in range(passnum):
ifalist[i]>alist[i+1]:
exchanges = True
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
passnum = passnum-1
shortBubbleSort(alist)
print(alist)
OUTPUT
[20,30,40,50,60,70,80,90,100,110]
Result:
ALGORITHM
1. Start
2. Declare variables and initializations
3. Read the Input variable.
4. Define recursive expression for computational processing.
5. Return the output of the calculations.
6. Stop
SOURCE CODE
def recur_sum(n):
if n <= 1:
return n
else:
return n + recur_sum(n-1)
if num< 0:
else:
OUTPUT
Result:
Thus the python program to find the sum of natural number up to n using recursive
function has been executed.
ALGORITHM
1. Start
2. Declare&Initializations of list.
3. Using + operator for computational processing of merge the two lists.
4. Return the output of the calculations.
5. Stop
SOURCE CODE
# Initializing lists
test_list3 = [1, 4, 5, 6, 5]
test_list4 = [3, 5, 7, 2, 5]
Output
Result:
Thus the program to merge two list has been executed successfully.
ALGORITHM
SOURCE CODE
def removeduplicateele(A):
newlist = [ ]
for n in A:
return newlist
# Driver Code
A=list()
for i in range(int(n)):
k=int(input(""))
A.append(int(k))
10
20
30
20
10
Result:
Thus the to remove duplicates elements from a List is obtained
AIM:
ALGORITHM :
Step1. Create one variable to hold the file path. This is a constant variable. In the example we are
showing here, you need to change this value with the file path in your own system. Also, initialize
one more variable to hold the total count of words. Initialize this variable as zero.
Step2. Open the file in read-only mode. We are only reading the content of the file for this
example. For counting the number of words in the file, read mode will be sufficient.
Step 3. Iterate through each line of the file using a loop. As this is a text file, we can iterate through
the lines one by one.
Step4. Inside the loop, split the line into its words. Find out the total number of words and add them
to the variable used to hold the total count of words. On each iteration of the loop, add the count of
each line to this variable.
Step5. After the loop will complete, the word count variable will hold the total count of words in the
text file. Print out the value of this variable to the user.
PROGRAM/SOURCE CODE :
word_count = 0
file_name = "D//in.txt"
OUTPUT
Number of words : 9
RESULT:
Thus the finding the count of the number of words in file is obtained.
AIM:
ALGORITHM
Step 2: Take the string from the user and assign it in a variable s.
Step 3: Generate all permutation using the permutation function and assign it in a
variable p.
Step 4: Since all elements of p are in tuple form. So, convert it in the list.
Step 5: At last, add all list elements and print it which is our possible permutations
PROGRAM/SOURCE CODE :
A=[]
b=[]
p=permutations(s)
for k in list(p):
A.append(list(k))
for j in A:
r= ' '. join(str(l) for l in j)
b.append(r)
RESULT:
Thus the program to generate all permutations of a string hasbeen executed successfully.
1.What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released in
1991.
It is used for:
3. Define Docstrings.
Python also has extended documentation capability, called docstrings. Docstrings can be one line,
or multiline.
Python has commenting capability for the purpose of in-code documentation.Comments start with a
#, and Python will render the rest of the line as a comment.
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• int
• float
• complex
54 LM- 1901009 [PSPPL]
8.What is the use of type() function?
To verify the type of any object in Python, use the type() function:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
There are four collection data types in the Python programming language:
• Equals: a == b
• Not Equals: a != b
The elif keyword is pythons way of saying "if the previous conditions were not true, then try
this condition"
The else keyword catches anything which isn't caught by the preceding conditions.
• while loops
• for loops
With the while loop we can execute a set of statements as long as a condition is true.
With the break statement we can stop the loop even if the while condition is true:
With the continue statement we can stop the current iteration, and continue with the next:
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set,
or a string).
To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and ends at a specified number.
A function is a block of code which only runs when it is called.You can pass data, known as
parameters, into a function.A function can return data as a result.
22.What is Recursion?
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls itself.
This has the benefit of meaning that you can loop through data to reach a result.
A lambda function is a small anonymous function. A lambda function can take any number of
arguments, but can only have one expression.
The power of lambda is better shown when you use them as an anonymous function inside another
function.Say you have a function definition that takes one argument, and that argument will be
multiplied with an unknown number.
The examples above are classes and objects in their simplest form, and are not really useful in real
life applications. To understand the meaning of classes we have to understand the built-in __init__()
function. All classes have a function called __init__(), which is always executed when the class is
being initiated. Use the __init__() function to assign values to object properties, or other operations
that are necessary to do when the object is being created:
Objects can also contain methods. Methods in objects are functions that belongs to the object.
The self parameter is a reference to the current instance of the class, and is used to access variables
that belongs to the class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
An iterator is an object that contains a countable number of values.An iterator is an object that can be
iterated upon, meaning that you can traverse through all the values.Technically, in Python, an iterator
is an object which implements the iterator protocol, which consist of the methods __iter__() and
__next__().
Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you
can get an iterator from.
All these objects have a iter() method which is used to get an iterator:
To create a module just save the code you want in a file with the file extension .py:
A date in Python is not a data type of its own, but we can import a module named datetime to work
with dates as date objects.
JSON is a syntax for storing and exchanging data. JSON is text, written with JavaScript object
notation.
Python has a built-in package called json, which can be used to work with JSON data.
RegEx can be used to check if a string contains the specified search pattern.
39.What is a Package?
A package contains all the files you need for a module. Modules are Python code libraries you
can include in your project.
When an error occurs, or exception as we call it, Python will normally stop and generate an
error message. These exceptions can be handled using the try statement:
The try block lets you test a block of code for errors.
The finally block lets you execute code, regardless of the result of the try- and except blocks.
The key function for working with files in Python is the open() function.
There are four different methods (modes) for opening a file: "r" - Read - Default
value. Opens a file for reading, error if the file does not exist "a" - Append -
Opens a file for appending, creates the file if it does not exist "w" - Write -
Opens a file for writing, creates the file if it does not exist "x" - Create - Creates