Assignment (Jatin)
Assignment (Jatin)
NAME: JATIN
ROLL NO:APS21093
DANIEL LIANG BACK EXERCISES:
CHAPTER-1
Q-Write a program that displays Welcome to python,Welcome to computer science and
Programming is fun?
Ans-print(“Welcome to python”)
print(“Welcome to computer science”)
print(“Programming is fun”)
Ans-n=("Welcome to python")
for i in range(0,5):
print(n)
FFFFFFF U U NN NN
FF U U NNN NN
FFFFFFF U U NN N NN
FF U U NN N NN
FF UUU NN NNN
Ans- N,U,F=””,””,””
P=””
i=1
while i<=5:
if i==1 or i==3:
f=”FFFFFFF”
else:
f=”FF “
if: i==4:
U=” U U “
elif:i==5:
U= ” UUU “
else:
U=”U U”
N=”NN”
J=1
while j<5:
if j==(i-1):
N=N+”N”
else:
N=N+” “
j=j+1
N=N+”NN”
P=F+” “+U+” “+N
print(str(p))
i=i+1
a a**2 a**3
1 1 1
2 4 8
3 9 27
4 16 64
Ans-print("a","a**2","a**3")
for i in range(1,5):
print(i,i**2,i**3,sep=" ")
print("\r")
9.5*4.5-2.5*3/45.5-3.5
Ans-m=0
for i in range(1,10):
m=m+i
print(m)
Value of pie=4*(1-1/3+1/5-1/7+1/9-1/11………)
4*(1-1/3+1/5-1/7+1/9-1/11+1/13-1/15) ?
Q-Write a program that displays the area and perimeter of a circle that has a radius of 5.5
using the following formulas:
area=radius*radius*pie
perimeter=2*radius*pie ?
Ans-radius=5.5
area=(radius**2)*3.14
perimeter=(2*3.14)*radius
print(“area of circle”,area)
print(“perimeter of circle”,perimeter)
Q-Write a program that displays the area and perimeter of a rectangle with the width of 4.5
and height of 7.9 using the following formula:
Area=height*width
Ans-width=4.5
height=7.9
area=height*width
perimeter=2*(height + width)
print(“area of rectangle”,area)
print(“perimeter of rectangle”,perimeter)
Ans-kilometers=14
miles=kilometers/1.6
minutes=45
seconds=30
hours=(minutes/60) + (seconds/3600)
speed=miles/hours
print(“speed in miles per hour is”,speed)
Q-The US census bureauprojects population based on the following assumptions:
Write a program to display the population for each of the next five years. Assume the
current population is 312032486 and one year has 365 days.
Hint: in Python, you can use integer division operator // to perform division. The result is an
integer.
For example, 5 // 4 is 1 (not 1.25) and 10 // 4 is 2 (not 2.5).
Ans- p=312032486
b=(365*24*60*60)//5
d=(365*24*60*60)//13
m=(365*24*60*60)//45
for i in range(1,6):
r=i*(b+m-d)+p
print(r)
CHAPTER 2
Q- Write a program that reads a Celsius degree from the console and converts it to
Fahrenheit and displays the result. The formula for the conversion is as follows: Fahrenheit
= (9 / 5) * Celsius + 32
Here is a sample run of the program:
Q- Write a program that reads in the radius and length of a cylinder and computes the area
and volume using the following formulas:
area=radius*radius*pie
volume=area*length
Here is a sample run:
enter the radius and length of a cylinder:5.5,12
the area is 95.0331
the volume is 1140.4
Ans- radius, length = eval(input("Enter the radius and length of a cylinder: "))
area = radius * radius * 3.14159
volume = area * length
print("The area is", area)
print("The volume of the cylinder is", volume)
Q- Write a program that reads a number in feet, converts it into meters, and
displays the result. One foot is 0.305 meters.
Here is a sample run:
Enter a value for feet:16.5
16.5 feet is 5.0325 meters
Q-Write a program that converts pounds into kilograms. The program prompts the user to
enter a value in pounds, converts it to kilograms, and displays the result. One pound is
0.454 kilograms.
Here is a sample run:
Q-Write a program that reads the subtotal and the gratuity rate and computes the gratuity
and total. For example, if the user enters 10 for the subtotal and 15% for the gratuity rate,
the program displays 1.5 as the gratuity and 11.5 as the total.
Here is a sample run:
Q-Write a program that reads an integer between 0 and 1000 and adds all the digits in the
integer. For example, if an integer is 932, the sum of all its digits is 14. (Hint: Use the %
operator to extract digits, and use the // operator to remove the extracted digit. For instance,
932 % 10 = 2 and 932 // 10 = 93.)
Q-Write a program that prompts the user to enter the minutes (e.g., 1 billion), and displays
the number of years and days for the minutes. For simplicity, assume a year has 365 days.
Here is a sample run:
Q-Write a program that calculates the energy needed to heat water from an initial
temperature to a final temperature. Your program should prompt the user to enter the
amount of water in kilograms and the initial and final temperatures of the water. The formula
to compute the energy is
Q-How cold is it outside? The temperature alone is not enough to provide the answer. Other
factors including wind speed, relative humidity, and sunshine play important roles in
determining coldness outside. In 2001, the National Weather Service (NWS) implemented
the new wind-chill temperature to measure the coldness using temperature and wind speed.
The formula is given as follows:
speed measured in miles per hour.twc is the wind-chill temperature. The formula
cannot be used for wind speeds below 2 mph or for temperatures below -58F or
above 41°F.
Write a program that prompts the user to enter a temperature between -58F and
41°F and a wind speed greater than or equal to 2 and displays the wind-chill tem-
perature.
if m>=2:
Q- Given an airplane’s acceleration a and take-off speed v, you can compute the minimum
runway length needed for an airplane to take off using the following formula:
Length=v**2/2a
Write a program that prompts the user to enter v in meters/second (m/s) and the
length = v * v / (2 * a)
print("The minimum runway length for this airplane is", length, "meters")
Q- Suppose you want to deposit a certain amount of money into a savings account with a
fixed annual interest rate.
What amount do you need to deposit in order to have $5,000 in the account after three
years?
The initial deposit amount can be obtained using the following formula:
Write a program that prompts the user to enter final account value, annual interest rate in
percent, and the number of years, and displays the initial deposit amount.
Here is a sample run:
Enter final account value: 1000
Enter annual interest rate in percent: 4.25
Enter number of years: 5
Initial deposit value is 808.8639197424636
Ans- n=eval(input("enter final account value"))
d=m/12
h=s*12
k=(1+d)*h
id=n/k
A b a ** b
1 2 1
2 3 8
3 4 81
4 5 1024
5 6 15625
for i in range(1,6):
Q- )Write a program that prompts the user to enter a four-digit integer and displays the
number in reverse order.
Here is a sample run:3125
Enter an integer:
1
2
Q- Write a program that prompts the user to enter the three points (x1, y1), (x2, y2), and (x3,
y3) of a triangle and displays its area.
The formula for computing the area of a triangle is
Enter three points for a triangle: (1.5, -3.4),( 4.6, 5),( 9.5, -3.4)
Ans-x1, y1, x2, y2, x3, y3 = eval(input("Enter three points for a triangle: "))
side1 = ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5
side2 = ((x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3)) ** 0.5
side3 = ((x3 - x2) * (x3 - x2) + (y3 - y2) * (y3 - y2)) ** 0.5
Q-Write a program that prompts the user to enter the side of a hexagon and displays its
area. The formula for computing the area of a hexagon is
Q-) Average acceleration is defined as the change of velocity divided by the time taken to
make the change, as shown in the following formula:
A= (V1-V0)/T
Write a program that prompts the user to enter the starting velocity V0 in
a = (v1 - v0) / t
Q-Body mass index (BMI) is a measure of health based on weight. It can be calculated by
taking your weight in kilograms and dividing it by the square of your height in meters. Write
a program that prompts the user to enter a weight in pounds and height in inches and
displays the BMI.
Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters.
BMI is 26.8573
locale.setlocale(locale.LC_ALL, 'en_US')
print()
choice = "y"
months = year * 12
future_value = 0
for i in range(months):
future_value, grouping=True))
print()
print()
print("Bye!")
MURACH’S LAST EXERCISE
CHAPTER 2
ANS 2.1- miles_driven=float(input(“enter miles driven:\t\t”))
gallons_used=float(input(“enter gallons of gas used:\t\t”))
costpergallon=float(input(“enter cost per gallon”))
mpg=miles_driven/gallons_used
mpg=round(mpg,2)
totalgascost=costpergallon*gallons_used
costpermile=totalgascost/miles_driven
print()
print(“miles per gallon:\t\t” + str(mpg))
print(“total gas cost:”,totalgascost)
print(“cost per mile:”,costpermile)
Output
Ans-2.2 counter=0
score_total=0
test_score=0
while test_score!=999:
test_score=int(input(“enter test score”))
if test_score>=0 and test _score<=100:
t= str(test_score)
print(t,sep=” “)
score_total += test_score
counter += 1
average_score= round(score_total/counter
print(“total score:” + str(score_total))
print(“average score:”+ str(average_score))
Ans-2.3
output
if miles_driven <= 0:
print("Miles driven must be greater than zero.
Please try again”)
elif gallons_used <= 0:
print("Gallons used must be greater than zero.
Please try again”)
else:
# calculate and display miles per gallon
mpg = round(miles_driven / gallons_used, 2)
print("Miles Per Gallon: ", mpg)
print()
print("Bye!")
# initialize variables
counter = 0
score_total = 0
test_score = 0
while test_score != 999:
test_score = int(input("Enter test score: "))
if test_score >= 0 and test_score <= 100:
score_total += test_score
counter += 1
elif test_score == 999:
break
else:
print(f"Test score must be from 0 through
100. "f"Score discarded. Try again.")
print("Bye!")
CH 4 MURACH BACK EXERCISE
ANS4.1 def calculate_future_value(monthly_investment,
yearly_interest, years):
# convert yearly values to monthly values
monthly_interest_rate=
yearly_interest/12/100
months = years * 12
def main():
choice = "y"
while choice.lower() == "y":
# get input from the user
monthly_investment = float(input("Enter monthly
investment:\t"))
yearly_interest_rate = float(input("Enter
yearly interest rate:\t"))
years = int(input("Enter number of
years:\t\t"))
# get and display future value
future_value = calculate_future_value(
monthly_investment,yearly_interest_rate,years)
print(f"Future value:\t\t\t{round(future_value,
2)}")
print()
# see if the user wants to continue
choice = input("Continue? (y/n): ")
print()
print("Bye!")
if __name__ == "__main__":
main()
CH 7 MURACH BACK EXERCISE
ANS 7.1
import csv
FILENAME = "trips.csv"
def write_trips(trips):
writer = csv.writer(file)
writer.writerows(trips
def read_trips():
trips = []
reader = csv.reader(file)
trips.append(row)
return trips
def get_miles_driven():
while True:
if miles_driven > 0:
return miles_driven
else:
continue
def get_gallons_used():
while True:
if gallons_used > 0:
return gallons_used
else:
continue
def list_trips(trips):
print("Distance\tGallons\tMPG")
for i in range(len(trips)):
trip = trips[i]
print()
def main():
trips = read_trips()
list_trips(trips)
more = "y"
miles_driven = get_miles_driven()
gallons_used = get_gallons_used()
print()
trip = []
trip.append(miles_driven)
trip.append(gallons_used)
trip.append(mpg)
trips.append(trip)
write_trips(trips)
list_trips(trips)
print("Bye")
if __name__ == "__main__":
main()
ANS7.2
import csv
FILENAME = "trips.csv"
def write_trips(trips):
writer = csv.writer(file)
writer.writerows(trips)
def get_miles_driven():
while True:
if miles_driven > 0:
return miles_driven
else:
continue
def get_gallons_used():
while True:
if gallons_used > 0:
return gallons_used
else:
continue
def main():
print()
trips = []
more = "y"
while more.lower() == "y":
miles_driven = get_miles_driven()
gallons_used = get_gallons_used()
print()
trip = []
trip.append(miles_driven)
trip.append(gallons_used)
trip.append(mpg)
trips.append(trip)
write_trips(trips)
print("Bye K. Zoom")
if __name__ == "__main__":
main()
ANS7.3
import pickle
FILENAME = "trips.bin"
def write_trips(trips):
pickle.dump(trips, file)
def get_miles_driven():
while True:
if miles_driven > 0:
return miles_driven
else:
continue
def get_gallons_used():
while True:
if gallons_used > 0:
return gallons_used
else:
continue
def main():
print()
trips = []
more = "y"
gallons_used = get_gallons_used()
print()
trip = []
trip.append(miles_driven)
trip.append(gallons_used)
trip.append(mpg)
trip.append(trip)
write_trips(trips)
print("Bye K. Zoom")
if __name__ == "__main__":
main()
import csv
import sys
FILENAME = "movies.csv"
def exit_program():
print("Terminating program.")
sys.exit()
def read_movies():
try:
movies = []
reader = csv.reader(file)
movies.append(row)
return movies
except FileNotFoundError as e:
exit_program()
except Exception as e:
print(type(e), e)
exit_program()
def write_movies(movies):
try:
writer.writerows(movies)
except Exception as e:
print(type(e), e)
exit_program()
def list_movies(movies):
print()
def add_movie(movies):
movies.append(movie)
write_movies(movies)
def delete_movie(movies):
while True:
try:
continue
else:
break
movie = movies.pop(number - 1)
write_movies(movies)
def display_menu():
print()
print("COMMAND MENU")
print()
def main():
display_menu()
movies = read_movies()
while True:
if command.lower() == "list":
list_movies(movies)
add_movie(movies)
delete_movie(movies)
break
else:
print("Bye!")
if __name__ == "__main__":
main()
ANS8.2
return future_value
def main():
choice = "y"
while choice.lower() == "y":
# get input from the user
monthly_investment = get_number("Enter monthly investment:\t", 0, 1000)
yearly_interest_rate = get_number("Enter yearly interest rate:\t", 0, 15)
years = get_integer("Enter number of years:\t\t", 0, 50)
print("Bye!")
if __name__ == "__main__":
main()
if n == 0:
return 0
elif n == 1:
return 1
else:
def main():
for i in range(16):
print("...")
if __name__ == "__main__":
main()
ANS 13.2
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
n1 = 0
n2 = 1
fib = 0
for i in range(2, n+1):
fib = n1 + n2
n1 = n2
n2 = fib
return fib
def main():
for i in range(16):
print(fib(i), end=", ")
print("...")
if __name__ == "__main__":
main()
ANS13.3
def move_disk(n, src, dest, temp):
if n == 0:
return
else:
move_disk(n-1, src, temp, dest)
print("Move disk", n, "from", src, "to", dest)
move_disk(n-1, temp, dest, src)
def main():
print("**** TOWERS OF HANOI ****")
print()
num_disks = int(input("Enter number of disks: "))
print()
move_disk(num_disks, "A", "C", "B")
print()
print("All disks have been moved.")
if __name__ == "__main__":
main()
def main():
"| |\n" + \
"| o |\n" + \
"|_____|")
"|o |\n" + \
"| |\n" + \
"|____o|")
"|o |\n" + \
"| o |\n" + \
"|____o|")
"| |\n" + \
"|o___o|")
"|o o|\n" + \
"| o |\n" + \
"|o___o|")
"|o o|\n" + \
"|o o|\n" + \
"|o___o|")
print()
dice = Dice()
for i in range(count):
die = Die()
dice.addDie(die)
choice = "y"
#display to user
print("\n")
print("Bye!")
if __name__ == "__main__":
main()
import random
@dataclass
class Die:
__value:int = 1
@property
def value(self):
return self.__value
@value.setter
if value < 1:
self.__value = value
def roll(self):
self.__value = random.randrange(1, 7)
class Dice:
def __init__(self):
self.__list = []
self.__list.append(die)
@property
def list(self):
return tuple(self.__list)
def rollAll(self):
die.roll()
ANS14.2
def list(movie_list):
if len(movie_list) == 0:
print("There are no movies in the list.\n")
return
else:
for i, row in enumerate(movie_list, start=1):
print(f"{i}. {row[0]} ({row[1]})")
print()
def add(movie_list):
name = input("Name: ")
year = input("Year: ")
movie = [name, year]
movie_list.append(movie)
print(f"{movie[0]} was added.\n")
def delete(movie_list):
number = int(input("Number: "))
if number < 1 or number > len(movie_list):
print("Invalid movie number.\n")
else:
movie = movie_list.pop(number-1)
print(f"{movie[0]} was deleted.\n")
def display_menu():
print("COMMAND MENU")
print("list - List all movies")
print("add - Add a movie")
print("del - Delete a movie")
print("exit - Exit program")
print()
def main():
movie_list = [["Monty Python and the Holy
Grail", 1975]
["On the Waterfront", 1954],
["Cat on a Hot Tin Roof", 1958]]
display_menu()
while True:
command = input("Command: ")
if command == "list":
list(movie_list)
elif command == "add":
add(movie_list)
elif command == "del":
delete(movie_list)
elif command == "exit":
break
else:
print("Not a valid command. Please try
again.\n")
print("Bye!")
if __name__ == "__main__":
main()
ANS14.3
def to_celsius(fahrenheit):
celsius = (fahrenheit - 32) * 5/9
return celsius
def to_fahrenheit(celsius):
fahrenheit = celsius * 9/5 + 32
return fahrenheit
# the main function is used to test the other functions
# this code isn't run if this module isn't the main module
def main():
for temp in range(0, 212, 40):
print(temp, "Fahrenheit equals",
round(to_celsius(temp), 2), "Celsius")
for temp in range(0, 100, 20):
print(temp, "Celsius equals",
round(to_fahrenheit(temp), 2),
"Fahrenheit")
# if this module is the main module, call the main function
# to test the other functions
if __name__ == "__main__":
main()
# TEMPRATURE CONVERTER
print()
print("MENU")
print()
def convert_temp():
if option == 1:
c = temp.to_celsius(f)
c = round(c, 2)
elif option == 2:
f = temp.to_fahrenheit(c)
f = round(f, 2)
print("Degrees Fahrenheit:", f)
else:
def main():
display_menu()
again = "y"
convert_temp()
print()
print()
print("Bye!")
if __name__ == "__main__":
main()
ANS1.
math.ceil(65.65) : 66
math.fabs(-67.58) : 67.58
math.exp(2.7) : 14.8797
math.log10(1000) : 3.0
math.sqrt(121) : 11.0
math.degree(math.pi/2): 90.0
math.ceil(65.47) : 66
math.fabs(3) : 3.0
math.log(45,2) : 5.491
math.pow(4,1/2) : 2.0
math.radians(30) : 0.5235
ANS2.
ANS3.
abs(-5.4) : 5.4
abs(15) : 15
chr(72) : 'H'
round(-24.9) : -25
float(57) : 57.0
complex('1+2j') : (1+2j)
float(57) : 57.0
pow(9,2) : 81
a) def pattern1():
print("\t\t*")
print("\t*\t*\t*)
print("*\t*\t*\t*\t*")
print("\t*\t*\t*")
print("\t\t*")
b) def pattern2():
print("$ $ $ $ $")
print("$ $")
print("$ $")
print("$ $")
print("$ $ $ $ $")
ANS5.
a) nMultiple(5) : 5
nMultiple(5,6) : 30
nMultiple(num=7) : 0
nMultiple(num=6,a=5): 30
nmultiple(5,num=6) : 30
ANS6.
a) a= 8
b= 5
b) None
ANS7.
import math
def areaTriangle(side1,side2,side3):
s=(side1+side2+side3)/2
d=s*(s-side1)*(s-side2)*(s-side3)
a=math.sqrt(d)
return a
def main():
ans=areaTriangle(side1,side2,side3)
print("Area: ",ans)
main()
ANS1.
def replacstar(stri):
strr=''
for i in range(0,len(stri)):
if stri[i]==stri[i-1]:
strr=strr[:i+1]+'*'
else:
strr+=stri[i]
return strr
ANS2.
if(sorted(s1)== sorted(s2)):
else:
ANS3.
def numberofwords(s):
count=1
for i in s:
if i==" ":
count+=1
print("number of words are :",count)
ANS4.
def convert(s):
ch = list(s)
for i in range(len(s)):
ord('A'))
ord('A'))
st = "".join(ch)
return st;
if __name__=="__main__":
print(convert(s));
ANS5.
def numberofwords(s):
count=1
for i in s:
if i==" ":
count+=1
ANS6.
a) 22
b) ' Delhi'
e) -1
h) False
ANS7.
a) 2
b) 15
c) 27
h) False
m) False
n) True
ANS1.
def removeduplicates(lst1):
s=set(lst1)
lst2=list(lst1)
return lst2
ANS2.
def cumulativelist(lst1):
lst2=[]
sum1=0
for i in lst:
sum1=sum1+i
lst2.append(sum1)
return lst2
ANS3.
def main():
freq={}
letters='abcdefghijklmnopqrstuvwxyz'
sentence=input("enter a sentence")
sentence1=sentence.lower()
for i in sentence1:
if i in letters:
if i in freq:
freq[i]+=1
else:
freq[i]=1
print(freq)
ANS4.
a) [0, 1, 2, 3, 4]
[3, 4, 5, 6, 7]
b) [3, 1, 5, 3, 7]
[0, 4, 2, 6, 4]
ANS5.
a) 30
b) 25
c) omputerc
d) 219
ANS6.
def funclist(n):
lst=[]
l=[0,0,0,0,0]
for i in range(1,n+1):
for j in range(1,6):
l[j-1]=i*j
lst.append(l[:])
ANS7.
def digit(n):
dicti={1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten'}
reverse=0
while n>0:
remainder=n%10
reverse=reverse*10+remainder
n=n//10
while reverse>0:
digits=reverse%10
print(dicti[digits],end=" ")
reverse=reverse//10
ANS8.
a) Index Error
b) [1, 2, 3, 1, 2, 3]
c) Type Error
d) 3
e) ['B', '-', '6', ' ', 'L', 'o', 'd', 'h', 'i', ' ', 'r', 'o', 'a', 'd', ',', 'D', 'e', 'l', 'h', 'i']
j) [2]
k) [2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8]
l) Type Error
m) Attribute Error
n) Type Error
o) 'a, e, i, o, u'
p) [('apple', 'red'), ('orange', 'orange')]
r) {'X': ['eng', 'hindi', 'maths', 'science'], 'XII': ['english', 'physics', 'chemistry', 'maths', 'computer
science']}
s) False
u) ['X', 'XII']
v) 'None'
ANS9.
c) {'Car'}
f) 'Bicycle'
'Scooter'
'Car'
'Bike'
'Truck'
'Bus'
'Rickshaw'
g) 7
h) 'Bicycle'
ANS1.
if r < l:
return -1
if arr[l] == x:
return l
if arr[r] == x:
return r
n = len(arr)
if index != -1:
ANS2.
def insertionSortRecursive(arr,n):
if n<=1:
return
insertionSortRecursive(arr,n-1)
in sorted array.'''
last = arr[n-1]
j = n-2
arr[j+1] = arr[j]
j = j-1
arr[j+1]=last
def printArray(arr,n):
for i in range(n):
print(arr[i],end=" ")
arr = [12,11,13,5,6]
n = len(arr)
insertionSortRecursive(arr, n)
printArray(arr, n)
ANS5.
if pivot == -1:
if arr[pivot] == key:
return pivot
return -1
if high == low:
return low
return mid
return (mid-1)
return -1
if key == arr[mid]:
return mid
key);
return binarySearch(arr, low, (mid -1), key);
print(arr1)
n = len(arr1)
pivotedBinarySearch(arr1, n, key))
ANS6.
N=int(no)
L=[]
k=input("Enter an element")
L.append(k)
print(L)
g=L[0]
L.pop(0)
L.append(g)
print(L)