problem solveing laboratory
problem solveing laboratory
LIST OF EXPERIMENTS:
1. Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for the same.
(Electricity Billing, Retail shop billing, Sin series, weight of a motorbike, Weight of a steel bar,
compute Electrical Current in Three Phase AC Circuit, etc.)
2. Python programming using simple statements and expressions (exchange the values of two
variables, circulate the values of n variables, distance between two points).
3. Scientific problems using Conditionals and Iterative loops. (Number series, Number Patterns,
pyramid pattern)
6. Implementing programs using Functions. (Factorial, largest number in a list, area of shape)
9. Implementing real-time/technical applications using File handling. (copy from one file
to another, word count, longest word)
10. Implementing real-time/technical applications using Exception handling. (divide by zero
error, voter’s age validity, student mark range validation)
11. Exploring Pygame tool.
12. Developing a game activity using Pygame like bouncing ball, car race etc.
1. Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for the same.
(Electricity Billing, Retail shop billing, Sin series, weight of a motorbike, Weight of a steel bar,
compute Electrical Current in Three Phase AC Circuit, etc.)
Write a program to calculate the electricity bill, we must understand electricity charges and rates.
/*
1 - 100 unit - 1.5/=
101-200 unit - 2.5/=
201-300 unit - 4/=
300 - 350 unit - 5/=
above 300 - fixed charge 1500/=
for example
*/
Declare total unit consumed by the customer using the variable unit.
If the unit consumed less or equal to 100 units, calculates the total amount of consumed
=units*1.5
If the unit consumed between 100 to 200 units, calculates the total amount of
consumed=(100*1.5)+(unit-100)*2.5)
If unit consumed between 200 to 300 units ,calculates total amount
ofconsumed=(100*1.5)+(200-100)*2.5+(units-200)*4
If unit consumed between 300-350 units ,calculates total amount of
consumed=(100*1.5)+(200-100)*2.5+(300-200)*4+(units-350)*5
If the unit consumed above 350 units, fixed charge – 1500/=
additional charges
if units<=100 – 25.00
Program 2
# driver nodes
# Enter value in degree in x
x = 10
Weight of a Bike
The horizontal position of a motorcycle’s CG can be easily found by using two scales and
finding how much of the motorcycle’s weight is on each wheel.
Wf=front weight
Wr=rear weight
WB=wheelbase
X =Wr*WB/ Wf+Wr
2. Python programming using simple statements and expressions (exchange the values of two
variables, circulate the values of n variables, distance between two points).
x = 10
y = 50
print("Value of x:", x)
print("Value of y:", y)
lst=[1,2,3,4,5]
d=deque(lst)
print d
d.rotate(2)
print d
Output:[3,4,5,1,2]
(OR)
list=[10,20,30,40,50]
list[n:]+list[:n]
Output: [30,40,50,10,20]
import math
p1 = [4, 0]
p2 = [6, 6]
print(distance)
3. Scientific problems using Conditionals and Iterative loops. (Number series, Number
Patterns,pyramid pattern)
NUMBER SERIES
print()
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Output
print("\nSum is : ",sum)
Output :
12+22+32+42+52+62+72+82+92+102
Sum is : 570
import math
# printing stars
print()
Output:
*
**
***
****
*****
# This is the example of print simple reversed right angle pyramid pattern
print(end=" ")
print("")
Output:
*
**
***
****
*****
Code -
print(" ")
Output:
Code -
m = (2 * n) - 2
print(end=" ")
print(" ")
Output:
Code -
k = 2 * rows - 2
print(end=" ")
k=k+1
print("")
Output:
***********
**********
*********
********
*******
******
*****
****
***
**
*
Code -
k = 2 * rows - 2
print(end=" ")
k=k-1
print("")
# Downward triangle Pyramid
k = rows - 2
print(end=" ")
k=k+1
print("")
Output:
Code -
print(" ")
print(" ")
Output:
Code -
k = rows - 2
print(end=" ")
k=k+1
print()
k = 2 * rows - 2
print(end="")
k=k-1
for j in range(0, i + 1):
print()
Output:
Code -
for i in range(rows+1):
for j in range(i):
print(" ")
Output:
Explanation -
In the above code, we have printed the numbers according to rows value. The first row prints a
single number. Next, two numbers, prints in the second row, and the next three number prints on
the third row and so on. In the
Code -
print("")
Output:
Code -
k=0
k += 1
print()
Output:
Explanation:
In the above code, we have used the reversed loop to print the downward inverted pyramid where
number reduced after each iteration.
Code -
n = rows
print()
Output:
Code -
Output:
Code -
current_Number = 1
stop = 2
for i in range(rows):
current_Number += 1
print("")
stop += 2
Output:
1
234
56789
print()
Output:
Code -
i=1
j=1
while j <= i:
j=j+1
i=i+1
print()
Output:
Code -
if j <= i:
else:
print()
Output:
print()
Output:
Code -
alphabate = chr(asciiValue)
print(alphabate, end=' ')
asciiValue += 1
print()
Output:
Explanation -
In the above code, we have assigned the integer value 65 to asciiValue variable which is an
ASCII value of A. We defined for loop to print five rows. In the inner loop body, we converted
the ASCII value into the character using the char() function. It will print the alphabets, increased
the asciiValue after each iteration.
Code -
alphabate = chr(asciiValue)
else:
Output:
Code -
str1 = "JavaTpoint"
x = ""
for i in str1:
x += i
print(x)
Output:
J
Ja
Jav
Java
JavaT
JavaTp
JavaTpo
JavaTpoi
JavaTpoin
JavaTpoint
Code -
s=5
asciiValue = 65
m = (2 * s) - 2
print(end=" ")
m=m-1
alphabate = chr(asciiValue)
asciiValue += 1
print()
Output:
my_set = set(my_list)
my_new_list = list(my_set)
Original List : [10, 20, 30, 40, 20, 50, 60, 40]
List of unique numbers : [40, 10, 50, 20, 60, 30]
Answer:
Answer:
d = dict()
for x in range(1,n+1):
d[x]=x*x
print(d)
Input a number 5
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Write a Python program to find maximum and the minimum value in a set.
Answer:
#Create a set
print(max(seta))
print(min(seta))
Output
20
Exercise 4:
myList =["books","periodicals",'newspapers','manuscripts','CDs','DVDs','e-
books','student_databases']
#append
myList.append(4)
myList.append(5)
myList.append(6)
myList.append(i)
print(myList)
#extend
myList.extend([4, 5, 6])
myList.append(i)
print(myList)
#insert
myList.insert(3, 4)
myList.insert(4, 5)
myList.insert(5, 6)
print(myList)
#remove
myList.remove('manuscripts')
myList.insert(4, 'CDs')
myList.insert(5, 'DVDs')
myList.insert(6, 'e-books')
print(myList)
#pop
myList.pop(4)
myList.insert(4, 'CDs')
myList.insert(5, 'DVDs')
myList.insert(6, 'e-books')
print(myList)
#slice operations
#reverse
print(myList)
#length
print(len(myList))
print(min([1, 2, 3]))
print(max([1, 2, 3]))
#count
print(myList.count(3))
#concatenation
print(myList+yourList)
#repetition
print(myList*2)
#sort
yourList = [4, 2, 6, 5, 0, 1]
yourList.sort()
print(yourList)
#myList.sort()
#print(myList)
T1=(10,50,30,40,20)
T2=('clutch','gearbox','propellershaft','axles','Chassis','Engine','TransmissionSystem','Body')
print (len(T1))
L1=(110,150,130,140,120)
T1=tuple(L1)
print (T1)
s1=('clutch','gearbox','propellershaft','axles','Chassis','Engine','TransmissionSystem','Body')
T2=tuple(s1)
#positive indices
print(T1[2:4])
#negative indexing
print(T1[:-2])
#sorted funtion
sorted(T1)
#len() function
print (len(T1))
#index()
print(T2.index('Chassis'))
#count()
print(T2.count(2))
#Membership operator
print('a' in tuple("string"))
#Concatenation
print( (1,2,3)+(4,5,6))
#Logical
print((1,2,3)>(4,5,6))
# Identity
a=(1,2)
print((1,2) is a)
#Addition
print (t);
#SLICING
print(t[2:4])
#MULTIPLICATION
print (t*3);
#DELETING
del (T1);
TComponents=('Bamboo','Wood','Bricks','Cementblocks','Buildingstone','GravelSand','Cementco
ncrete','Reinforcedconcrete')
LWeight=[300,500,1500,950,2000,1900,2300,2700]
#len() function
print (len(TComponents))
#index()
print(TComponents.index('Bricks'))
#count()
print(TComponents.count('Cementconcrete'))
Components of an automobile
6. Implementing programs using Functions. (Factorial, largest number in a list, area of shape)
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(n))
def large(arr):
maximum = arr[0]
maximum= ele
return maximum
list1 = []
for i in range(0,n):
list1.append(n1)
for i in range(0,n):
print(list1[i])
result = large(list1)
print("largest number",result)
AREA OF SHAPE
def square(l):
area=l*l
return area
def rectangle(l,w):
area=l*w
return area
print("Square = 1")
print("Rectangle = 2")
if (i==1):
if (i==2):
R=rectangle(length, width)
REVERSE A STRING
def reversed_string(text):
if len(text) == 1:
return text
print(reversed_string("Python Programming!"))
PALINDROME
def isPalindrome(s):
return s == s[::-1]
if ans:
else:
CHARACTER COUNT
def count_chars(txt):
result = 0
return result
REPLACING CHARACTERS
print(string.replace("p", "P",1))
print(string.replace("p", "P"))
PANDAS
import pandas as pd
df = pd.read_csv('Data.csv')
print(df.to_string())
NUMPY
import numpy
arr = numpy.array([4, 5,7,8])
print(arr)
Matplotlib
plt.plot(xpoints, ypoints)
plt.show()
scipy
from scipy import constants
print(constants.liter)
import numpy as np
from scipy.sparse import csr_matrix
print(csr_matrix(arr))
9. Implementing real-time/technical applications using File handling. (copy from one file
to another, word count, longest word)
with open("test.txt") as f:
for line in f:
f1.write(line)
print("copied to out file :",line)
Word count
with open("test.txt") as f:
for line in f:
wordcount = len(line.split())
# total no of words
Longest word
def longest_word(filename):
words = infile.read().split()
return word
if len(word) == max_len :
print(longest_word('test.txt'))
Output
Enter a=4
Enter b=4
a/b result in 0
try:
c=a
#Raising Error
if c<18:
raise ValueError
#Handling of error
except ValueError:
else:
print (c)
Student mark range validation
a=int(input("Enter any marks"))
try:
c=a
#Raising Error
raise ValueError
#Handling of error
except ValueError:
else:
print (c)
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
1. Installing through pip: The good way to install Pygame is with the pip tool (which is what
python uses to install packages). The command is the following:
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 the above command in the terminal or use the following steps:
import pygame
pygame.init()
screen = pygame.display.set_mode((400,500))
done = False
12. Developing a game activity using Pygame like bouncing ball, car race etc.
pygame.init()
speed = [1, 1]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball.png")
ballrect = ball.get_rect()
while 1:
if event.type == pygame.QUIT:
sys.exit()
ballrect = ballrect.move(speed)
speed[0] = -speed[0]
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
OUTPUT
RESULT:
Thus the program to simulate bouncing ball using pygameis executed and the output is
obtained.
PROGRAM/SOURCE CODE :
import random
import pygame
class CarRacing:
def __init__(self):
pygame.init()
self.display_width = 800
self.display_height = 600
self.black = (0, 0, 0)
self.clock = pygame.time.Clock()
self.gameDisplay = None
self.initialize()
def initialize(self):
self.crashed = False
self.carImg = pygame.image.load('.\\img\\car.png')
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
self.count = 0
def racing_window(self):
pygame.display.set_caption('Car Dodge')
self.run_car()
def run_car(self):
if event.type == pygame.QUIT:
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
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
self.car(self.car_x_coordinate, self.car_y_coordinate)
self.highscore(self.count)
self.count += 1
self.enemy_car_speed += 1
self.bg_speed += 1
self.crashed = True
self.crashed = True
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
self.bg_y2 += self.bg_speed
self.bg_y1 = -600
if self.bg_y2 >= self.display_height:
self.bg_y2 = -600
def display_credit(self):
if __name__ == '__main__':
car_racing = CarRacing()
car_racing.racing_window()
OUTPUT