GE3171 Problem Solving and Python Programming Lab Manual Shanen
GE3171 Problem Solving and Python Programming Lab Manual Shanen
net
elif(units<=200) then
payAmount=(100*1.5)+(units*100)*2.5
fixedcharge=50.00
ww elif(units<=350) then
payAmount=(100*1.5)=(200-100)*2.5+(300-200)*4=(units-300)*5
fixedcharge=100.00
w else
payAmount=0
.Ea
fixedcharge=1500.00
step4 : calculate total=payAmount+fixedcharge
syE
Step 5: print the electricity bill
Step 6: stop
PROGRAM
ngi
units=int(input("please enter the number of units you consumed in a month"))
if(units<=100):
payAmount=units*1.5
fixedcharge=25.00 nee
elif(units<=200):
payAmount=(100*1.5)+(units-100)*2.5
fixedcharge=50.00 rin
elif(units<=300):
payAmount=(100*1.5)+(200-100)*2.5+(units-200)*4 g.n
fixedcharge=75.00
elif(units<=350):
payAmount=(100*1.5)+(200-100)*2.5+(300-200)*4+(units-300)*5
fixedcharge=100.00
et
else:
payAmount=0
fixedcharge=1500.00
Total=payAmount+fixedcharge
print("\nElecticity bill",Total)
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
please enter the number of units you consumed in a month300
Electicity bill 875.0
wwbill_amount=0
i=0
w
total=0
leng=len(reqd_items) .Ea
syE
check = all(item in items_list for item in reqd_items)
if check is True:
while(i<leng):
ngi
inty=items_list.index(reqd_items[i])
total=total+ price_list[inty]*reqd_quantity[i] nee
bill_amount=total
rin
else:
i=i+1
g.n
bill_amount=total
return bill_amount
et
items_list=["rice","oil","sugar","soap","paste"]
price_list=[50,200,40,30,35]
reqd_items=["rice","oil"]
reqd_quantity=[5,2]
bill_amount=calculate_bill_amount(items_list, price_list, reqd_items, reqd_quantity)
print(“Total bill amount:”, bill_amount)
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
Total bill amount: 650
1.C.SINE SERIES
AIM:
To write a python program to calculate Sine series
sin x = x - x3/3! + x5/5! - x7/7! + x9/9! ........
ALGORITHM:
Step 1: start
Step 2: read the value of x and n
Step 3: calculate the sum of sine series
Sign=-1
Fact=i=1
Sum=0
Step 4: check while i<=n then
P=1
Fact=1
For j in range (1,I +1)then
P=p*x
fact=fact*j
sign=-1*sign
w Step 7:stop
PROGRAM:
.Ea
x = int(input("Enter the value of x: "))
n = int(input("Enter the value of n: "))
sign = -1
fact = i =1
sum = 0 syE
while i<=n:
p=1
fact = 1 ngi
for j in range(1,i+1):
p = p*x nee
fact = fact*j
sign = -1*sign
sum = sum + sign* p/fact rin
i = i+2
print("sin(",x,") =",sum) g.n
RESULT:
Thus the Program was executed successfully and the output was verified.
et
OUTPUT:
Enter the value of x: 5
Enter the value of n: 4
sin( 5 ) = -15.833333333333332
PROGRAM:
Wf=10#front weight
Wr=40# rear weight
WB=50#wheelbase
X =Wr*WB/ Wf+Wr
print("Weight of bike",X)
ww
RESULT:
Thus the Program was executed successfully and the output was verified.
w
OUTPUT:
PROGRAM:
D=10
L=100
W=(D**2)*L)/162
ww
RESULT:
Thus the Program was executed successfully and the output was verified.
w
OUTPUT:
.Ea
Weight of steel bar 61.72839506172839
syE
ngi
nee
rin
g.n
et
AIM:
To write a python program to calculate Sine series
ALGORITHM:
Step 1: start
Step 2: read the value of R , X_L ,V_L ,f
Step 3: calculate the line current
V_Ph =V_L/sqrt(3)
Z_Ph =sqrt((R**2)+(X_L**2))
I_Ph =V_Ph/Z_Ph
I_L = I_Ph
Step 4: print the line current in A is , round(I_L ,2)
Step 5: calculate the power factor
Pf = cos (phi) = R_Ph/Z_Ph
R_Ph=R
Phi= a cos(R_Ph/Z_Ph)
Step 6: print the power factor is : Pf ‘degree lag.
ww
Step 7: calculate the power supplied
P=sqrt(3)*V_L*I_L*cos(phi)
Step 8: print the power supplied in W is;P
w
Step 9: stop
PROGRAM:
.Ea
from math import cos,acos,sqrt
R = 20.;# in ohm
X_L = 15.;# in ohm
V_L = 400.;# in V syE
f = 50.;# in Hz
#calculations
V_Ph = V_L/sqrt(3);# in V ngi
Z_Ph = sqrt( (R**2) + (X_L**2) );# in ohm
I_Ph = V_Ph/Z_Ph;# in A nee
I_L = I_Ph;# in A
print ("The line current in A is",round(I_L,2))
# pf = cos(phi) = R_Ph/Z_Ph; rin
R_Ph = R;# in ohm
phi= acos(R_Ph/Z_Ph); g.n
# Power factor
pf= cos(phi);# in radians
print ("The power factor is : ",pf,"degrees lag.")
P = sqrt(3)*V_L*I_L*cos(phi);# in W
et
print ("The power supplied in W is",P)
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
ALGORITHM:
Step1: start
Step2: read upper limit ‘var’
Step3: read ‘var’ elements using loop and store them in list
Step4: pop out each element from list and append to list
Step5: print list
Step6: stop
PROGRAM:
Var=int(input(‘enter number of values’))
List1=[]
For val in range (0, var, 1):
ele=int(input(“Enter the element”))
list1 . append(ele)
print (“circulating the elements of list”,list1)
ww
for val in range (0, var,1)
ele = list1.pop(0)
list1.append(ele)
w
RESULT:
print(list1)
.Ea
To write a Python program to circulate values of ‘n’ variables in the list.
OUTPUT:
enter number of values 4
syE
enter the element12
enter the element43 ngi
enter the element11
enter the element56
circulating the elements of list [12, 43, 11, 56] nee
[43, 11, 56, 12]
[11, 56, 12, 43]
rin
[56, 12, 43, 11]
[12, 43, 11, 56]
g.n
et
ALGORITHM:
Step 1: Start
Step 2: Initialize the function of swap
Step 3: Declare the variables a and b read input
Step 4: Call the function swap a,b
Step 5: The function swap perform the following operation
temp=a
a=b
b=temp
step 6:Print swap number a and b
step 7:Stop
PROGRAM:
ww
def swap(a,b):
temp=a
a=b
w b=temp
.Ea
print(“the value of x after swapping:”,a)
print(“the value of y after swapping:”,b)
return
x=int(input(“Enter value of x:”))
y=int(input(“Enter value of y:"))
swap(x,y)
syE
RESULT: ngi
nee
Thus the Program was executed successfully and the output was verified.
OUTPUT:
rin
Enter value of x:6
Enter value of y:8
the value of x after swapping: 8 g.n
the value of y after swapping: 6
et
ww
import math
w
def distance (x1,y1,x2,y2):
.Ea
d=math.sqrt(((x2-x1)**2)+((y2-y1)**2))
return d
syE
a= int(input('Enter the value of x1'))
b= int(input('Enter the value of x2'))
c= int(input('Enter the value of x1'))
ngi
d= int(input('Enter the value of x2'))
nee
print( 'The distance between the two points is', distance(a,b,c,d))
RESULT:
Thus the Program was executed successfully and the output was verified. rin
OUTPUT: g.n
Enter the value of x13
Enter the value of x24
Enter the value of x15
Enter the value of x22
et
The distance between the two points is 2.8284271247461903
AIM:
ALGORITHM:
Step 2: Take the input from the user by using python input () function.
Step 4: Increment for loop iteration value by 1, as well as print iteration value.
PROGRAM
ww
n = int(input("Please Enter any Number: "))
w
for i in range(1, n + 1):
nee
OUTPUT:
Please Enter any Number: 10
The List of Natural Numbers from 1 to 10
rin
g.n
1 2 3 4 5 6 7 8 9 10
et
ALGORITHM:
PROGRAM
num = 5
for n in range(1, num):
3.C.PYRAMID PATTERN
AIM:
ALGORITHM:
PROGRAM
num = 5
for n in range(0, num):
ww
newlist=list.append(newbook)
print(list)
newlist=['C++ programming','C Programming']
w
print('Concatenation of 2 lists')
.Ea
print('Concatenated list: ',(list+newlist))
print('Repetition of an item in list')
print(3*'python programming')
list.remove('python programming')
print("Available books")
syE
print("Removing an item from list")
print(list)
RESULT: ngi
OUTPUT:
operations of list nee
Thus the python program was executed and verified successfully.
print('operations of tuple1')
tuple1=('bricks','cement','steel')
print('Displaying the items in tuple1')
print('Materials required for construction of building:')
print(tuple1)
newtuple1=('sand','wood')
ww
print('Concatenation of 2 tuples')
print('Concatenated tuple1: ',(tuple1+newtuple1))
print('Repetition of an item in tuple1')
w
print(3*'steel')
.Ea
print('Searching the materials for construction of building')
if 'C' in tuple1:
print('present')
else:
print('not present') syE
RESULT: ngi
Thus the python program was executed and verified successfully.
OUTPUT:
operations of tuple1 nee
Displaying the items in tuple1
Materials required for construction of building:
rin
('bricks', 'cement', 'steel')
Concatenation of 2 tuples
Concatenated tuple1: ('bricks', 'cement', 'steel', 'sand', 'wood') g.n
Repetition of an item in tuple1
steelsteelsteel
Searching the materials for construction of building
not present
et
AIM:
ALGORITHM:
Step 2: Creating a Set with the use of a List and print the result.
Step 3: Addition of Languages to the Set using Update operation and print the result.
Step 4: Removing languages from Set using Remove operation and print the result.
Step5: Find the Language present or not in Set using membership operation and print the result.
ww
Step6: Apply Union operation on Set using “|” operator and print the result.
Step7: Apply Intersection operation on set using “&” operator and print the result.
w .Ea
Step 8: Stop the program.
PROGRAM
syE
set1 = set(["python", "C", "C++","java"])
print("\n Programming languages ")
print(set1) ngi
set1.update(["PHP","SQL","VISUAL BASIC"])
nee
print("\nSet after Addition of Languages using Update: ")
print(set1) rin
set1.remove("C")
g.n
set1.remove("PHP")
print("\nSet after Removal of two Languages: ")
print(set1)
et
if "C" in set1:
print("present")
else:
print("not present")
set2=set(["Java script","R"])
set3 = set1|set2
print("\nUnion using '|' operator")
print(set3)
set4 = set1 & set3
print("\nIntersection using '&' operator")
print(set4)
RESULT:
Thus the Program was executed successfully and the output was verified.
OUTPUT:
Programming languages
{'C', 'python', 'java', 'C++'}
not present
ww
Union using '|' operator
{'python', 'R', 'java', 'SQL', 'Java script', 'VISUAL BASIC', 'C++'}
w
Intersection using '&' operator
.Ea
{'python', 'C++', 'java', 'SQL', 'VISUAL BASIC'}
syE
ngi
nee
rin
g.n
et
AIM:
ALGORITHM:
ww
Step6: Find the components present or not in Dictionary using membership operator and print the
result.
w
Step7: Apply Intersection operation on set using “&” operator and print the result.
OUTPUT:
Components of automobile
{1: 'Engine', 2: 'Gearbox', 3: 'lights'}
Updated Components:
{1: 'Engine', 2: 'Gearbox', 3: 'lights', 4: 'Battery'}
Accessing a Component using key:
Engine
ww
w .Ea
syE
ngi
nee
rin
g.n
et
ww
def factorial(num):
w
if num == 1:
else:
return num
.Ea
syE
return num * factorial(num - 1)
num = int(input("Enter the number: "))
if num < 0:
ngi
print("Invalid input")
elif num == 0: nee
print ("Factorial of 0 is 1")
rin
else:
print ("Factorial of %d is %d" %(num, factorial(num))) g.n
RESULT:
Thus the Program was executed successfully and the output was verified.
et
OUTPUT:
Enter the number: 5
Factorial of 5 is 120
ww
Step5:stop the program
PROGRAM:
w
def myMax(list1):
max = list1[0]
.Ea
for x in list1:
if x > max: syE
max = x
ngi
nee
return max
list1 = [10, 20, 4, 45, 99]
print("Largest element is:", myMax(list1))
RESULT: rin
Thus the Program was executed successfully and the output was verified.
g.n
OUTPUT:
Largest element is: 99 et
AIM:
ww Area = side*side
w return Area
.Ea
side = int(input('enter a the value of side'))
print(Areaofsquare(side))
RESULT:
syE
Thus the Program was executed successfully and the output was verified.
OUTPUT:
ngi
enter a the value of side8
64 nee
rin
g.n
et
AIM:
def reversed_string(text):
ww if len(text) == 1:
wreturn text
.Ea
return reversed_string(text[1:]) + text[:1]
syE
print(reversed_string("Python Programming!"))
RESULT:
ngi
Thus the Program was executed successfully and the output was verified.
OUTPUT:
nee
rin
!gnimmargorP nohtyP
g.n
et
7.B. PALINDROME
AIM:
ww
def isPalindrome(s):
w
return s == s[::-1]
.Ea
s = input("enter any string :")
ans = isPalindrome(s)
syE
if ans:
ngi
nee
print(s,"Yes it's a palindrome")
else:
OUTPUT:
et
enter any string :malayalam
AIM:
Program:
def count_chars(txt):
ww result = 0
.Ea
result += 1 # same as result = result + 1
return result
syE
text=input("enter any string")
ngi
nee
print("no.of characters in a string",count_chars(text))
RESULT:
Thus the Program was executed successfully and the output was verified.
rin
OUTPUT:
g.n
enter any string welcome
AIM:
Program:
ww
print(string.replace("a", "A",1))
print(string.replace("a", "A"))
w
RESULT:
.Ea
Thus the Program was executed successfully and the output was verified.
OUTPUT:
syE
python is A programming language is powerful
python is A progrAmming lAnguAge is powerful ngi
nee
rin
g.n
et
ALOGIRTM
Step1: Start the program
Step 2: import pandas as pd.
Step 3: creating a series as data.
Step 4: creating a series as data1
Step 5: print the series data and data1.
Step 6: Stop the program.
PROGRAM:
import pandas as pd
data = pd.Series([5, 2, 3,7], index=['a', 'b', 'c', 'd'])
data1 = pd.Series([1, 6, 4, 9], index=['a', 'b', 'd', 'e'])
print(data, "\n\n", data1)
RESULT:
ww
Thus the python program was executed and verified successfully.
OUTPUT:
a 5
b w2
.Ea
syE
c 3
d 7
dtype: int64
a 1 ngi
b
d
6
4
nee
e 9
rin
dtype: int64
g.n
et
ALOGIRTM
PROGRAM:
import numpy as np
ww
data = np.array([1,3,4,7])
print(data)
w
RESULT:
.Ea
Thus the python program was executed and verified successfully.
OUTPUT:
[1 3 4 7] syE
ngi
nee
rin
g.n
et
ALOGIRTM
ww
PROGRAM:
w
from matplotlib import pyplot as plt
x = [5, 2, 9, 4, 7]
y = [10, 5, 8, 4, 2] .Ea
plt.plot(x,y)
plt.show()
syE
RESULT:
ngi
nee
Thus the python program was executed and verified successfully.
rin
OUTPUT:
g.n
et
ALOGIRTM
PROGRAM:
ww
import numpy as np
A = np.array([[1,2,3],[4,2,6],[7,3,9]])
from scipy import linalg
w
linalg.det(A)
RESULT:
.Ea
syE
Thus the python program was executed and verified successfully.
OUTPUT:
6.0
ngi
nee
rin
g.n
et
ww
with open('first.txt','r') as firstfile, open('second.txt','a') as secondfile:
for line in firstfile:
w
RESULT:
secondfile.write(line)
.Ea
syE
Thus the python program was executed and verified successfully.
FILE CREATION:
ngi
nee
rin
g.n
et
OUTPUT:
9.B.WORD COUNT
AIM:
To find the word and lines in command line arguments.
ALGORITHM:
STEP 1: Start
STEP 2: Add arguments to find the words and lines
STEP 3: Add file name as argument
STEP 4: Parse the arguments to get the values
STEP 5: Format and print the words
STEP 6: Stop
PROGRAM:
fname = input("Enter file name: ")
ww num_words = 0
with open(fname, 'r') as f:
w for line in f:
.Ea
words = line.split()
num_words += len(words)
print("Number of words:") syE
RESULT:
print(num_words)
ngi
nee
Thus the python program was executed and verified successfully.
FILE CREATION:
rin
g.n
et
OUTPUT:
Enter file name: first.py
Number of words:
3
PROGRAM:
ww
fin = open("first.py","r")
str = fin.read()
words = str.split()
w
max_len = len(max(words, key=len))
for word in words:
.Ea
if len(word)==max_len:
longest_word =word
print(longest_word)
RESULT:
syE
ngi
Thus the python program was executed and verified successfully.
FILE CREATION:
nee
rin
g.n
et
OUTPUT:
welcome
AIM
To write a python program to implement exception handling using devide by zero error.
Algorithm
step 1: Start
Step 2: Enter the inputs a and b
Step 3: Calculate (a+b)/(a-b) in try block
Step 4: if a equal to b try block throws an exception.
Step 5: The exception is caught and handled.
Step 6: stop
Program
a=int(input("Entre a="))
ww
b=int(input("Entre b="))
try:
c = ((a+b) / (a-b))
w
#Raising Error
if a==b:
.Ea
raise ZeroDivisionError
#Handling of error
except ZeroDivisionError:
print ("a/b result in 0")
else: syE
print (c)
RESULT: ngi
nee
Thus the python program was executed and verified successfully.
OUTPUT:
Enter a=4 rin
Enter b=4
a/b result in 0 g.n
et
AIM
To write a python program to implement exception handling using voter’s age validity.
Algorithm
step 1: Start
Step 2: Enter the age
Step 3: Check whether the age is less than 18.
Step 4: If less than 18 throw an exception
Step 5: The exception is caught and handled.
Step 6: stop
Program:
ww
try:
w c=a
#Raising Error
.Ea
if c<18:
raise ValueError
syE
#Handling of error ngi
except ValueError:
nee
print ("not eligible for voting - enter above 18")
rin
else:
g.n
print (c)
RESULT:
et
Thus the python program was executed and verified successfully.
OUTPUT:
20
AIM
To write a python program to implement exception handling using Students mark range.
Algorithm
step 1: Start
Step 2: Enter the mark of student
Step 3: Check whether the mark is between 0 and 100
Step 4: if the range is not between 0 and 100 then throw an exception.
Step 5: The exception is caught and handled.
Step 6: stop
Program:
ww
a=int(input("Enter any marks"))
try:
w c=a
except ValueError:
nee
print ("not correct students mark range value btween 1-100") rin
else: g.n
print (c)
RESULT:
et
Thus the python program was executed and verified successfully.
OUTPUT:
90
Pygame
o Pygame is a cross-platform set of Python modules which is used to create video games.
o It consists of computer graphics and sound libraries designed to be used with the Python
programming language.
o Pygame was officially written by Pete Shinners to replace PySDL.
o Pygame is suitable to create client-side applications that can be potentially wrapped in a
standalone executable.
Pygame Installation
Install pygame in Windows
Before installing Pygame, Python should be installed in the system, and it is good to have 3.6.1 or
above version because it is much friendlier to beginners, and additionally runs faster. There are
mainly two ways to install Pygame, which are given below:
1. Installing through pip: The good way to install Pygame is with the pip tool (which is what python
ww
uses to install packages). The command is the following:
w
py -m pip install -U pygame --user
.Ea
2. Installing through an IDE: The second way is to install it through an IDE and here we are using
Pycharm IDE. Installation of pygame in the pycharm is straightforward. We can install it by running
o syE
the above command in the terminal or use the following steps:
PROGRAM/SOURCE CODE :
pygame.init()
speed = [1, 1]
screen = pygame.display.set_mode(size)
ww
pygame.display.set_caption("Bouncing ball")
w
ball = pygame.image.load("ball.png")
.Ea
ballrect = ball.get_rect()
while 1:
speed[1] = -speed[1]
et
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
OUTPUT
RESULT:
wwThus the program to simulate bouncing ball using pygameis executed and the output is
w
obtained.
.Ea
syE
ngi
nee
rin
g.n
et
PROGRAM/SOURCE CODE :
import random
import pygame
class CarRacing:
def __init__(self):
ww pygame.init()
wself.display_width = 800
.Ea
self.display_height = 600
self.black = (0, 0, 0)
syE
self.white = (255, 255, 255)
self.carImg = pygame.image.load('.\\img\\car.png')
et
self.car_x_coordinate = (self.display_width * 0.45)
self.car_width = 49
# enemy_car
self.enemy_car = pygame.image.load('.\\img\\enemy_car_1.png')
self.enemy_car_starty = -600
self.enemy_car_speed = 5
self.enemy_car_width = 49
self.enemy_car_height = 100
# Background
self.bgImg = pygame.image.load(".\\img\\back_ground.jpg")
self.bg_y1 = 0
self.bg_y2 = -600
self.bg_speed = 3
wwself.count = 0
w .Ea
def car(self, car_x_coordinate, car_y_coordinate):
syE
self.gameDisplay.blit(self.carImg, (car_x_coordinate, car_y_coordinate))
def racing_window(self):
ngi
self.gameDisplay = pygame.display.set_mode((self.display_width, self.display_height))
pygame.display.set_caption('Car Dodge')
nee
self.run_car()
rin
def run_car(self):
if event.type == pygame.QUIT:
et
self.crashed = True
# print(event)
if (event.type == pygame.KEYDOWN):
if (event.key == pygame.K_LEFT):
self.car_x_coordinate -= 50
if (event.key == pygame.K_RIGHT):
self.car_x_coordinate += 50
Download From: www.EasyEngineering.net
Download From: www.EasyEngineering.net
self.gameDisplay.fill(self.black)
self.back_ground_raod()
self.run_enemy_car(self.enemy_car_startx, self.enemy_car_starty)
self.enemy_car_starty += self.enemy_car_speed
self.enemy_car_starty = 0 - self.enemy_car_height
ww self.car(self.car_x_coordinate, self.car_y_coordinate)
self.highscore(self.count)
w .Ea
self.count += 1
syE
if (self.count % 100 == 0):
self.enemy_car_speed += 1
self.bg_speed += 1
ngi
nee
if self.car_y_coordinate < self.enemy_car_starty + self.enemy_car_height:
rin
if self.car_x_coordinate > self.enemy_car_startx and self.car_x_coordinate <
self.enemy_car_startx + self.enemy_car_width or self.car_x_coordinate + self.car_width >
g.n
self.enemy_car_startx and self.car_x_coordinate + self.car_width < self.enemy_car_startx +
self.enemy_car_width:
self.crashed = True
self.crashed = True
pygame.display.update()
self.clock.tick(60)
self.display_credit()
pygame.display.update()
self.clock.tick(60)
sleep(1)
car_racing.initialize()
car_racing.racing_window()
def back_ground_raod(self):
self.bg_y1 += self.bg_speed
w .Ea
self.bg_y2 += self.bg_speed
syE
if self.bg_y1 >= self.display_height:
self.bg_y1 = -600
rin
self.gameDisplay.blit(self.enemy_car, (thingx, thingy))
def display_credit(self):
if __name__ == '__main__':
Download From: www.EasyEngineering.net
Download From: www.EasyEngineering.net
car_racing = CarRacing()
car_racing.racing_window()
OUTPUT
ww
w .Ea
syE
ngi
RESULT: nee
Thus the python program was executed and verified successfully.
rin
g.n
et
ww
w.E
asy
E ngi
nee
rin
g.n
et