You are on page 1of 85

VELAMMAL ENGINEERING COLLEGE

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

I YEAR / II SEMESTER

19CS103T – PROGRAMMING FOR PROBLEM SOLVING USING PYTHON

LABORATORY

Submitted by

REG NO:

Name of the Student:


LAB EXPERIMENTS

Sl.No. Name of the Experiment

1. Programs using operators


2. Programs using conditional statements
3. Programs using looping statements
4. Recursive functions – Towers of Hanoi
5. Programs using strings
6. Searching – Linear and Binary
7. Sorting – Selection, Insertion and Merge
8. Matrix – Addition and Multiplication
9. Histograms
10. Plotting graphs
11. Files – reading and writing
12. File Copy
13. Programs using Exception Handling
14. Simulate elliptical orbits in Pygame.
15. Simulate bouncing ball using Pygame.
16. Mini Project -
Exp. No 1. To Convert Celsius to Fahrenheit Temperature
Date:

Aim: To implement a python program to convert the temperature given in Celsius into
Fahrenheit.

Algorithm:

Step1: Start
Step2: Enter the temperature in Celsius
Step3: Calculate Fahrenheit using the formula
f=c*1.8+32
Step4: Print Fahrenheit
Step5: Stop
Flow Chart:

Start

Enter Celsius,c

Fahrenheit f=c*1.8+32

Print
Fahrenheit f f

Stop
Program:

c=float(input("Enter the Celsius"))


f=c*1.8+32
print("Fahrenheit=",f)

Output:
Enter the Celsius 37.6
Fahrenheit=99.68

Result:
Thus Python program to convert Celsius to Fahrenheit temperature is executed and output is
verified.
Exp. No 2. To Find the square root of a number (Newton‘s method)
Date:

Aim: To implement a python program to find the square root of a number using Newton’s
method.

Algorithm:

Step1: Start
Step2: Enter the number for which square root is to be calculated, n
Step3: Enter the guess number which may be the square root of the number, x
Step4: Compute new_x=1/2(x+n/x) , Newton’s formula to find the new guess
Step 5: Compute new_x=1/2(x+n/new_x) till the approximate square root is found,
Step6: Print the square root new_n
Step7: Stop

Flow Chart:

Start

Enter the number to find the square root

Enter the guess number

new_x=0.5*(x+(n/x))

Print new_x

F
for i in
range(0,10)
T

new_x=0.5*(new_x+
(n/new_x))

Print new_x

Stop
Program:
n=float(input("What number you like to square root?"))
x=float(input("Enter your guess number:"))
print(“Square root Approximation:”)
new_x=0.5*(x+(n/x))
print(new_x)
for i in range(0,10):
new_x=0.5*(new_x+(n/new_x))
print(new_x)

Output:
What number you like to squareroot?12
Enter your guess number:7
Square root Approximation:
4.357142857142857
3.5556206088992974
3.465279430087719
3.4641018153017074
3.4641016151377606
3.4641016151377544
3.4641016151377544
3.4641016151377544
3.4641016151377544
3.4641016151377544
3.4641016151377544

Result:
Thus Python program to find the square root of a number using Newton method is executed and
output is verified.
Exp. No 3. Exponentiation of a number
Date:

Aim: To implement a Python program to calculate the exponentiation of number using exponent
operator.

Algorithm:

Step1. Start
Step2. Enter the value of a and b(to the power of a)
Step3.Multiply a and b using exponent (**) operator
Step4. Store the value into c
Step5.Print c
Step6. Stop

Flow chart:

Start

Enter the value of a

Enter the value of b

c=a**b

Print c

Stop
Program:

a=int(input(“Enter the first number:”))


b=int(input(“Enter the power of first number:”))
c=a**b
print(c)

Output:

Enter the first number:2


Enter the power of first number:3
8

Result :
Thus a Python program to calculate the exponentiation of number using exponent operator is
implemented.
Exp. No 4. Distance between two points
Date:

Aim: To implement a Python program to find the distance between two points .

Algorithm:

Step1. Start
Step2. Enter the value of x1 and x2
Step3.Enter the value of y1 and y2
Step4. Use formula ((((x2-x1)**2)+((y2-y1)**2))**0.5) and store the result into d
Step5.Print d
Step6. Stop

Start

Enter the value of x1 & x2

Enter the value of y1 & y2

d= (((x2-x1)**2)+((y2-y1)**2))**0.5

Print d

Stop
Program:

x1=int(input(“enter the number:”))


x2=int(input(“enter the number:”))
y1=int(input(“enter the number:”))
y2=int(input(“enter the number:”))
d= (((x2-x1)**2)+((y2-y1)**2))**0.5
print(d)

Output:
enter the number:4
enter the number:2
enter the number:1
enter the number:1

Result :
Thus a Python program to find the distance between two points is implemented.
Exp. No 5. Finding polynomial coefficients
Date:

Aim: To implement a Python program to find coefficients of the polynomial

Algorithm:

Step1. Start
Step2. Define the function ‘poly’
2.1. Assign the values 0 to sum and list to xp
2.2. Iterate the list with the iterator variable ‘a’
2.2.1. Calculate sum=sum+a*xp
2.2.2. caompute xp=x+xp
2.2.3. Return the sum value
Step 3. Do function call
Step 4. Stop

Start
Flow chart:

Call poly(l,x)

Sum=0; xp=l

F
For a times
T

Sum=sum+a*xp
Xp=x+xp

Return the value

Print the value

Stop
Program:

def poly(l, x):


sum = 0
xp =1
for a in l:
sum += a *xp
xp = x* xp
return sum
print (poly([1,2,1],2))
print (poly([1,0,1,0,1],3))

Output:
9
91

Result : Thus Python program to calculate the coefficients of polynomial is implemented.


Exp. No 6. Finding leap year or not
Date:

Aim: To implement a Python program to find whether a given year is leap or not.

Algorithm:

Step1. Start
Step2. Enter the year
Step3. Check the condition (year%4 and year%100!=0 or year%400)
3.1.If the condition is satisfied, then print the given year is leap
3.2. Otherwise, print the given year is not leap
Step4. Stop

Start

Enter the year

if(year%4==0 and year False


%100!=0 or year
%400==0)

True

Print leap year Print not leap year

Stop
Program:

year=int(input("Enter year to be checked:"))


if(year%4==0 and year%100!=0 or year%400==0):
print(“The year is a leap year!”)
else:
print(“The year isn't a leap year!”)

Output:

Enter year to be checked:1200


The year is a leap year!
Enter year to be checked:1987
The year isn't a leap year!

Result:
Thus a Python program to find the given year is leap or not is implemented.
Exp. No 7. To Exchange the values of two variables

Date:

Aim: To implement a Python program to exchange the values of two variables.

Algorithm:

Step 1: Start
Step 2: Read the values of a and b.
Step 3:compute a=a+b
b=a-b
a=a-b
Step 4: Print the values of a and b
Step 5: Stop

Flow Chart:
Start

Read a,b

a=a+b
b=a-b
a=a-b

Print a,b

Stop
Program:

a=int(input("Enter value of first variable: "))


b=int(input("Enter value of second variable: "))
a=a+b
b=a-b
a=a-b
print("The value of a is:",a,"The value of b is:",b)

Output :

Enter value of first variable: 3


Enter value of second variable: 5
The value of a is: 5 The value of b is: 3

Result:
Thus Python program to exchange the values of two variables is implemented.
Exp. No 8. To Circulate the values of n variables

Date:

Aim: To implement python program to circulate the values of n variables

Algorithm:

Step 1: Get three values as input from the user

Step 2: Perform
temp=a
a=b
b=c
c=temp
Step 3: Print the values of a,b,c

Flowchart:
Start

Read a,b,c

temp=a
a=b
b=c
c=temp

Print a,b,c

Stop
Program:

a=int(input(“Enter the value for A:”))


b=int(input(“Enter the value for B:”))
c=int(input(“Enter the value for C:”))
temp=a
a=b
b=c
c=temp
print(“The Circulated values of A,B and C is:”,a,b,c)

Output:
Enter the value for A:10
Enter the value for B:20
Enter the value for C:30
The Circulated values of A,B and C is: 20 30 10

Result: Thus Python program to circulate the value of n variables is implemented.


Exp. No 9. To Calculate the GCD of two numbers
Date:

Aim: To implement Python program to calculate the GCD of two numbers

Algorithm:

Step 1: Get two values from the user x,y

Step 2: Repeat the following until y !=0

2.1  Do swapping by x, y = y, x % y 

Step 4: The value of x gives the GCD , Print x

Flowchart:

Start

Read x,y

F
Whil
e y!
=0
T

x , y = x%y , y

Print x

Stop
Program:

x=int(input(“Enter the value for x:”))

y=int(input(“Enter the value for y:”))

while b!=0:

a,b=b,a%b

print(a,b)

print('The GCD of x and y is:', a)

Output:

Enter the value for x:48

Enter the value for y:12

The GCD of x and y is : 12

Result: Thus Python program to find the GCD of two numbers is implemented.
Exp. No 10. Towers of Hanoi

Date:

Aim: To implement a Python program to move discs from source pole to destination pole using
recursive function.

Algorithm:
Step 1. Start
Step 2. Read number of discs N
Step 3. If N=1 Move Single disc from source to dest .
Step 4. Move n-1 disks from source to aux
Step 5. Move nth disk from source to dest.
Step 6. Move n-1 disks from aux to dest.
Step 7. Stop
Flowchart:
Program:

def moveTower(height,fromPole, toPole, withPole):

if height >= 1:

moveTower(height-1,fromPole,withPole,toPole)

moveDisk(fromPole,toPole)

moveTower(height-1,withPole,toPole,fromPole)

def moveDisk(fp,tp):

print("moving disk from",fp,"to",tp)

moveTower(3,"A","B","C")

Output:
moving disk from A to B
moving disk from A to C
moving disk from B to C
moving disk from A to B
moving disk from C to A
moving disk from C to B
moving disk from A to B

Result:

Thus Python program to move discs from source pole to destination pole using recursive
function is implemented successfully.
Exp. No 11. Factorial of a Number
Date:

Aim: To implement Python program to find factorial of a given number.

Algorithm:

Step 1. Start
Step 2. Read the number n
Step 3. Initialize i=1, fact=1
Step 4. Repeat the following until i=n
4.1. fact=fact*i
4.2. i=i+1
Step 5. Print fact
Step 6. Stop Start

Flowchart:
Read
N

i = 1 fact=
1

1 *
factF == fact
i

F
i=i+1 is i=N ?

T
Print
fact

Stop
Program:

num = int(input("Enter number to find its factorial ::: "))


factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

Output:

Enter number to find its factorial ::: -1


Sorry, factorial does not exist for negative numbers

Enter number to find its factorial ::: 0


The factorial of 0 is 1

Enter number to find its factorial ::: 5


The factorial of 5 is 120

Result:
Thus Python program to find factorial of a given number is implemented successfully.
Exp. No 12. To Reverse a given Number
Date:

Aim: To implement a Python program to find reverse of a given number.

Algorithm:

Step 1.Start
Step 2.Read Input number: n
Step 3.Initialize rev = 0
Step 3.Loop while n> 0
3.1.divide n by 10 and store the remainder in dig
3.2.rev = rev*10 + dig;
3.3.Divide n by 10
Step 4.Print rev
Step 5.Stop

Flowchart:

Star
t

Read
N

rev=0

is N >
0?
F T

dig = N%10

rev = rev*10 +
dig
N = N/10

Print rev

Sto
p
Program:

n=int(input("Enter number: "))


rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
print("Reverse of the number:",rev)

Output:

Enter number: 123


Reverse of the number: 321

Result: Thus Python program to find reverse of a given number is implemented successfully.
Exp. No.13. To print all Prime Numbers in an Interval of Numbers
Date:

Aim : To implement Python program to print all prime numbers in an interval of numbers.

Algorithm:

Step 1. Start
Step 2. Enter the lower interval and upper interval
Step 3. Repeat step 3.1and step 3.2 for each integer num in the lower to upper interval
Step 3.1.If num % any interger i in interval is equal to zero then num is not prime
Step 3.2.else Print the num value as prime and repeat from step 3 for next value in
interval
Step4.Stop

Flow Chart:

Start

Enter the upper and lower


interval

F
for num in range
(lower,upper+1)
and (num>1)

Print num T

F T i in
for
range(2,num)

T
If num F

Stop
Program:

lower = int(input("Enter the lower interval::: "))


upper = int(input("Enter the Upper interval::: "))
print("Prime numbers between ",lower," and ",upper," are: ")
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)

Output :

Enter the lower interval::: 10


Enter the Upper interval::: 50
Prime numbers between 10 and 50 are:
11
13
17
19
23
29
31
37
41
43
47

Result : Thus Python program to print all prime numbers between an interval of numbers is
implemented.
Exp.No.14. To Print Pascal’s triangle for n number of rows
Date:

Aim : To implement a Python Program to print the pascal’s triangle for n number of rows .

Algorithm:
Step1. Start
Step 2. Read no.of rows n
Step 3. Initialize list trow=[1],y=[0]
Step 4. Repeat step 4.1 and 4.2 n no. of times
Step 4.1. Print trow
Step 4.2. List trow is re-created by adding elements of trow+y and y+trow using zip
function
Step 5. Stop

Flow Chart:

Start

Read no.of rows


n
Initialize list trow=[1],y=[0]

for n times

Print trow

List trow is re-created by adding elements of


trow+y and y+trow using zip function

Sto
Program:

def pascal_triangle(n):
trow = [1]
y = [0]
for x in range(max(n,0)):
print(trow)
trow=[l+r for l,r in zip(trow+y, y+trow)]
return n>=1
pascal_triangle(6)

Output :

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]

Result : Thus Python Program to print the pascal’s triangle for n number of rows is
implemented.
Exp. No.15. To Check if a String is a Palindrome
Date:

Aim: To implement a Python Program to check if a string is a palindrome or Ft.

Algorithm:

Step 1. Start
Step 2. Read string s
Step 3. String s is compared with its reverse using string slicing
Step 3.1. If both are equal, print the string is a palindrome
Step 3.2.else print the string is not a palindrome
Step 4. Stop

Flow Chart:

Start

Read String
s

If (str = =
str[::-1])

Print string is not palindrome


T

Print string is palindrome

Stop
Program:

string=input("Enter string:")
if(string==string[: : -1]):
print("The string is a palindrome")
else:
print("The string isn't a palindrome")

Output:

Case 1:
Enter string:mam
The string is a palindrome
 
Case 2:
Enter string:hello
The string isn't a palindrome

Result: Thus a Python Program to check if a string is a palindrome or Ft is implemented


Ex.No.16. To Calculate the Number of Words and Characters
present in a String
Date:

Aim: To implement a Python Program to calculate the number of Words and Characters present
in a String

Algorithm:

Step 1. Start
Step 2. Read string s

Step 3. Initialize the character count variable = 0 and word count variable = 1.
Step 4. Traverse through the string s and Repeat steps 4.1 and 4.2 for each character in the string
Step 4.1.Increment character count variable each time.
Step 4.2. Increment the word count variable only if a space is encountered.

Step 5. Print the total count of the characters and words in the string.
Step 6. Stop
Flow Chart:

Start

Read string s

Initialize char=0, word = 1

F
for each
character
Stop i in s

char = char+1

F T
If i is space

word = word+1
Program:

string=input("Enter string:")
char=0
word=1
for i in string:
char=char+1
if ( i == ' '):
word=word+1
print("Number of words in the string:")
print(word)
print("Number of characters in the string:")
print(char)

Output:

Enter string: Hello world


Number of words in the string:
2
Number of characters in the string:
11
 

Result : Thus a Python program to calculate the number of Words and Characters present in a
String is implemented.
Ex.No.17. To Count the number of Vowels in a String
Date:

Aim: To implement Python program to Count the number of Vowels in a String.

Algorithm:

Step 1: Start
Step 2: Read string s.
Step 3: Initialize a count = 0.
Step 4: for each character in the string s.
Step 5: if character = vowel increment count else go to step 4
Step 6: Print the total number of vowels in the string.
Step 7: Stop

Flow chart:

Start

Read string s

F
For i through
Initialize each
count=0
character in string s

If i is a
vowels

F
T
vowel = vowel +1
Program:

string=raw_input("Enter string:")
vowel=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or
i=='U'):
vowel = vowel +1
print("Number of vowels are:")
print(vowel)

Output:

Enter string:Hello world


Number of vowels are:
3

Result : Thus a Python program to Count the number of Vowels in a String is implemented.
Exp. No 18. To Sum an array of numbers and determine its Average
Date:

Aim : To implement a Python program to determine the sum and average of numbers in an array
using list.

Algorithm:

Step1. Start

Step2. Enter the no. of elements for the list ‘n’

Step3. Iterate the loop n times

3.1. Input the elements of the list

3.2.Append the elements to the list

Step 4. Calculate the total sum of elements in the list.

Step 5. Divide the sum by total number of elements in the list to find average

Step 6. Print sum and average

Step7.Stop

Flow Chart: Start

Enter the no. of elements in list ‘n’

For n
times in
List
Input the elements of the list

Append the elements


to the list

Calculate the total sum of elements in the list

Divide the sum by total number of


elements in the list to find average

Print sum and average

Stop
Program:

n=int(input("Enter the number of elements to be inserted: "))


a=[ ]
for i in range(0,n):
elem=int(input("Enter element: "))
a.append(elem)
s=sum(a)
avg=s / n
print("Sum of elements in the list=", s )
print("Average of elements in the list=", round (avg ,2 ) )

Output :

Enter the number of elements to be inserted: 5


Enter element: 12
Enter element: 24
Enter element: 33
Enter element: 25
Enter element: 18
Sum of elements in the list=112
Average of elements in the list= 22.4

Result : Thus a Python program to determine the sum and average of numbers in an array using
list is implemented.
Ex.No.19. Finding maximum from a list of numbers
Date:

Aim: To write a Python Program to find the maximum from a list of numbers.

Algorithm:

Step 1.Start
Step 2.Creating a list with some values
Step 3. Assign the first value of the list as the maximum.
Step 4. Iterate or repeat steps 4.1 and 4.2 up to length of the list
4.1.Compare the current element in the list with maximum element
4.2. If the element is greater than the maximum, then set that element as maximum.
Step 5.Display the maximum element in the list.
Step 6.Stop
Flowchart:
Program:

l=[3,10,2,15,2]

max=l[0]

for i in range(len(l)):

if(l[i]>max):

max=l[i]

print("Maximum value in the list:",max)

Output:

Maximum value in the list : 15

Result:

Thus a Python program to determine the maximum number from a list is implemented.
Exp.No.20. To Insert a Card using a List
Date:

Aim : To implement a Python Program to insert a card using a list.

Algorithm:
Step 1. Start
Step 2. Read list A, value , index
Step 3. Sort list A
Step 4. Insert value in the index position of list
Step 5. Print list A
Step 6. Stop

Flow Chart:

Start

Read list A, value ,


index

Sort list A

Insert value in the index position of list A

Print list A

Sto
Program:

A=eval(input(‘Enter list =‘))


index=eval(input(‘Enter index were to insert=’))
value=eval(input(‘Enter value to be insert=’))
A.sort()
A.insert(index ,value)  
print(A)  

Output :
Enter list = [10, 2, 3, 4]
Enter index were to insert=1
Enter value to be insert=11
[10, 11, 2, 3, 4]

Result : Thus Python Program to insert a card using a list is implemented.


Exp.No.21.To Guess a Number
Date:

Aim : To implement a Python Program to guess a number using a list.

Algorithm:
Step 1. Start
Step 2. Read list A and guessed number
Step 3. If number in list A print the guessed number is in list
Step 4. Else print the guessed number is not in list A
Step 5. Stop

Flow Chart:

Start

Read list A and guessed


number

F
If
number
in list A
Print guessed
T number is not in
list
Print guessed
number is in list

Sto
p
Program:

A = list(range(1, 10))
number = int(input('Enter a number='))
if number in A:
print(‘Guessed number’,number, ‘is in list’, list(range(1, 10)))
else:
print(‘Guessed number’,number, ‘ is not in list’, list(range(1, 10)))

Output :
Enter a number= 6
Guessed number 6 is in list [1, 2, 3, 4, 5, 6, 7, 8, 9]

Result : Thus Python Program to guess a number using a list is implemented.


Exp. No. 22. Multiply Matrices
Date:

Aim : To implement Python Program to Multiply Matrices

Algorithm:

Step 1. Start
Step 2. Read matrix a and b as nested list
Step 3. Find dimension of matrix a (m1 x n1) and b (m2 x n2)
Step 4.if n1 = m2 then
Step 4.1. Create result matrix of dimension (m1 x n2) using list comprehension
Step 4.2. for i traversing through rows of matrix a
Step 4.2.1 for j traversing through column of matrix b
Step 4.2.1.1 for k incremented till n1
Step 4.2.1.1.1 result[i][j] + = a[i][k] * b[k][j]
Step 5. Print result matrix
Step 6. Stop
Flow Chart:

Start

Read matrix a and b as nested list

Find dimension of matrix a (m1 x n1) and b (m2 x n2)

if n1 =
m2
F T

Initialize result matrix with dimension


m1 x n2

F
for i through
rows of matrix
a
T
F
for j through
column of matrix
b
T

F
for k
incremented till
n1
T

result[i][j]+=m1[i][k]*m2[k][j]

Print cannot
multiply matrices Print
result
matrix

Stop
Program:

a=eval(input("Enter the first matrix:"))


b=eval(input("Enter the second matrix:"))
m1=len(a)
n1=len(a[0])
m2=len(b)
n2=len(b[0])
if (n1==m2):
result=[[0]*n2 for x in range(m1)]
for i in range(m1):
for j in range(n2):
for k in range(n1)):
result[i][j] + = a[i][k] * b[k][j]
else:
print(“Check dimensions of matrices to be multiplied”)
print("Result matrix=")
for r in result:
print(r)

Output :

Enter the first matrix:[[1,2,1],[1,2,3],[1,2,1]]


Enter the second matrix:[[1,2,1],[1,2,3],[1,2,1]]
Result matrix=
[4, 8, 8]
[6, 12, 10]
[4, 8, 8]

Result : Thus Python program to multiply two matrices is implemented.


Exp. No. 23. Linear Search
Date:

Aim: To implement a Python program to search an element in a list using linear search.

Algorithm:

Step 1. Start the program

Step 2. Input the elements to the list , l

Step 3. Enter the element to be searched, value

Step 4.For i = every element of list l until the end of the list

Step 4.1 If i= =value

Step 4.1.1 Print value is found in the list l

Step 4.1.2.Go to step 6

Step 5. Otherwise if end of list, print value is not found in the list.

Step 6.Stop
Flow Chart:

Start

Input the elements to the list l

Enter the element to


be searched, value

For element i in F
List l

T Print the value


is Ft found
F
if
i==value

Print the value is found

Stop
Program:

l=eval(input(“Enter list:”))
value=int(input(“Enter the value to be searched:”))
for i in l:
if i==value:
print(value,"is found in the list")
break
else:
print(value,"is Ft found in the list")

Output :

Enter list :[1,-7,2,4,5]


Enter the value to be searched:5
5 is found in the list

Result : Thus a Python program to search an element in a list using linear search is
implemented.
Exp. No. 24. Binary Search
Date:

Aim : To implement a Python program to search an element in a list using binary search.

Algorithm:

Step1. Start

Step2. Input the elements to the list and item to be searched.

Step3. Initialize first =0, found =False and last=length of list

Step4. While (first<=last and found =False)

Step 4.1 Find the middle element by using mid= (first+last)//2

Step 4.2 If item_list[mid]= =item, return found as true.

Step 4.3. Else if item<item_list[mid],

Step 4.3.1 Perform a binary search of the left half of the original list repeating

from step 4 with last=mid-1

Step 4.4 Else Perform a binary search of the right half of the original list repeating from

step 4 with first=mid+1

Step 5:Print found

Step 6: Stop
Flow Chart:
Start

Input the elements


to the list and item
to be searched

Initialize first =0
found =False
last=len(list)-1

While F
(first<=last and
found =False)

mid= (first+last) //2

F If
T
item_list[mid]=
=item

T if F
item<item_list[mi
d]

first=mid+1 found =True


last=mid-1

Print found
Program:

Stop
def binary_search(item_list,item):
first=0
last=len(item_list)-1
found=False
while(first<=last and Ft found):
mid=(first+last)//2
if item_list[mid]==item:
found=True
else:
if item<item_list[mid]:
last=mid-1
else:
first=mid+1
return found
print(binary_search([1,2,3,5,8],6))
print(binary_search([1,2,3,5,8],5))

Output :

False

True

Result :Thus a Python program to search an element using binary search is implemented.
Ex.No.25. Selection Sort
Date:

Aim:To implement Python program for sorting a lit using selection sort.

Algorithm:

Step1.Create an empty list A[]

Step2.Input the number of elements , n

Step3.Input the elements in the list with input() and append() method for n no.of times

Step4.for i in range of length of elements in list A

Step 4.1.Initialize i to min_idx

Step 4.2.for j in range(i+1,len(A))

Step 4.2.1. if(A[min_idx]>A[j]

Step 4.2.2.Initialize j to min_idx

Step 4.3. A[i],A[min_idx]=A[min_idx],A[i]

Step5.Print list A

Step6.Stop
Flowchart:
Start

Input number of elements n

F
for i in
range(
n)
T

Read input element a

Append a to A

F
for i in of length
of elements in list
A
T

min_idx=j

F
for j in
range(i+1,len(
A))

T
F
If
A[min_idx]>A[j]

T
min_idx=j

A[i],A[min_idx]=A[min_idx],A[i]

Print sorted list A

Stop
Program:

A=[ ]

print(“Enter number of elements in the list”)

n=int(input())

print(“enter elements in the list”)

for i in range(n)

a=int(input())

A.append(a)

Print(*****Selection Sort******)

for i in range(len(A))

min_idx=i

for j in range(i+1,len(A))

if(A[min_idx]>A[j]):

min_idx=j

A[i] , A[min_idx] =A[min_idx] , A[i]

print (“Sorted List:”,A)

Output:

Enter number of elements in the list


5
Enter elements in the list
1
3
2
77
11
*****Selection Sort*****
Sorted List: [1,2,3,11,77]

Result: Thus Python program to sort a list using selection sort is implemented.
Ex.No.26. Insertion Sort
Date:

Aim:To implement Python program for sorting a lit using insertion sort.

Algorithm:

Step1.Start

Step2.Read the list to be sorted , l

Step3. for i in range of length of elements in list l

Step 3.1.Assign position, pos=i

Step 3.2.Repeat steps3.2.1 and 3.2.1 until l[pos ] < l[pos-1] and pos > 0

Step 3.2.1. Swap values between l [pos] and l [pos-1]

Step 3.2.2. Assign new position pos = pos-1

Step4.Print sorted list l

Step5.Stop
Flowchart:
Start

Read the list to be sorted, l

F
for i in of length
of elements in list
A

pos=i

F
While l[pos ] <
l[pos-1] and pos > 0

l[pos],l[pos-1]=l[pos-1],l[pos]

pos=i

Print sorted list l

Stop
Program:

def insertion_sort ( l):

for i in range(1,len(l)):

pos=i

while ( l[pos] < l[pos-1] and pos>0 ):

l[pos] , l[pos-1]=l[pos-1] , l[pos]

pos=pos - 1

print (‘Sorted list :’, l)

list=eval(input(‘Enter list to be sorted:’))

insertion_sort(list)

Output:

Enter list to be sorted:[3,77,3,2,11]


Sorted List: [1,2,3,11,77]

Result: Thus Python program to sort a list using insertion sort is implemented.
Ex. No.27. Merge Sort
Date:

Aim: To implement a python program for sorting a list using Merge sort.

Algorithm:

Step1. Input the list

Step2. call the function divide(list)

2.1. if len(x)==1 return x

2.2. if step 2.1 fails

2.2.1. find mid by len(x)//2

2.2.2. call function divide(x[:mid])

2.2.3. call function divide(x[mid:]

2.2.4. return(merge(a,b))

Step5. function merge(a,b)

5.1. create an empty list c

5.2. while len(a) and len(b) not equal to zero

5.2.1. if (a[0]<b[0])

5.2.1.1. Append a to list c

5.2.1.2. Remove a from list a

5.2.2. if (a[0]>b[0])

5.2.2.1. Append b to list c

Step5.2.2.2. Remove b from list b

5.2.3.if(len(a)!=0,Add list a and c

5.2.4.else Add list b to c

5.3: Return c
Flowchart

Start

Input list x

def divide(x)

No
If
(len(x)==1

Yes

Return x

mid=len(x)//2

a=divide(x[:mid])
b=divide(x[mid:])

return(merge(a,b))

def merge(a,b)

Create an empty list c

B
A
A
B
No
while (len(a)!=0 and
len(b)!=0)

Yes
No
if (a[0]<b[0]):

Yes

c.append(a[0]) c.append(b[0])
a.remove(a[0]) a.remove(b[0])

if (len(a)!=0):

Yes No
c=c+a c=c+b

Return(c)
Program:

def divide(x):
if(len(x)==1):
return(x)
else:
mid=len(x)//2
a=divide(x[:mid])
b=divide(x[mid:])
return(merge(a,b))
def merge(a,b):
c=[]
while (len(a)!=0 and len(b)!=0):
if (a[0]<b[0]):
c.append(a[0])
a.remove(a[0])
else:
c.append(b[0])
b.remove(b[0])
if (len(a)!=0):
c=c+a
else:
c=c+b
return(c)
print(divide([5,3,7,1]))

Output:

[1,3,5,7]

Result: Thus Python program is implemented for sorting a list using Merge sort.
Exp. No 28. Graph
Date:

Aim: To write a python program to create a Line graph, Histogram

Algorithm:

Step 1 Define the x-axis and corresponding y-axis values as lists.


Step 2 Plot them on canvas using .plot() function.
Step 3 Give a name to x-axis and y-axis using .xlabel() and .ylabel() functions.
Step 4 Give a title to your plot using .title() function.
Step 5 Finally, to view the plot  show() function is used

Program :

LINE GRAPH
import matplotlib.pyplot as plt
x = [1,2,3]
y = [2,4,1]
plt.plot(x, y)
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('My first graph!')
plt.show()

Output :
Step 1 Frequencies are passed as the ages list to plt.hist() function to plot a histogram.
Step 2 Range could be set by defining a tuple containing min and max value.
Step 3 To divide the entire range of values into a series of intervals is to “bin” the range
of values
Step 4 Finally, to view the plot  show() function is used

HISTOGRAM
import matplotlib.pyplot as plt
ages = [2,5,70,40,30,45,50,45,43,40,44,60,7,13,57,18,90,77,32,21,20,40]
range = (0, 100)
bins = 10  
plt.hist(ages, bins, range, color = 'green',histtype = 'bar', rwidth = 0.8)
plt.xlabel('age')
plt.ylabel('No. of people')
plt.title('My histogram')
plt.show()

Output :

Result: Thus Python program to create Line graph and Histogram are implemented successfully.
Exp. No 29. Python Program That Takes Command Line Argument
(Word Count)
Date:

Aim: To write a python program that takes command line argument (word count)

Algorithm:

Step 1 Start
Step 2 Open python IDLE and open the script mode
Step 3 Import Sys package using import command
Step 4 Assign sys.argv[1], which contains the filename, to filename variable ‘filename’
Step 5 Open the filename object ‘f’
a. Read the contents of file and store them in a string variable
Step 6 Using list comprehension in python, create a list containing words and their count as
pairs
Step 7 Print the word and word count
Step 8 Stop

To Run the Program in Command Prompt

Step 1 Open command prompt in windows


Step 2 Change directory to the python home path
Step 3 Type the command given below
a.C:\python35>python filename.py argument(filename)
Flow Chart:

Start

Open python IDLE and open


the script mode

Import Sys package using


import command

sys.argv[1] contains the filename from which the


word count is to be calculated
Assign sys.argv[1] to filename variable

Open the file name passed as command line argument Read


the contents of file and store them in a string variable

Using list comprehension in python, create a list


containing words and their count as pairs
Print the word and word count using iteration

Stop
Program:

import sys
filename = sys.argv[1]
f = open(filename)
wordcount ={}
passage = f.read()
for w in passage.split():
if word not in wordcount:
wordcount [w] = 1
else:
wordcount[w]+=1
print(wordcount)
f.close()

Output:

TextFile.txt
Python is a high level programming
language.

C:\Python35>python commandline.py TextFile.txt


Python 2
Is 1
a1
high 1
level 1
programming 1
language 1

Result: Thus Python program that takes command line argument (word count) is implemented
successfully.
Exp. No 30. Python Program to find the Most Frequent Word in a
Text: Read from a File
Date:

Aim: To write a python program to find the most frequent word in a text: read from a file

Algorithm:

Step 1.Start
Step 2 Open python IDLE and open the script mode
Step 3 Open the file name to read the text
a. Read the contents of file and store them in a string variable
Step 4 Using list comprehension in python, create a list containing words as keys and their count
as values as pairs
Step 5 Convert the list to dictionary
Step 6 Using the max() function find the most frequent (word and count) pair from dictionary
Step 7 Print the most frequent word
Step 8 Stop

Flow Chart

Start

Open the file name containing text

Read the contents of file and store them in a string variable

Get all the unique words from the file using list comprehension in python,
create a list containing words as keys and their count as values as pairs
Convert the list to dictionary

Using list comprehension in python, create a list containing words and


Program their count as pairs
Print the Word that Occurred Most in the file

Stop
f = open(‘TextFile’,’r’)
wordcount ={}
passage = f.read()
wordcount ={}

for w in passage.split():

if w not in wordcount:
wordcount [w] = 1
else:
wordcount[w]+=1
print(wordcount)
print("Max Count is")
lcount= wordcount.values()
m = max(lcount)
for i in wordcount:
if(m == wordcount[i]):
print(i," = is Present ",m," times")

Output

TextFile.txt

The Hello World is a sample program


that explains primitive concepts.
Python is a high level programming
language

is = is Present 2 times

Result:
Thus Python Program to find the Most Frequent Word in a Text: Read from a File has
been implemented successfully.

Exp. No 31. Python Program To Copy File


Date:

Aim:
To write a Python program to copy file

Algorithm:

Step 1 Start
Step 2 Open the file from which the contents needs to copied in read mode, let it be ‘in’ file
Step 3 Open the file on which the content to copied in write mode, let it be out file
Step 4 Read line by line from the file opened in read mode(from ‘in’ file)
Step 5 Using the write function, write line by line to the file opened in write mode(the ‘out’ file)
Step 6 Print the message “Successfully Completed” after the write function completion.
Step 7 Stop

Flowchart:
Start

Open the file from which the contents needs to


copied in read mode, let it be ‘in’ file

Open the file on which the content to copied in


write mode, let it be out file

Read line by line from the file opened in read


mode(from ‘in’ file)

Using the write function, write line by line to the


file opened in write mode(the ‘out’ file)

Using the write function, write line by line to the


file opened in write mode(the ‘out’ file)

Program:
Stop
a = open("TextFile.txt",”r+”)
b = open("out.txt", "w")
for line in a:
b.write(line)
a.close()
b.close()
print(“Successfully Copied a.txt to b.txt file”)

Output:
TextFile.txt Out.txt

The Hello World is a sample program The Hello World is a sample program
that explains primitive concepts. that explains primitive concepts.
Python is a high level programming Python is a high level programming
language language

Successfully Copied a.txt to b.txt file

Result:
Thus Python program to copy file has been implemented successfully.

Exp. No 32. Python Program to handle Exceptions


Date:

Aim: To write a python program to handle exceptions.

Program :

try:
print(x) # NameError
except NameError:
print("Variable x is not defined")

try:
a = [1, 2, 3]
print ("Fourth element =" ,a[3]) #IndexError
except IndexError:
print("Throws error since there are only 3 elements in array")

try:
geek = "Python ver"
num = 10
print(geek + num + geek)
except:
print("String type cannot be concatenated with Integer")

try:
b=c=3.0
d = ((b+c) / (b-c)) #ZeroDivisionError
except ZeroDivisionError:
print ("b/c result in 0")

Output :

Variable x is not defined


Throws error since there are only 3 elements in array
String type cannot be concatenated with Integer
b/c result in 0

Result: Thus Python program to handle exceptions has been implemented successfully.

Exp. No 33. Simulate Elliptical Orbit in PyGame


Date:

Aim: To write a python program simulate elliptical orbit in pygame

Algorithm:

Step 1 Open the Python 3.1 shell


Step 2 Open a new window and save as orbit.py file
Step 3 Write a program to access numpy and matplotlib package and
Step 4 Use the coordinates to plot the elliptical orbit
Step 5 Print the result
Step 6 Exit

Program:
from numpy import linalg
from numpy import linspace
import numpy as np
from numpy import meshgrid
import random
import matplotlib.pyplot as plt
from scipy import optimize
from sympy import *
xs = [1.02, 0.95, 0.87, 0.77, 0.67, 0.56, 0.44, 0.30, 0.16, 0.01]
ys = [0.39, 0.32, 0.27, 0.22, 0.18, 0.15, 0.13, 0.12, 0.12, 0.15]
b = [i ** 2 for i in xs]
def fxn(x, y): # That is the function that solves the given equation to find each parameter.
my_list = [] #It is the main list.
for z in range(len(x)):
w = [0] * 5
w[0] = y[z] ** 2
w[1] = x[z] * y[z]
w[2] = x[z]
w[3] = y[z]
w[4] = 1
my_list.append(w)
return my_list
t = linalg.lstsq(fxn(xs, ys), b)
def ysolv(coeffs):
x,y,a,b,c,d,e = symbols('x y a b c d e')
ellipse = a*y**2 + b*x*y + c*x + d*y + e - x**2
y_sols = solve(ellipse, y)
print(*y_sols, sep='\n')
num_coefs = [(a, f) for a, f in (zip([a,b,c,d,e], coeffs))]
y_solsf0 = y_sols[0].subs(num_coefs)
y_solsf1 = y_sols[1].subs(num_coefs)
f0 = lambdify([x], y_solsf0)
f1 = lambdify([x], y_solsf1)
return f0, f1
f0, f1 = ysolv(t[0])
y0 = [f0(x) for x in xs]
y1 = [f1(x) for x in xs]
plt.scatter(xs, ys)
plt.scatter(xs, y0, s=100, color = 'red', marker='+')
plt.scatter(xs, y1, s=100, color = 'green', marker='+')
plt.show()

Output:

Result: Thus Python program to Simulate elliptical orbits in Pygame has been implemented
successfully.

Exp. No 34. Simulate bouncing ball using Pygame


Date:

Aim: To write a python program to simulate bouncing ball using Pygame

Algorithm:

Step 1. Open the Python 3.1 shell


Step 2. Open a new window and save as orbit.py file
Step 3. Write a program to access numpy and matplotlib package and
Step 4. Use the coordinates to create a ball bouncing game
Step 5. Execute the program
Step 6. Stop

Program :
import pygame
pygame.init()

window_w = 800
window_h = 600
white = (255, 255, 255)
black = (0, 0, 0)
FPS = 120
window = pygame.display.set_mode((window_w, window_h))
pygame.display.set_caption("Bouncing Ball 2D ")
clock = pygame.time.Clock()
def game_loop():
block_size = 20
velocity = [1, 1]
pos_x = window_w/2
pos_y = window_h/2
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pos_x += velocity[0]
pos_y += velocity[1]
if pos_x + block_size > window_w or pos_x < 0:
velocity[0] = -velocity[0]

if pos_y + block_size > window_h or pos_y < 0:


velocity[1] = -velocity[1]
# DRAW
window.fill(white)
pygame.draw.rect(window, black, [pos_x, pos_y, block_size, block_size])
pygame.display.update()
clock.tick(FPS)
game_loop()

Output:

Result: Thus Python program to simulate bouncing ball using pygame is implemented
successfully.
Exp. No. 35.GUI based python programs with Tkinter
Packages
Date:

Aim: To write a python program to perform GUI based python program using Tkinter package.

Algorithm:

Step 1. Open the Python 3.1 shell


Step 2. Open a new window and save as TKINTEREX.py file
Step 3. Write a program to access TKINTER package
Step 4. Open a window with a button using the python code
Step 5. Execute the program
Step 6. Stop

Program:

from Tkinter import *


classApp:
def__init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
self.button.pack(side=LEFT)
self.hi_there = Button(frame, text="Hello", command=self.say_hi)
self.hi_there.pack(side=LEFT)
defsay_hi(self):
print"hi there, everyone!"
root = Tk()
app = App(root)
root.mainloop()
root.destroy() # optional; see description below
Output:

Result:
Thus GUI based Python program using Tkinter package is implemented successfully.
Mini Project

ROCK,PAPER AND SCISSORS

Lakshya.D, Naveenaa.S and Nithyalakshmy.C.R

Ist Year F section

ABSTRACT:
Rock paper scissors game is also known as stone paper scissors. It is a
hand game that is usually played between 2 people, each player can randomly
form any one of three from their hand. A player who chooses rock will win by
another player who chooses scissors but loose by the player who chooses
paper; a player with paper will lose by the player with the scissors.
If both players choose the same then the game is tied. Rock paper scissors game
is mainly played among kids.

Rock-Paper-Scissors Game Python Project


The object of the rock-paper-scissor python project is to build a game for
a single player that plays with a computer, anywhere, and anytime. This project
is base on the rules that:
rock blunts scissors so rock wins
scissors cut the paper so scissors win
paper cover rock so paper wins
This project is build using random modules, and the basic concept of
python.
In this python project, players have to choose any one from rock, paper, and
scissors. Then click on the play button will show the result of the game.
PROGRAM:
import random
choices = ["Rock", "Paper", "Scissors"]
computer = random.choice(choices)
player = False
cpu_score = 0
player_score = 0
while True:
player = input("Rock, Paper or Scissors?").capitalize()
## Conditions of Rock,Paper and Scissors
if player == computer:
print("Tie!")
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
cpu_score+=1
else:
print("You win!", player, "smashes", computer)
player_score+=1
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
cpu_score+=1
else:
print("You win!", player, "covers", computer)
player_score+=1
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
cpu_score+=1
else:
print("You win!", player, "cut", computer)
player_score+=1
elif player=='End':
print("Final Scores:")
print(f"CPU:{cpu_score}")
print(f"Plaer:{player_score}")
break

OUTPUT CONCLUSION
Our research evaluated the behavior of human players against other human
opponents as well as computer probabilistic opponents in the RPS game. We
found that, regardless of playing with another human or an algorithm,
participants did not play the optimal strategy. In general, we did not observe a
conclusive win-stay/lose-change strategy for players, but, when humans played
with an algorithm, we observed that the win-stay strategy was common against
the WDLS computer strategy, and lose-change was also common against the
WSLU computer strategy. This suggests that participants are capable of learning
simple strategies when these can result in a clear advantage against their
opponent.

You might also like