Technical Publications



[pic]

[pic]

Programming and Problem Solving Laboratory

Experiment 1 : To calculate salary of employee given his basic pay(take as input from user). Calculate gross salary of employee. Let HRA be 10% of basic pay and TA be 5% of the basic pay. Let employee pay professional tax as 2% of total salary. Calculate net salary payable after deductions.

Solution :

print("Enter basic salary: ")

basic=float(input())

HRA=(basic*10)/100

TA=(basic *5)/100

gross_salary=basic+HRA+TA

print("Gross Salary is: ",gross_salary)

PTax=(gross_salary*2)/100

net_salary=gross_salary-PTax

print("Net Salary is:",net_salary)

Output

Enter basic salary:

10000

Gross Salary is: 11500.0

Net Salary is: 11270.0

>>>

Experiment 2 : To accept an object mass in kilogram and velocity in meters per second and display its momentum. Momentum is calculated as e=mc2 where m is the mass of the object and c is its velocity.

Solution :

print("Enter mass of the object(kg)")

m=float(input())

print("Enter velocity of the object(m/s)")

c=float(input())

e=m*(c**2)

print("Momentum is: ",e)

Output

Enter mass of the object(kg)

10

Enter velocity of the object(m/s)

2.5

Momentum is: 62.5

>>>

Experiment 3 : To accept N numbers from user. Compute and display maximum in list, minimum in list, sum and average of numbers.

Solution :

mylist = [] # start an empty list

print("Enter the value of N: ")

N = int(input()) # read number of element in the list

for i in range(N):

print("Enter the element: ")

new_element = int(input()) # read next element

mylist.append(new_element) # add it to the list

print("The list is: ")

print(mylist)

print("The maximum element from list is: ")

max_element=mylist[0]

for i in range(N): #iterating throu list

if(mylist[i]>max_element):

max_element=mylist[i] #finding the maximum element

print(max_element)#printing the maximum element

print("The minimum element from list is: ")

min_element=mylist[0]

for i in range(N): #iterating throu list

if(mylist[i]>>

Experiment 4 : To accept student’s five courses marks and compute his/her result. Student is passing if he/she scores marks equal to and above 40 in each course. If student scores aggregate greater than 75%, then the grade is distinction. If aggregate is 60>= and = and = and >

Experiment 5 : To check whether input number is Armstrong number of not. An Armstrong number is an integer with three digits such that the sum of the cubes of its digits is equal to the number itself. Ex.371.

Solution :

print("Enter some number:")

num = int(input())

# initialize sum

sum = 0

# find the sum of the cube of each digit

temp = num

while (temp >0):

digit = temp % 10

sum = sum + (digit ** 3)

temp //= 10

# display the result

if (num == sum):

print(num,"is an Armstrong number")

else:

print(num,"is not an Armstrong number")

Output(Run1)

Enter some number:

371

371 is an Armstrong number

>>>

Output(Run2)

Enter some number:

456

456 is not an Armstrong number

>>>

Experiment 6 : To simulate simple calculator that performs basic tasks such as addition, subtraction, multiplication and division with special operations like computing xy and x!

Solution :

import math

def add(x, y):

return x + y

def sub(x, y):

return x - y

def mult(x, y):

return x * y

def div(x, y):

return x / y

def x_pow_y(x,y):

return math.pow(x,y)

def x_factorial(x):

factorial = 1

if x == 0:

return factorial

else:

for i in range(1,x+ 1):

factorial = factorial*i

return factorial

while(True):

print("Main Menu")

print("1.Add")

print("2.Subtract")

print("3.Multiply")

print("4.Divide")

print("5.x^y")

print("6.x!")

print("7.Exit")

print("Enter your choice")

choice = int(input())

if choice == 1:

print("Enter first number")

num1 = int(input())

print("Enter second number: ")

num2 = int(input())

print(num1,"+",num2,"=", add(num1,num2))

elif choice == 2:

print("Enter first number")

num1 = int(input())

print("Enter second number: ")

num2 = int(input())

print(num1,"-",num2,"=", sub(num1,num2))

elif choice == 3:

print("Enter first number")

num1 = int(input())

print("Enter second number: ")

num2 = int(input())

print(num1,"*",num2,"=", mult(num1,num2))

elif choice == 4:

print("Enter first number")

num1 = int(input())

print("Enter second number: ")

num2 = int(input())

print(num1,"/",num2,"=", div(num1,num2))

elif choice == 5:

print("Enter first number")

num1 = int(input())

print("Enter second number: ")

num2 = int(input())

print(num1,"^",num2,"=", x_pow_y(num1,num2))

elif choice == 6:

print("Enter a number")

num1 = int(input())

print(num1,"! = ", x_factorial(num1))

else:

print("Exiting")

break;

Output

Main Menu

1.Add

2.Subtract

3.Multiply

4.Divide

5.x^y

6.x!

7.Exit

Enter your choice

1

Enter first number

10

Enter second number:

20

10 + 20 = 30

Main Menu

1.Add

2.Subtract

3.Multiply

4.Divide

5.x^y

6.x!

7.Exit

Enter your choice

3

Enter first number

2

Enter second number:

4

2 * 4 = 8

Main Menu

1.Add

2.Subtract

3.Multiply

4.Divide

5.x^y

6.x!

7.Exit

Enter your choice

6

Enter a number

4

4 ! = 24

Main Menu

1.Add

2.Subtract

3.Multiply

4.Divide

5.x^y

6.x!

7.Exit

Enter your choice

5

Enter first number

5

Enter second number:

4

5 ^ 4 = 625.0

Main Menu

1.Add

2.Subtract

3.Multiply

4.Divide

5.x^y

6.x!

7.Exit

Enter your choice

7

Exiting

>>>

Experiment 7 : To accept the number and compute a) square root of a number b) Square of number c) Cube of a number d) Check for prime e) factorial of number f) prime factors

Solution :

import math

def sqrt_num(x):

return math.sqrt(x)

def sq_num(x):

return x*x

def cube_num(x):

return x * x *x

def isPrime(x):

if x > 1:

#check for factors

for i in range(2,x):

if (x % i) == 0: #factors exists

return False #hence it is not prime

else:

return True

else:

return False

def x_factorial(x):

factorial = 1

if x == 0:

return factorial

else:

for i in range(1,x+ 1):

factorial = factorial*i #multipying by subsequent number

return factorial

def prime_factors(x):

# Print the number of two's that divide x

while x % 2 == 0:

print ("2")

x = x / 2

# x must be odd at this point

# so a skip of 2 ( i = i + 2) can be used

for i in range(3,int(math.sqrt(x))+1,2):

# while i divides x , print i and divide x

while x % i== 0:

print(i)

x = x / i

# Condition if n is a prime

# number greater than 2

if x > 2:

print(x)

while(True):

print("Main Menu")

print("1.Square root")

print("2.Square")

print("3.Cube")

print("4.Check for Prime")

print("5.Factorial")

print("6.Prime Factors")

print("7.Exit")

print("Enter your choice")

choice = int(input())

if choice == 1:

print("Enter a number")

num = int(input())

print("Square Root of ",num,"is: ", sqrt_num(num))

elif choice == 2:

print("Enter a number")

num = int(input())

print("Square of ",num,"is: ", sq_num(num))

elif choice == 3:

print("Enter a number")

num = int(input())

print("Cube of ",num,"is: ", cube_num(num))

elif choice == 4:

print("Enter a number")

num = int(input())

if(isPrime(num)):

print(num," is a prime number")

else:

print(num," is not a prime number")

elif choice == 5:

print("Enter a number")

num = int(input())

print("Factorial of ",num," is: ", x_factorial(num))

elif choice == 6:

print("Enter a number")

num = int(input())

prime_factors(num)

else:

print("Exitting")

break;

Output

Main Menu

1.Square root

2.Square

3.Cube

4.Check for Prime

5.Factorial

6.Prime Factors

7.Exit

Enter your choice

1

Enter a number

25

Square Root of 25 is: 5.0

Main Menu

1.Square root

2.Square

3.Cube

4.Check for Prime

5.Factorial

6.Prime Factors

7.Exit

Enter your choice

2

Enter a number

4

Square of 4 is: 16

Main Menu

1.Square root

2.Square

3.Cube

4.Check for Prime

5.Factorial

6.Prime Factors

7.Exit

Enter your choice

4

Enter a number

7

7 is a prime number

Main Menu

1.Square root

2.Square

3.Cube

4.Check for Prime

5.Factorial

6.Prime Factors

7.Exit

Enter your choice

5

Enter a number

5

Factorial of 5 is: 120

Main Menu

1.Square root

2.Square

3.Cube

4.Check for Prime

5.Factorial

6.Prime Factors

7.Exit

Enter your choice

6

Enter a number

12

2

2

3.0

Main Menu

1.Square root

2.Square

3.Cube

4.Check for Prime

5.Factorial

6.Prime Factors

7.Exit

Enter your choice

7

Exitting

>>>

Experiment 8 : To accept two numbers from user and compute smallest divisor and Greatest Common Divisor of these two numbers

Solution :

def LCM(a,b):

if(a>b):

greater = a

else:

greater = b

while(True):

if((greater%a==0) and (greater%b==0)):

ans=greater

break

greater=greater+1

return ans

def GCD(a,b):

if(a>>

Experiment 9 : To accept numbers from user and print digits of number in reverse order.

Solution :

print("Enter some number")

n=int(input())

reverse=0

while (n >0):

reminder = n %10

reverse = (reverse *10) + reminder

n = n //10

print("The reversed number is: ",reverse)

Output

Enter some number

1234

The reversed number is: 4321

Experiment 10 : To input binary number from user and convert it to decimal number

Solution :

print("Enter a binary number: ")

binary = list(input())

value = 0

for i in range(len(binary)):

digit = binary.pop()#reading each digit of binary number from LSB

if digit == '1':#if it is 1

value = value + pow(2, i) #then get 2^i and add it to value

print("The decimal value of the number is", value)

Output

Enter a binary number:

1100

The decimal value of the number is 12

>>>

Experiment 11 : To generate pseudo random numbers

Solution :

import random

print(random.randint(0,100))

Output

39

>>>

Experiment 12 : To accept list of N integers and partition list into two sub lists even and odd numbers

Solution :

numlist = []

print("Enter total number of elements: \t")

n = int(input())

for i in range(1, n+1):

print("Enter element:")

element = int(input())

numlist.append(element)

evenlist = []

oddlist = []

for j in numlist:

if j % 2 == 0:

evenlist.append(j)

else:

oddlist.append(j)

print("Even numbers list \t", evenlist)

print("Odd numbers list \t", oddlist)

Output

Enter total number of elements:

5

Enter element:

11

Enter element:

22

Enter element:

33

Enter element:

44

Enter element:

55

Even numbers list [22, 44]

Odd numbers list [11, 33, 55]

>>>

Experiment 13 : To accept the numbers of terms a finds the sum of sine series

Solution :

We will first understand what the sine series is –

Sine series is a series used to find the value of sin(x) where x is the angle which is in radians and not in degrees. If the angle is given in degrees(which is the usual practice of specifying the angle)then it should be converted to radian.

The formula used to compute sine series is

sin x = [pic]

i.e.

sinx = [pic]

Consider x=900 . If we convert it to radian then

x in radian = angle*Pi/180

= 90*3.14159/180

= 1.5707

( sin(1.5707) = [pic] + ……

= 1.00

Let us now see the Python program based on this computation

import math

print("Enter the value for x in degree : ")

x=float(input())

print(" Enter the value for n : ")

n=int(input())

x=x*3.14159/180 #conversion of degree to radian

print("Angle in radian is: ",x)#displaying angle in radian

sum=0#initializing sum by zero

# Loop to calculate the value of Sine

for i in range(n):

sign=(-1)**i

sum = sum+((x**(2.0*i+1))/math.factorial(2*i+1))*sign

print("Sum of Sine series is: ",sum)

Output

Enter the value for x in degree :

90

Enter the value for n :

3

Angle in radian is: 1.570795

Sum of Sine series is: 1.004524829039292

>>>

Experiment 14 : To accept from user the number of Fibonacci numbers to be generated and print the Fibonacci series.

Solution :

def fibonacci(n):

a = 0

b = 1

print("fibonacci series is:")

print(a, ",", b, end=", ") #displaying first two elements of series

for i in range(2, n):

c = a + b #getting third element

print(c, end=", ")

a = b

b = c

print("Enter number of elements you want in series (minimum 2): ")

n = int(input())

fibonacci(n)# Call to the function

Output

Enter number of elements you want in series (minimum 2):

10

fibonacci series is:

0 , 1, 1, 2, 3, 5, 8, 13, 21, 34,

>>>

Experiment 15 : Write a python program that accepts a string from user and perform following string operations – i) Calculate length of string ii) String reversal

iii) Equality check of two strings iv) Check palindrome v) Check substring

Solution :

def str_len(str):

len = 0

for i in str:

len = len+1

return len

def str_rev(str):

return str[::-1]

def str_cmp(str1,str2):

if(str1==str2):

return True

else:

return False

def is_palindrome(str):

# Calling reverse function

rev = str_rev(str)

# Checking if both string are equal or not

if (str == rev):

return True

return False

def is_substr(str1,str2):

if(str1.find(str2)==-1):

return -1

else:

position=str1.find(str2)

return position

while(True):

print("Main Menu")

print("1.Calculate Length of String")

print("2.String Reversal")

print("3.Equality Check of two strings")

print("4.Check for Palindrome")

print("5.Check substring")

print("6.Exit")

print("Enter your choice")

choice = int(input())

if choice == 1:

print("Enter some string: ")

str = input()

print("Length of String: ",str,"is: ", str_len(str))

elif choice == 2:

print("Enter some string: ")

str = input()

print("Reversal of String: ",str,"is: ", str_rev(str))

elif choice == 3:

print("Enter first string: ")

str1 = input()

print("Enter second string: ")

str2 = input()

if(str_cmp(str1,str2)):

print("Two Strings are equal")

else:

print("Two Strings are not equal")

elif choice == 4:

print("Enter some string: ")

str = input()

if(is_palindrome(str)):

print("String ",str," is palindrome")

else:

print("String ",str," is not palindrome")

elif choice == 5:

print("Enter some String: ")

str1 = input()

print("Enter some substring: ")

str2 = input()

if((is_substr(str1,str2))>>

Experiment 16 : To copy contents of one file to another. While copying a) all full stops are replaced with commas b) lower case are replaced by upper case c) upper case are to be replaced with lower case.

Solution :

def replace_dot(file1):

file2=open("d:\\Replacedot.txt","w")

text=file1.readline()

while text:

word=text.split() #creating a list of words

word = [w.replace('.', ',') for w in word]#searching dot from each word and replacing it by comma

text=' '.join(word)#creating a sentence again from list of words

text+='\n'

file2.write(text)#writing the content to the file

text=file1.readline()#reading file line by line in a loop

file1.close()

file2.close()

def to_lower_case(file1):

file2=open("d:\\lowercase.txt","w")

text=file1.readline()

while text:

word=text.split()

word = [w.lower() for w in word] #converting each word to lower case

text=' '.join(word)

text+='\n'

file2.write(text)

text=file1.readline()

file1.close()

file2.close()

def to_upper_case(file1):

file2=open("d:\\uppercase.txt","w")

text=file1.readline()

while text:

word=text.split()

word = [w.upper() for w in word] #converting each word to upper case

text=' '.join(word)

text+='\n'

file2.write(text)

text=file1.readline()

file1.close()

file2.close()

file1=open("d:\\Original.txt","r")

replace_dot(file1)

print("The dots are replaced by commas in the file")

file1=open("d:\\Original.txt","r")

to_lower_case(file1)

print("The upper case letters are converted to lower case")

file1=open("d:\\Original.txt","r")

to_upper_case(file1)

print("The lower case letters are converted to upper case")

Output

|original.txt |

|[pic] |

|Replacedot.txt |lowercase.txt |

|[pic] |[pic] |

|uppercase.txt |

|[pic] |

Experiment 17 : To count total characters in file, total words in file, total lines in file and frequency of given word in file.

Solution :

from collections import Counter

def word_count(fname):

count=0

with open(fname,'r') as f:

for line in f:

word=line.split()

count+=len(word)

f.close()

return count

def char_count(fname):

count=0

with open(fname,'r') as f:

for line in f:

word=line.split()

count+=len(line)

f.close()

return count

def line_count(fname):

count=0

with open(fname,'r') as f:

for line in f:

word=line.split()

count+=1

f.close()

return count

def freq_word_count(fname):

with open(fname) as f:

return Counter(f.read().split())

print("Number of characters in the file :\n",char_count("d:\\test.txt"))

print("Number of words in the file :\n",word_count("d:\\test.txt"))

print("Number of lines in the file :\n",line_count("d:\\test.txt"))

print("Number of words with frequency count in the file :\n",freq_word_count("d:\\test.txt"))

Output

umber of characters in the file :

181

Number of words in the file :

32

Number of lines in the file :

5

Number of words with frequency count in the file :

Counter({'to': 3, 'This': 2, 'line': 2, 'is': 2, 'file.': 2, 'the': 2, 'Introduction': 1, 'File': 1, 'operations.': 1, 'Reading': 1, 'and': 1, 'Writing': 1, 'file': 1, 'operations': 1, 'in': 1, 'Python': 1, 'are': 1, 'easy': 1, 'understand.': 1, 'We': 1, 'enjoy': 1, 'it.': 1, 'written': 1, 'last': 1, 'of': 1})

>>>

Experiment 18 : Create class EMPLOYEE for storing details(Name, designation, gender, Date of joining and Salary). Define function members to compute a) total number of employees in an organization b) Count of male and female employee c) Employee with salary more than 10,000 d) Employee with designation “Asst Manager”

Solution :

class Employee:

count=0

female_count=0

male_count=0

salary_count=0

desig_count=0

def __init__(self,name,desig,gender,doj,salary):

self.name=name

self.desig=desig

self.gender=gender

self.doj=doj

self.salary=salary

Employee.count+=1

if(self.gender=="F"):

Employee.female_count+=1

else:

Employee.male_count+=1

if(self.salary>10000):

Employee.salary_count+=1

if(self.desig =="Asst_manager"):

Employee.desig_count+=1

def display_emp_count(self):

print("There are ",Employee.count, " employees in the organization")

def count_gender(self):

print("There are ",Employee.female_count, " female employees in the organization")

print("There are ",Employee.male_count, " male employees in the organization")

def count_big_salary(self):

print("There are ",Employee.salary_count, " employees in the organization having salary >10000")

def count_desig(self):

print("There are ",Employee.desig_count, " employees in the organization with designation 'Asst_manager' ")

#Entering data for Employee class

e1=Employee("Chitra","manager","F","1-2-2001",50000)

e2=Employee("Ankita","Asst_manager","F","23-5-2007",20000)

e3=Employee("Varsha","Accountant","F","11-9-2010",10000)

e4=Employee("Rahul","HR","M","24-3-2012",30000)

e5=Employee("Aditya","Asst_manager","M","14-7-2009",20000)

e5.display_emp_count()

e5.count_gender()

e5.count_big_salary()

e5.count_desig()

Output

There are 5 employees in the organization

There are 3 female employees in the organization

There are 2 male employees in the organization

There are 4 employees in the organization having salary >10000

There are 2 employees in the organization with designation 'Asst_manager'

>>>

Experiment 19 : Create a class STORE to keep track of Products(product Code, Name and price).Display menu of all products to user. Generate bill as per order.

Solution :

class STORE:

__product_code = []

__name = []

__price =[]

def input_data(self):

for i in range(3):

self.__product_code.append(int(input("Enter the code of product: ")))

self.__name.append(input("Enter the name of product: "))

self.__price.append(float(input("Enter the price of product: ")))

def display_data(self):

print("Product code\t Name \t Price")

for i in range(3):

print(self.__product_code[i],"\t\t",self.__name[i],"\t\t\t",self.__price[i])

def generate_bill(self,qty):

total_amount=0

for i in range(3):

total_amount= total_amount+self.__price[i]*qty[i]

print("\t\t###### BILL #######")

print("Code \t Name\t Price \t Qty \t Subtotal")

for i in range(3):

print(self.__product_code[i],"\t",self.__name[i],"\t\t",self.__price[i],"\t",qty[i],"\t",self.__price[i]*qty[i])

print("----------------------------------------------------")

print("Total = ",total_amount)

s=STORE()

s.input_data()

s.display_data()

qty=[]

for i in range(3):

print("Enter the quantity for each product")

qty.append(int(input()))

s.generate_bill(qty)

Output

Enter the code of product: 101

Enter the name of product: pen

Enter the price of product: 20

Enter the code of product: 102

Enter the name of product: pencil

Enter the price of product: 5

Enter the code of product: 103

Enter the name of product: eraser

Enter the price of product: 2

Product code Name Price

101 pen 20.0

102 pencil 5.0

103 eraser 2.0

Enter the quantity for each product

10

Enter the quantity for each product

25

Enter the quantity for each product

15

###### BILL #######

Code Name Price Qty Subtotal

101 pen 20.0 10 200.0

102 pencil 5.0 25 125.0

103 eraser 2.0 15 30.0

---------------------------------------------------

Total = 355.0

>>>

Experiment 20 (Mini Project) : Program that simulates rolling dice. When the program runs, it will randomly choose the numbers between 1 and 6(or other integer you prefer). Print that number. Request user to roll again. Set the min and max number that dice can show. For the average die, that means a minimum of 1 and maximum of 6.

Solution :

import random

min = 1

max = 6

roll_again = "yes"

while roll_again == "yes" or roll_again == "y":

print("Rolling the dice...")

print("The value is....")

print(random.randint(min, max))

roll_again = input("Do you want to Roll the dice again?")

Output

Rolling the dice...

The value is....

6

Do you want to Roll the dice again?y

Rolling the dice...

The value is....

2

Do you want to Roll the dice again?y

Rolling the dice...

The value is....

6

Do you want to Roll the dice again?y

Rolling the dice...

The value is....

4

Do you want to Roll the dice again?n

>>>

Experiment 21(Mini Project):

Guess Number: Randomly generate a number unknown to the user. The user needs to guess what that number is. If user’s guess is wrong, the program should return some sort of indication as to how wrong(e.g. the number is too high or too low). If the user guesses correctly, a positive indication should appear. Write functions to check if the user input is an actual number, to see the difference between the inputted number and the randomly generated numbers and to then compare the numbers

Solution :

import random

randomNumber = random.randrange(0,100)

print("Random number has been generated")

guessed = False

while guessed==False:

num = int(input("Enter some guess: "))

if num==randomNumber:

guessed = True

print("Well done!You have guessed a number correctly!!!")

elif num>100 and num randomNumber:

print("Number is high")

elif num < randomNumber:

print("Number is low")

Output

Random number has been generated

Enter some guess: 55

Number is low

Enter some guess: 80

Number is high

Enter some guess: 65

Number is high

Enter some guess: 60

Number is low

Enter some guess: 62

Number is low

Enter some guess: 64

Well done!You have guessed a number correctly!!!

>>>

θθθ

Notes[pic]

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download