0% found this document useful (0 votes)
88 views24 pages

CB - Sc.u4cse23215 PQ

The document contains 6 programming questions related to functions in Python. Question 1 asks to write a function to check if a number is prime. Question 2 asks to write a function to print factors of a number. Question 3 asks to write a function to calculate factorial of a number. Question 4 asks to write a function to print a number in words. Questions 5 and 6 ask to write functions that accept arrays as input and perform operations like finding sum and difference between maximum and minimum elements.

Uploaded by

vimal007.x
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views24 pages

CB - Sc.u4cse23215 PQ

The document contains 6 programming questions related to functions in Python. Question 1 asks to write a function to check if a number is prime. Question 2 asks to write a function to print factors of a number. Question 3 asks to write a function to calculate factorial of a number. Question 4 asks to write a function to print a number in words. Questions 5 and 6 ask to write functions that accept arrays as input and perform operations like finding sum and difference between maximum and minimum elements.

Uploaded by

vimal007.x
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Qn1.

Write a program that contains a function to check whether the argument is a


prime number or not. Function accepts an integer and returns 0 if the integer is a
prime number. Otherwise, it returns 1.
CODE:
def check_prime(num):
global factor
factor = 0
for i in range(1,num+1):
if (num%i==0):
factor+=1
return factor

num = int(input())
check_prime(num)
if factor==2:
print("1")
else:
print("0")
OUTPUT:

Qn 2. Write a program that contains a function which will print the factors of the
given number. Number to be given as argument/input to the function.
CODE:
def factor(num):
global factors
factors=[]
for i in range(1,num+1):
if num%i==0:
[Link](i)
return factors

num=int(input())
factor(num)
for i in factors:
print(i)

OUTPUT:
Qn 3. Write a program that contains a function to calculate the factorial of a given
number. The function takes number as argument and returns its factorial.
CODE:
def factorial(num):
global value
value=1
for i in range(1,num+1):
value=value*i
return value

num=int(input())
factorial(num)
print(value)
OUPUT:

Qn 4. Write a program that contains a function which will print the number given
as argument in words – 123 to be printed as one two three
CODE:
def num_word(num):

list=["Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine"]
for i in num:
print(list[int(i)] , end = " ")

num=input()
num_word(num)

OUTPUT:

Qn 5. Write a program with a function that accepts an array and the number of
elements in the array as inputs and returns the sum of the elements in the array.
CODE:
import array as arr
list=[]
def sum_array():
global sum1
ARRAY=[Link]('i', [ ])
[Link](list)
sum1=0
for x in ARRAY:
sum1 = sum1 + x
return sum1
n = int(input("Len of List:" ))
for i in range(n):
ele = int(input())
[Link](ele)
sum_array()
print(sum1)

Qn 5. Write a program that contains a function that accepts an array and the number
of elements in the array as inputs and returns the difference between largest and
smallest elements of the array.
CODE:
import array as arr
list = []
def diff_array():
global diff_ele
aRRAY = [Link]('i', [ ])
[Link](list)
largEle = smallEle = aRRAY[0]
for i in aRRAY:
if i > largEle:
largEle = i
if i < smallEle:
smallEle = i
diff_ele = largEle - smallEle
return diff_ele
n = int(input())
for i in range(n):
list_ele = int(input())
[Link](list_ele)
diff_array()
print(diff_ele)
OUTPUT:

36 (diff of largest and smallest ele in array)


PROGRAMMING [Link]
Qn 1. A company offers dearness allowance (DA) of 40% of basic pay and house rent
allowance (HRA) of 10% of basic pay. Input basic pay of an employee, calculate his/her
DA, HRA and Gross pay (Gross = Basic Pay + DA+ HRA).
CODE:
BP = int(input())
DA = 0.4*BP
HRA = 0.1*BP
grossPay = BP + DA + HRA
print(DA)
print(HRA)
print(grossPay)
OUTPUT:

a. Modify the above scenario, such that the DA and HRA percentages are also given
as inputs.
CODE:
BP = int(input())

DA_percent = int(input())
DA = DA_percent*BP/100

HRA_percent = int(input())
HRA = HRA_percent*BP/100

grossPay = BP + DA + HRA
print(DA)
print(HRA)
print(grossPay)
OUTPUT:
b. Update the program such that the program uses a user-defined function for
calculating the Gross pay. The function takes Basic pay, DA percentage and HRA
percentage as inputs and returns the gross pay.
CODE:
BP = int(input())
def grossPay():
global grossPay

DA_percent = int(input())
DA = DA_percent*BP/100

HRA_percent = int(input())
HRA = HRA_percent*BP/100

grossPay = BP + DA + HRA
return grossPay
grossPay()
print(grossPay)
OUTPUT:

Qn 2. You have a monthly income of Rs 1100. Your monthly outgoings are as follows.
• Rent – Rs.500
• Food – Rs.300
• Electricity – Rs.40
• Phone - Rs 60
• Cable TV - Rs 30.
Calculate the Monthly Expenses and the remainder (what’s left over each month).
CODE:
# Everything is in rupees
Salary = 1100
Rent = 500
Food = 300
Electricity = 40
Phone = 60
Cable_TV = 30

monthlyExpense = Rent + Food + Electricity + Phone + Cable_TV


moneyLeft = Salary - monthlyExpense
print(monthlyExpense)
print(moneyLeft)
OUTPUT:

a. Modify the above program by inputting the income as well as values for expenses
and calculate Monthly expense.
CODE:
# Everything is in rupees
Salary = int(input())
Rent = int(input())
Food = int(input())
Electricity = int(input())
Phone = int(input())
Cable_TV = int(input())

monthlyExpense = Rent + Food + Electricity + Phone + Cable_TV


moneyLeft = Salary - monthlyExpense

print(monthlyExpense)
print(moneyLeft)
OUTPUT:

c. Include a function to check whether you will have savings or you have to borrow
money based on the monthly income and total expenses. The function should
print an appropriate message for each case.
CODE:
# Everything is in rupees
def expense():
global monthlyExpense
global moneyLeft
monthlyExpense = Rent + Food + Electricity + Phone + Cable_TV
moneyLeft = Salary - monthlyExpense

Salary = int(input())
Rent = int(input())
Food = int(input())
Electricity = int(input())
Phone = int(input())
Cable_TV = int(input())

expense()
if monthlyExpense > Salary:
print("You need to borrow")
elif monthlyExpense < Salary:
print("You will have savings")
else:
print("Neither you will have savings nor need to borrow")
OUTPUT:

Qn 3. For a vehicle, its on-road cost is calculated as SUM of Basic Price, Vehicle Tax,
Weight Tax and Insurance. There are two types of vehicles – PRIVATE (P) and BUSINESS
(B). The details are given below: -

Input Price, Type and Weight of the vehicle and calculate the on-road price.

CODE:

Price = int(input())
Type = input()
Weight = int(input())
if Type == 'P':
VT = 0.05*Price
WT = 0.01*Weight
IP = 0.01*Price
elif Type == 'B':
VT = 0.1*Price
WT = 0.03*Weight
IP = 0.02*Price

onRoadPrice = Price + VT + WT + IP
print(onRoadPrice)
OUTPUT:
a. Modify the above program to create a dictionary for each vehicle by including
all details – Type, Weight, Basic price, Vehicle Tax, Weight Tax, Insurance and
on-road price.

CODE:

vehicleDict = {}
vehicleDict["Type"] = input()
vehicleDict["Weight"] = int(input())
vehicleDict["basicPrice"] = int(input())
vehicleDict["vehicleTax"] = float(input())*vehicleDict["basicPrice"]
vehicleDict["weightTax"] = float(input())*vehicleDict["Weight"]
vehicleDict["insurance"] = float(input())*vehicleDict["basicPrice"]
vehicleDict["onRoadPrice"] = vehicleDict["basicPrice"] +
vehicleDict["vehicleTax"] + vehicleDict["weightTax"] +
vehicleDict["insurance"]
print(vehicleDict)
OUTPUT:

b. With the help of appropriate data organizations, get the details of N different
vehicles.
CODE:

vehicleList = []
N = int(input())
for i in range(N):
vehicleDict = {}
vehicleDict["vehicleName"]=input()
vehicleDict["Type"] = input()
vehicleDict["Weight"] = int(input())
vehicleDict["basicPrice"] = int(input())
vehicleDict["vehicleTax"] =
float(input())*vehicleDict["basicPrice"]
vehicleDict["weightTax"] = float(input())*vehicleDict["Weight"]
vehicleDict["insurance"] = float(input())*vehicleDict["basicPrice"]
vehicleDict["onRoadPrice"] = vehicleDict["basicPrice"] +
vehicleDict["vehicleTax"] + vehicleDict["weightTax"] +
vehicleDict["insurance"]
[Link](vehicleDict)
print(vehicleList)
OUTPUT:

c. Using the details collected in 3.b., find the vehicle/ vehicles that has/ have i.
The highest on-road price. ii. The least weight.
CODE:

vehicleList = []
N = int(input())
for i in range(N):
vehicleDict = {}
vehicleDict["vehicleName"]=input()
vehicleDict["Type"] = input()
vehicleDict["Weight"] = int(input())
vehicleDict["basicPrice"] = int(input())
vehicleDict["vehicleTax"] =
float(input())*vehicleDict["basicPrice"]
vehicleDict["weightTax"] = float(input())*vehicleDict["Weight"]
vehicleDict["insurance"] = float(input())*vehicleDict["basicPrice"]
vehicleDict["onRoadPrice"] = vehicleDict["basicPrice"] +
vehicleDict["vehicleTax"] + vehicleDict["weightTax"] +
vehicleDict["insurance"]
[Link](vehicleDict)
print(vehicleList)
ORP = []
highOrp = vehicleList[0]["onRoadPrice"]

weightList = []
leastWeight = vehicleList[0]["Weight"]
for i in range(len(vehicleList)):
if vehicleList[i]["Weight"] <= leastWeight:
leastWeight = vehicleList[i]["Weight"]
[Link](vehicleList[i]["vehicleName"])

for i in range(len(vehicleList)):
if vehicleList[i]["onRoadPrice"] >= highOrp:
highOrp = vehicleList[i]["onRoadPrice"]
[Link](vehicleList[i]["vehicleName"])

for i in ORP:
print("High ORP", i, end = " ")
for i in weightList:
print("least Weight", i, end = " ")
OUTPUT:

d. Using the details collected in 3.b., find the following details: -

i. The average on-road price.

ii. Count of vehicles that has highest on-road price than the average onroad
price.

CODE:

vehicleList = []
N = int(input())
for i in range(N):
vehicleDict = {}
vehicleDict["vehicleName"]=input()
vehicleDict["Type"] = input()
vehicleDict["Weight"] = int(input())
vehicleDict["basicPrice"] = int(input())
vehicleDict["vehicleTax"] =
float(input())*vehicleDict["basicPrice"]
vehicleDict["weightTax"] = float(input())*vehicleDict["Weight"]
vehicleDict["insurance"] = float(input())*vehicleDict["basicPrice"]
vehicleDict["onRoadPrice"] = vehicleDict["basicPrice"] +
vehicleDict["vehicleTax"] + vehicleDict["weightTax"] +
vehicleDict["insurance"]
[Link](vehicleDict)
print(vehicleList)
sumORP = 0
for i in range(len(vehicleList)):
sumORP = sumORP + vehicleList[i]["onRoadPrice"]
print(sumORP)

AVG_ORP = sumORP/N
print(AVG_ORP)

count = 0
for i in range(len(vehicleList)):
if vehicleList[i]["onRoadPrice"] > AVG_ORP:
count+=1
print(count)
OUTPUT:
iii. Count of vehicles that have weight above a given value.

iv. Count of vehicles that have on-road price less than or equal to a given
budget.

CODE:

vehicleList = []
N = int(input())
for i in range(N):
vehicleDict = {}
vehicleDict["vehicleName"]=input()
vehicleDict["Type"] = input()
vehicleDict["Weight"] = int(input())
vehicleDict["basicPrice"] = int(input())
vehicleDict["vehicleTax"] =
float(input())*vehicleDict["basicPrice"]
vehicleDict["weightTax"] = float(input())*vehicleDict["Weight"]
vehicleDict["insurance"] = float(input())*vehicleDict["basicPrice"]
vehicleDict["onRoadPrice"] = vehicleDict["basicPrice"] +
vehicleDict["vehicleTax"] + vehicleDict["weightTax"] +
vehicleDict["insurance"]
[Link](vehicleDict)
print(vehicleList)

count = 0
budget = int(input())
for i in range(len(vehicleList)):
if vehicleList[i]["onRoadPrice"] <= budget:
count+=1
print(count)

count1 = 0
weight = int(input())
for i in range(len(vehicleList)):
if vehicleList[i]["Weight"] > weight:
count1+=1
print(count1)
OUTPUT:
4. Mr. Anthony is very much concerned about the depletion of energy reserves and has
installed in his home both geyser and solar water heater in his bathroom. When the day is
hot and the solar heater is heating, the geyser remains off and when the day is cloudy, the
geyser is on. A day is considered hot if the temperature is more than 25 degree Celsius.
Read the temperature for the day and provide a message whether to use geyser or solar
water heater.
a. Update the above problem by reading the temperature values for N days and do
the following with the help of user-defined functions: -
i. Print the number of days on which geyser was used.
ii. Print the percentage of days on which solar water heater was used
CODE:

def heater(N):
global countSolar
global countGeyser
countGeyser = 0
countSolar = 0
for i in range(N):
temp = float(input())
if temp > 25.0:
countSolar+=1
elif temp <= 25.0:
countGeyser+=1
heater(5)
print(countGeyser, countSolar)
OUTPUT:

5. Michael works as a marketing executive and spends his whole day travelling around
getting orders for his company. Sometimes the trips are short and often times he has to
travel large distances on his two wheelers. He decides his outfit based on the climate so
that he is comfortable when he is at work. The decision is made as follows: If the day is
cold and it is snowing, he wears a parka. If it is cold and not snowing, he wears a jacket. If
the day is not cold, He wears formal outfit. Design an automatic decision making system to
help Michael to choose his outfit, given a list of day type combinations (cold and snowing).
CODE:
weather = input()
if weather == 'Cold and Snowing' or weather == 'COLD AND SNOWING' or weather
== 'cold and snowing':
print("Wear Parka")
elif weather == 'COLD' or weather == 'cold' or weather == 'Cold':
print("Wear Jacket")
else:
print("Wear Formal Outfit")
OUTPUT:

7. A person is eligible for obtaining Gas subsidy if he has submitted his Aadhar card or has
a bank account. ‘Efficient Gas Agency’ is in the process of verifying whether its consumers
have submitted either of the two documents and come up with a list whether a customer
is eligible for subsidy or not. The data sheet consists of Consumer Number, Consumer
Name, Aadhar card Submission status and Bank account number submission status.
Design a strategy to determine the list of consumers of Efficient Gas Agency who are
eligible for gas subsidy and those who are not.
CODE:
dataSheet = []
subsidyList = []
subsidyNotList = []
N = int(input("Number of Consumers: "))
for i in range(N):
consumerData = {}
consumerData["consumerNo"] = input()
consumerData["consumerName"] = input()
consumerData["statusAadhar"] = input("Aadhar submitted? (Y/N): ")
consumerData["statusACC_No"] = input("ACC_No. submitted? (Y/N): ")
[Link](consumerData)
for i in range(len(dataSheet)):
if dataSheet[i]["statusAadhar"]=='Y' or dataSheet[i]["statusACC_No"] ==
'Y':
[Link](dataSheet[i]["consumerName"])
else:
[Link](dataSheet[i]["consumerName"])
print(dataSheet)
print(subsidyNotList)
print(subsidyList)
OUTPUT:

8. The consistency of a soil can be determined by field tests in which the soil is evaluated
in place, or by lab tests on samples that have been carefully handled to avoid remoulding.
The unconfined compression test is often used as an indication of consistency. In practice,
the relative terms soft, medium, stiff, very stiff, and hard are applied to describe
consistency. Get the shear strength and classify soil into different consistencies Soft,
Medium Stiff, Stiff Very Stiff based on the table given below.
CODE:
shrStr = int(input())
if shrStr <= 24500:
print("Soft")
elif shrStr>24500 and shrStr<=49000:
print("Medium Stiff")
elif shrStr>49000 and shrStr<=98000:
print("Stiff")
elif shrStr>98000 and shrStr<=196000:
print("Very Stiff")
else:
print("Hard")
OUTPUT:

9. Suppose data giving the living areas and prices of houses from New Found Land are
given below. Based on the budget of a customer find the Living area he/she can afford.
CODE:
budget = int(input())
if budget>=1100000 and budget<1400000:
print("1500")
elif budget>=1400000 and budget<2100000:
print("2100")
elif budget>=210000:
print("3100")
OUTPUT:

11. You are arranging for a birthday treat at a famous restaurant. You plan to have a buffet
menu with different kinds of dishes. The menu card of the hotel includes the name of the
item and unit price. You choose to order varying quantities of almost each item based on
the choices of your friends. The hotel charges a fixed sales tax of 8% on cost of every single
piece of item ordered.
a. Given the menu item and price per item, input quantity of each item you wish to order
and compute ‘Sales Tax’ which indicates the sales tax applicable for the quantity of each
item ordered.
b. Compute the total amount applicable for each item and the overall bill for all the items.
c. In addition to ordering the menu items, you have requested the hotel to provide the
catering services for your Birthday function. The catering charges of the hotel are as
follows:
CODE:
menu={"Idly":15,"Dosa":50,"Biriyani":140,"Chapati":40,"Panner butter
Masala":250}
qtyIdly = int(input())
qtyDosa = int(input())
qtyBri = int(input())
qtyChap = int(input())
qtyPBM = int(input())
print("sale Tax of Idly", qtyIdly*0.08*menu["Idly"])
print("sale Tax of Dosa",qtyDosa*0.08*menu["Dosa"])
print("sale Tax of Briyani ", qtyBri*0.08*menu["Biriyani"])
print("sale Tax Chapati ", qtyChap*0.08*menu["Chapati"])
print("sale Tax of PBM", qtyPBM*0.08*menu["Panner butter Masala"])

print("tot amnt for idly ", qtyIdly*menu["Idly"] + qtyIdly*0.08*menu["Idly"] )


print("tot amnt of Dosa", qtyDosa*menu["Dosa"] + qtyDosa*0.08*menu["Dosa"])
print("tot amnt of Briyani ", qtyBri*menu["Biriyani"] +
qtyBri*0.08*menu["Biriyani"])
print("tot amnt of Chapati ", qtyChap*menu["Chapati"] +
qtyChap*0.08*menu["Chapati"])
print("tot amnt of PBM", qtyPBM*menu["Panner butter Masala"] +
qtyPBM*0.08*menu["Panner butter Masala"])
paperItems = 110.87
rentalEquip = 249.95

totalBill = qtyIdly*menu["Idly"]+qtyIdly*0.08*menu["Idly"]
+qtyDosa*menu["Dosa"] + qtyDosa*0.08*menu["Dosa"] + qtyBri*menu["Biriyani"] +
qtyBri*0.08*menu["Biriyani"] +qtyChap*menu["Chapati"] +
qtyChap*0.08*menu["Chapati"]+qtyPBM*menu["Panner butter Masala"] +
qtyPBM*0.08*menu["Panner butter Masala"]
serviceFee = 0.18*totalBill

print("The amnt for food", totalBill)


print("The total amnt to be paid",
round((totalBill+paperItems+rentalEquip+serviceFee),2))

OUTPUT:

12. Mr. Gopal Yadav runs an online site that rates movies released in India. The site rates
movies based on five aspects - Story, Screenplay, Acting, BGM/songs, and Direction. For
each movie, each of these aspects gets a score between 1 and 10. By default, the
weightage of each aspect is set as follows:-
CODE:
N = int(input())
movieList = []
for i in range(N):
movieDict={}
movieDict["movieName"] = input()
movieDict["stryrating"] = int(input())*0.3
movieDict["scrPlyRating"] = int(input())*0.2
movieDict["actRating"] = int(input())*0.2
movieDict["bgmRating"] = int(input())*0.1
movieDict["directRating"] = int(input())*0.2
movieDict["movieRating"] = movieDict["stryrating"] +
movieDict["scrPlyRating"] + movieDict["actRating"] +movieDict["bgmRating"] +
movieDict["directRating"]
movieDict["IMDB_Rating"] = float(input())
[Link](movieDict)

diffList = []
for i in range(len(movieList)):
[Link](movieList[i]["movieRating"] - movieList[i]["IMDB_Rating"])

for i in range(len(movieList)):
print("The difference in ratings", movieList[i]["movieName"],":",
diffList[i])

for i in range(len(movieList)):
movieList[i]["stryrating"]*0.2/0.3
movieList[i]["actRating"]*0.1/0.2
movieList[i]["directRating"]*0.4/0.2
movieDict["movieRating"] = movieDict["stryrating"] +
movieDict["scrPlyRating"] + movieDict["actRating"] +movieDict["bgmRating"] +
movieDict["directRating"]
print("The updated ratings", movieList[i]["movieName"], ":", movieList[i]
["movieRating"])
sum = 0
for i in range(len(movieList)):
sum = sum + movieList[i]["movieRating"]
avgRating = sum/len(movieList)
print("The AVG RATING", avgRating)
count = 0
for i in range(len(movieList)):
if movieList[i]["movieRating"] >= movieList[i]["IMDB_Rating"]:
count+=1
print(count)

OUTPUT:
13. Mr. Shamith has stored his weekly expenditure, refund and income for the months of
May and June. Help him to find out the following: -
a. Total Expenditure for each week, which is given as Expenditure minus Refund.
b. Average of Total expenditure for the eight weeks.
c. Profit earned in each week, which is equal to Income minus Total expenditure.
d. Count the number of weeks, with profit greater than $75.00
CODE:
N = int(input())
expList = []
refList = []
incList = []
totExpList = []
profList = []
for i in range(N):
[Link](int(input()))
[Link](int(input()))
[Link](int(input()))
[Link](expList[i] - refList[i])
[Link](incList[i] - totExpList[i])
print("The Avg TE : ", sum(totExpList)/len(totExpList))

for i in range(len(totExpList)):
print("The TE for week",i+1, totExpList[i])
print("The Profit for week",i+1, profList[i])

count = 0
for i in profList:
if i > 75.00:
count+=1
print(count)

OUTPUT:

14. Travelling details of 9 sales representatives of Amway is stored as a dictionary with


three fields – name, month and distance covered in that month. How will you find out the
following?
a. Total distance travelled by each sales rep.
b. Travelling expense for each sales rep., if travelling allowance is provided at the rate of
$0.65 per kilometre.
c. Average expense that the company must pay for a representative.
d. Maximum amount to be paid towards travelling expense for a given month.
CODE:
N = int(input())
saleRepList = []
for i in range(N):
salRepDict = {}
salRepDict["Name:"] = input()
salRepDict["Month"] = input()
salRepDict["dist"] = int(input())
[Link](salRepDict)

for i in range(len(saleRepList)):
print(saleRepList[i]["Name:"], "Travelled ",saleRepList[i]["dist"], "km
and Travelling Expense is $", round(saleRepList[i]["dist"]*0.65,2))
sumExp = 0
for i in range(len(saleRepList)):
sumExp = sumExp + saleRepList[i]["dist"]*0.65
avgExp = sumExp/N
print("The Avg Exp to be paid $", avgExp)
print("The Max Exp should be paid is $", sumExp)
OUTPUT:

15. Raj is the owner of a fruit store. He has owned the fruit store for one complete year.
He concentrates mainly on the selling of four types of fruits – Apples, Bananas, Oranges
and Grapes. He recorded the sales values for each of the four fruits per month. Help him
to find the answer for the following questions with the data available: -
a. Which fruit has the highest annual sales?
b. Which fruit has the lowest annual sales?
c. What is the average annual sale?
d. Raj wants to find out the number of months in which sales of Apples were less than
Rs.3000. How will you help him to find out answer?

CODE:
N = int(input())
frtList = []
saleList = []
for i in range(N):
frtDict = {}
frtDict["frtName"] = input()
for j in range(12):
[Link](int(input()))
frtDict["Sales"] = saleList
[Link](frtDict)

annualSales = []
for i in range(len(frtList)):
[Link](sum(frtList[i]["Sales"]))
print(annualSales)
print("The highest sold fruit is",
frtList[[Link](max(annualSales))]["frtName"])
print("The least sold fruit is", frtList[[Link](min(annualSales))]
["frtName"])

sumSale = 0
for i in range(len(frtList)):
sumSale = sumSale + sum(frtList[i]["Sales"])
avgSale = sumSale/N
print('The Avg Sale is ', avgSale)

count = 0
for i in range(N):
if frtList[i]["frtName"] == 'Apple':
for j in frtList[i]["Sales"]:
if j < 3000:
count+=1
print("The sales of apple were less than Rs 3000 for ", count, "Months")
OUTPUT:

16. You just got a job at Jimmy’s Skateboard Shop. You have a choice of two different
salary plans.
• Plan A Earnings: $120 per week plus 10% of sales
• Plan B Earnings: $90 per week plus 15% of sales
a. You can expect your average sales per week to be $400. Which salary plan is better?
b. For most retailers, the months of November and December bring in a lot more sales
than usual. If you can expect your average sales per week to be $1,000 during these two
months, then how would this influence your decision on which salary plan to go with?
CODE:
plnA = 120 + 0.1*400
plnB = 90 + 0.15*400
if plnA>plnB:
print('Plan A earnings is more')
elif(plnA<plnB):
print("Plan B earnings is more")
else:
print("Both A n B have same earnings")

annualEarnA = 44*plnA + 8*(120 + 0.1*1000)


annualEarnB = 44*plnB + 8*(90 + 0.15*1000)
if annualEarnA>annualEarnB:
print('Plan A earnings is more')
elif annualEarnA<annualEarnB:
print("Plan B earnings is more")
else:
print("Both A n B have same earnings")

OUTPUT:

In both the cases the earnings is high for plan A


17. In an election, there are seven candidates. The number of voters are unknown
beforehand. Each voter is allowed one vote. While casting the vote, the voter is allowed to
enter only the vote number. The vote number is 1 for candidate 1, 2 for candidate 2, 3 for
candidate 3, and so on. Any vote which is not a number from 1 to 7 is a spoilt vote. The
voting process is terminated by a vote of 0 (zero). Display the election results: count of
votes for each candidate, count of invalid votes, and the candidate with highest votes.
CODE:
vote1 = vote2 = vote3 = vote4 = vote5 = vote6 = vote7 = invalidVote = 0

while(True):
vote = int(input())
if vote==1:
vote1+=1
elif vote==2:
vote2+=1
elif vote==3:
vote3+=1
elif vote==4:
vote4+=1
elif vote ==5:
vote5+=1
elif vote==6:
vote6+=1
elif vote==7:
vote7+=1
elif vote==0:
break
else:
invalidVote+=1

canditateList = ['C1', 'C2', 'C3', 'C4','C5','C6','C7','Invalid_Vote']


voteList = [vote1,vote2,vote3,vote4,vote5,vote6,vote7,invalidVote]

for i in range(len(canditateList)):
print(canditateList[i],":", voteList[i])
print(canditateList[[Link](max(voteList))])
OUTPUT:

18. Billing of electrical charges needs to be automated. The number of customers who
have come to pay the charges are unknown beforehand. The data for each customer
consists of customer ID, name, consumer type, previous meter reading and present meter
reading. If the previous reading is greater than the current reading, an error memo is
generated. Each customer is permitted for only one billing. For the tariff given below for
Domestic and Non-residential supply, process the data and generate the bill for each
customer. In addition to billing, the program needs to also keep track of the following: the
number of bills generated, the number of error memos generated.
CODE:
error=0
bill=0
while(True):
custData = {}
custData["custID"] = int(input())
custData["Name"] = input()
custData["type"] = input()
custData["prevMR"] = int(input())
custData["presMR"] = int(input())
reading = custData["presMR"] - custData["prevMR"]
if custData["presMR"]<custData["prevMR"]:
print("Error")
error+=1
if custData["type"]=="Domestic":
if reading < 150:
custData["Charge"] = reading*2.55
elif reading>150 and reading<=400:
custData["Charge"] = 150*2.55 + ((reading-150)*4.8)
elif reading>400 and reading<1000:
custData["Charge"] = 150*2.55 + 250*4.8 + ((reading-400)*5)
bill+=1
else:
if reading < 150:
custData["Charge"] = reading*5
elif reading>150 and reading<=400:
custData["Charge"] = 150*5 + ((reading-150)*5.2)
elif reading>400 and reading<1000:
custData["Charge"] = 150*5 + 250*5.2 + ((reading-400)*5.45)
bill+=1
print([Link]())
print("Error Memo", error)
print("Bill ", bill)

OUTPUT:

You might also like