TCS PRA Exam Coding Questions
- Get link
- X
- Other Apps
TCS PRA Exam Coding Questions
findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks findyourkicks
Question 1
Create a class Payslip having attributes basicSalary,hra and ita.
Create a class PaySlipDemo containing a method getHighestPF with takes a list of payslip objects and return the highest PF among the objects.PF should be 12% of the basic salary
input:
2
10000
2000
1000
50000
3000
2000
output:
6000
Solution:
class Payslip:
def __init__(self,bs,h,t):
self.bs=bs
self.h=h
self.t=t
class Pd:
def __init__(self):
self.a=10
def getpf(self,l):
k=[]
for i in l:
a=i.bs*0.12
k.append(a)
k1=max(k)
return int(k1)
if __name__==’__main__’:
p=[]
c=input()
for i in range(c):
bs=input()
h=raw_input()
t=input()
p.append(Payslip(bs,h,t))
pa=Pd()
pf=pa.getpf(p)
print pf
TCS PRA Exam Coding Questions
Question 2
Create a class Stock having attributes StockName,StockSector,StockValue. Create a method getStockList with takes a list of Stock objects and a StockSector(string) and returns a list containing stocks of the given sector having value more than 500.
input:
3
TCS
IT
1000
INFY
IT
400
BMW
Auto
1200
IT
Output:
TCS
Solution:
class Stock:
def __init__(self,sn,ss,sv):
self.sn=sn
self.ss=ss
self.sv=sv
class StockDemo:
def __init__(self):
self.a=10
def gets(self,l,s):
k=[]
for i in l:
if(i.ss==s and i.sv>500):
k.append(i)
return k
if __name__==’__main__’:
c=input()
p=[]
for i in range(c):
sn=raw_input()
ss=raw_input()
sv=input()
o=Stock(sn,ss,sv)
p.append(o)
s=raw_input()
pra=StockDemo()
l=pra.gets(p,s)
for i in l:
print i.sn,i.sv
TCS PRA Exam Coding Questions
Question 3
Given passenger ID name gender distance
In last two lines they provide the passenger ID and discount percentage
We need to print the discount to be given for that particular passenger if that given Id is not in the list print no name or no value
input :
4
101
a
f
10000
102
b
m
12000
103
c
f
45000
104
d
m
65000
101
5
output:
discount of 101 is: 500.0
Solution 1(without class):
n=int(input())
k=[]
for i in range(n):
l=[]
l.append(input())
l.append(input())
l.append(input())
l.append(int(input()))
k.append(l)
key=input()
dis=int(input())
z=[]
for ind in range(n):
if(key==k[ind][0]):
z.append(ind)
if(len(z)==0):
print(“no id found”)
else:
i=z[0]
disc=k[i][3]*dis/100
if(disc>0):
print(‘discount of’,k[i][0],’is:’,disc)
else:
print(k[i][0],’is not eligible for discount’)
Solution 2(with class):
class Passenger:
def __init__(self,pid,pname,pgender,pmiles):
self.pid=pid
self.pname=pname
self.pgender=pgender
self.pmiles=pmiles
def calculate_discount(self,pid,discount_rate):
for i in pass_list:
if i.pid==pid:
discount=(i.pmiles*discount_rate)/100
return discount
class Organisation(Passenger):
def __init__(self,oname,pass_list):
self.oname=oname
self.pass_list=pass_list
if __name__ == ‘__main__’:
n=int(input())
pass_list=[]
for i in range(n):
pid=input()
pname=input()
pgender=input()
pmiles=int(input())
pass_list.append(Passenger(pid,pname,pgender,pmiles))
pid=input()
discount_rate=int(input())
o=Organisation(‘TCS’,pass_list)
discount=o.calculate_discount(pid,discount_rate)
if discount<0:
print(“Passenger not eligible for discount”)
else:
print(“The discount of passenger “+pid+” is ” +str(discount))
TCS PRA Exam Coding Questions
Question 4
Take list of employees (id, name and leaves (el, sl, cl).
For a particular employee… Demand a leave from available leave types…
Return available leaves…If available is greater than or equal to demand, return ‘Granted’, else ‘Rejected’.
Solution:
class Employee:
def _init_(self,emp_no,emp_name,leaves):
self.emp_no=emp_no
self.emp_name=emp_name
self.leaves=leaves
class Company:
def _init_(self,company_name,emps):
self.company_name=company_name
self.emps=emps
def display_leave(self,emp_no1,Ltype):
for i in self.emps:
if i.emp_no==emp_no1:
return i.leaves[Ltype]
def Number_of_leaves(self,emp_no1,Ltype,nol):
for i in self.emps:
if i.emp_no==emp_no1:
if i.leaves[Ltype]>=nol:
return “Granted”
else:
return “Rejected”
n=int(input())
emps=[]
c=Company(“ABC”,emps)
leaves={}
for i in range(n):
emp_no=int(input())
emp_name=input()
leaves[“CL”]=int(input())
leaves[“EL”]=int(input())
leaves[“SL”]=int(input())
c.emps.append(Employee(emp_no,emp_name,leaves))
emp_no1=int(input())
Ltype=input()
nol=int(input())
print(c.display_leave(emp_no1,Ltype))
print(c.Number_of_leaves(emp_no1,Ltype,nol))
TCS PRA Exam Coding Questions
Question 5
Create a class employee with attributes
emp Id,
emp name,
emp role,
emp salary
In the same class,define method increment_salary() which takes number as an argument, here number represents the percentage by which the salary should be incremented.
Create another class organization with attributes org_name and list of employee objects
In the same class create a method calculate_salary() which takes string and number as the input arguments.string input represents the employee role and number represents the percentage by which the salary should be incremented,return list of employee objects whose salary has incremented.
Note: use increment_salary method in this method
Input:
4
100
rajesh
developer
40000
101
ayesha
developer
41000
102
hari
analyst
45000
103
amar
manager
60000
developer
5
Output:
rajesh
42000.0
ayesha
43050.0
Solution:
class Employee:
def __init__(self,id,name,role,salary):
self.emp_id=id
self.emp_name=name
self.emp_role=role
self.emp_salary=salary
def increse_salary(self,no):
self.emp_salary+=self.emp_salary*(no/100)
class Organisation:
def __init__(self,oname,elist):
self.org_name=name
self.emp_list=elist
def calculate_salary(self,role,percentage):
result=[]
for i in self.emp_list:
if(i.emp_role==role):
i.increse_salary(percetage)
result.append(i)
return result
if __name__ == ‘__main__’:
count=int(input())
emp_l=[]
for i in range(count):
id=int(input())
name=input()
role=input()
salary=int(input())
emp_l.append(Employee(id,name,role,salary))
o=Organisation(“XYZ”,emp_l)
role=input()
percentage=int(input())
result=o.calculate_salary(role,percentage)
for i in result:
print(i.emp_name)
print(i.emp_salary)
TCS PRA Exam Coding Questions
Question 6
Make a Class Item having 4 attributes- item_id, item_name, item_price and quantity_available.It has a Method calc_price() that takes a number ‘quantity’ is argument and checks if the provided quantity is greater than or equal to quantity_available attribute. If so, it returns the total price as (quantity * item_price). Otherwise, it returns 0.
Create another class Store that has one attribute item_list (list of Item objects).
It has a method generate_bill() that takes a dictionary having (item_name: quantity). It returns total price for the items in the dictionary if available in store. It uses calc_price() method of item class
Solution:
class Item:
def __init__(self,a,b,c,d):
self.iid=a
self.name=b
self.price=c
self.quant=d
def calc(self,n):
if self.quant>=n
return self.price*n
else:
return 0
class Store:
def __init__(self,l):
self.list1=l
def gen_bill(self,d):
s=0
for a,b in d.items():
for i in range(len(self.list1)):
if self.list1[i].name==a:
s+= self.list1[i].calc(b)
return s
if __name__==’__main__’:
l=[]
c=int(input())
for _ in range (c):
i=Item(int(input()),input(),int(input()),int(input()))
l.append(i)
s=Store(l)
d={}
for _ in range(int(input())):
n=input()
q=int(input())
d[n]=q
print(l[0].calc(2))
print(s.gen_bill(d))
TCS PRA Exam Coding Questions
Question 7
Class Book – has 2 attributes – book_id and book_name. Has a constructor.
Class Library – has 3 attributes – library_id, address and a list of book objects. Has 2 functions.
1.One gets a character as input and returns the count of books starting with that character.
2.Second function takes a list of book names as input and removes those books from library if present.
input:
3
100
C++ Programming
200
Introduction to SQL
300
Core Java
C
2
Introduction to SQL
Python Programming
Output:
2
C++ Programming
Core Java
Solution:
class Book:
def __init__(self,bn,bname):
self.bn=bn
self.bname=bname
class Library:
def __init__(self,lid,add,bl):
self.lid=lid
self.add=add
self.bl=bl
def count_books(self,char):
c=0
for i in self.bl:
if(i.bname[0]==char):
c+=1
return c
def remove_books(self,names):
for i in self.bl:
if i.bname not in names:
print(i.bname)
if __name__==’__main__’:
bl=[]
t=input()
for i in range(t):
bn=input()
bname=raw_input()
bl.append(Book(bn,bname))
l=Library(123,’Mumbai’,bl)
char=raw_input()
names=[]
t=input()
for i in range(t):
names.append(raw_input())
print l.count_books(char)
l.remove_books(names)
Question 8
Create a class Bill with attributes mobile number and payment bill.Create another class mobile with attributes service provider, mobile number, data used, payment method.
Service provider maybe airtel or jio. Data used is integer values in Gigabytes(GB). Payment method maybe paytm,gpay,amazon and so on.
Create a method calculate bill that takes the list of objects and calculates the bill and returns the list of objects of class bill with mobile number and payment bill.
The payment is calculated as follows:
1.If the service provider is airtel, the bill is Rs.11 for every 1GB used and if it is jio, the bill is Rs.10 for every 1GB used.
2. If the payment method is paytm there is a cashback of 10% of the total bill for airtel users only. The bill is calculated and rounded off after deducing the cashback value.
input:
3(No of objects to be created)
airtel
123
16
paytm
airtel
456
10
amazon
jio
788
10
paytm
Output:(123,158)
(456,110)
(789,100)
Solution:
class Bill:
def __init__(self,no,b):
self.no=no
self.b=b
class Mob:
def __init__(self,sp,no,net,p):
self.sp=sp
self.no=no
self.net=net
self.p=p
def calc(self,l):
m=[]
for i in l:
if i.sp==”airtel”:
b=i.net*11
if i.p==”paytm”:
b-=(0.1*b)
elif i.sp==”jio”:
b=i.net*10
m.append(Bill(i.no,int(b)))
return m
if __name__==’__main__’:
l=[]
count=input()
for i in range(count):
sp=raw_input()
no=input()
net=input()
p=raw_input()
l.append(Mob(sp,no,net,p))
demo=Mob(“”,0,0,””)
m=demo.calc(l)
for i in m:
print i.no,i.b
Question 9:
Create a class Doctor with below attributes:
doctorId – Numeric type
doctorName – String type
specialization – String type
consultationFee – Numeric type
doctorId represents the unique identification number of a Doctor object.
doctorName represents the name of the doctor.
specialization represents the doctor specialization and consultationFee represents the doctors fee.
Define the __init__ method to initialize the attributes in the above sequence.
Create a class Hospital with below attribute:
doctorDB – is of type dictionary with Doctor objects [ Serial number of a Doctor in the Hospital and the respective Doctor object as a key : value pair ]
Define the __init__ method to initialize the dictionary attribute in the Hospital class . It initializes the dictionary of Doctor objects in the Hospital class with the dictionary supplied from main program while creating the Hospital object.
The Dictionary( with Doctor serial number and the respective Doctor object as key : value pair ) is created and filled in main program by adding each Doctor object. This Doctor object is created with the input data related to a respective Doctor object . This dictionary after filling to be passed as an argument to the Hospital constructor and this will be initialized to doctorDB dictionary with in the Hospital class.
Define two methods – searchByDoctorName and calculateConsultationFeeBySpecialization in Hospital class.
searchByDoctorName:
This method will take Doctor name as a parameter, find the respective Doctor object based on the doctor name given and return to main function with a list of Doctor objects, whose name matches with the given name, supplied as an argument.
If there is no Doctor found with the given name then return None to main program and display the message “No Doctor Exists with the given DoctorName” in the main function.
Hint:
a. Use the dictionary, doctorDB in Hospital object to find out the Doctor object(s) based on the given Doctor name.
b. Display the Doctor object /list of doctor objects (returned by this function) in the main function – Refer sample testcase below for more details
calculateConsultationFeeBySpecialization:
This method will take a Doctor specialization as parameter and return the total consultationFee of all the Doctors ,whose specialization is same as supplied as an argument from the main program.
If there is no Doctor found with the given specialization then return 0 to main program and display the message “No Doctor with the given specialization” in the main function, excluding the double quotes
These two methods(described above) should be called from the main function / program and in the above order.
Hint
a. Use the dictionary, doctorDB in hospital to get the consultation fee of each of Doctor (Doctor object in the Hospital ) for the given specialization supplied as argument .
b.Display the Total Fee in the in the main function – Refer sample testcase below for more details
Instructions to implement Main function:
a. You would required to write the main program completely, hence please follow the below instructions for the same.
b. You would required to write the main program, inlign to the sample input data mentioned below and to read the same .
c. Create the respective objects(Doctor and Hospital)
i.Create a Doctor object after reading the data related to one Doctor and add the doctor object to Doctors dictionary with Serial number and Doctor object as key:value pair.
ii.Repeat above point for the total number of Doctor objects , read in the first line of input data.
iii. Create a Hospital Object with the dictionary of Doctor objects, created in the previous step (c.i)
d. Call the methods ( searchByDoctorName and calculateConsultationFeeBySpecialization) mentioned above in the same order , they appear in the question text from main function .
e. Display the data returned by the functions , in the main program as per the format mentioned in the sample output.
If no Doctor exists with the given name(return value None from the respective function )then display the message “No Doctor Exists with the given DoctorName” in the main function, excluding the double quotes.
If no Doctor exists with the given specialization (return value 0 from the respective function )then display the message “No Doctor with the given specialization” in the main function, excluding the double quotes.
Sample Input (below) data description:
1.The 1st input taken in the main section is the number of Doctor objects to be created and added to the dictionary of Doctors in the Main program
2.The next set of inputs are the doctorId, doctorName, specialization and consultationFee of first Doctor
3. For each Doctor object repeat point#2 and this point is repeated for number of Doctor objects given in the first line of input
4.The last but one line of input refers the doctorName to be searched ie an argument for searchByDoctorName function
5. Last line of input represents the specialization, supplied as an argument to calculateConsultationFeeBySpecialization function, to get the total consultationFee of all the Doctors for a given specialization.
Sample Input :
5
90901
GovindRajulu
ENT
500
90902
Madhuri
Dermatologist
700
90903
Divya
Gynaecologist
600
90904
Suryam
Cardiologist
900
90905
Madhuri
Cardiologist
1000
Madhuri
Cardiologist
Output :
90902
Madhuri
Dermatologist
700
90905
Madhuri
Cardiologist
1000
1900
Solutions:
class Doctor:
def __init__(self,docid,docname,specs,fee):
self.docid=docid
self.docname=docname
self.specs=specs
self.fee=fee
class Hospital:
def __init__(self,doc):
self.doctorDB=doc
def searchByDoctorName(self,name):
l=[]
for i in doctorDB.keys():
if doctorDB[i].docname==name:
l=l+[doctorDB[i]]
return l
def calculateConsultationFeeBySpecialization(self,spec):
s=0
for i in doctorDB.keys():
if doctorDB[i].specs==spec:
s=s+doctorDB[i].fee
return s
if __name__ == ‘__main__’:
n=int(input())
lst=[]
for i in range(n):
did=int(input())
name=input()
spec=input()
fee=int(input())
d=Doctor(did,name,spec,fee)
lst=lst+[d]
searchname=input()
searchspec=input()
doctorDB={}
c=1
for i in lst:
doctorDB[c]=i
c=c+1
h=Hospital(doctorDB)
rname=h.searchByDoctorName(searchname)
rspec=h.calculateConsultationFeeBySpecialization(searchspec)
if len(rname)==0:
print(‘No Doctor Exists with the given DoctorName’)
else:
for i in rname:
print(i.docid)
print(i.docname)
print(i.specs)
print(i.fee)
if rspec==0:
print(‘No Doctor with given sepcialization’)
else:
print(rspec)
Question 10
Create a class ParkedVehicle with below attributes:
vehicleSeq –Integer type
fourWheeler – String type
parkedFor – float type
valetParking – String type
parkedStatus – String type
vehicleSeq represents a unique identification number for each of the parked vehicle
fourWheeler represents if the vehicle is a four wheeler or Not (“Yes“ / “No“ are the possible values)
parkedFor represents the number of hours for which the vehicle was parked
valetParking – if the vehicle is parked using valet parking (“Yes“ / “No“ are the possible values)
parkedStatus represents if the vehicle is “Parked“ or “Cleared“
Define the __init__ method to initialize all the attributes (mentioned above, in the sequence ) except parkedStatus. The parkedStatus will be set as default argument with a value “Parked” in the constructor during the respective object creation.
The constructor will be called from main function. The input data read in the main function and supplied to constructor as mentioned in the above line and in the sequence mentioned.
Create a class ParkingLot with below attributes:
parkd_vehicles – is of type dictionary with ParkedVehicle objects [parking lot_number ( an integer ) and the respective ParkedVehicle object as a key : value pair ]
Define the __init__ method to initialize the dictionary attribute in the class
It initializes the dictionary (parkd_vehicles) of ParkedVehicle objects in the ParkingLot class with the dictionary supplied from main program, while creating the ParkingLot object.
Note: The dictionary is created and filled in main program by adding each ParkedVehicle object(which is created with the input data related to the respective ParkedVehicle )and
passed as an argument to the constructor of ParkingLot class and this will be initialized to parkd_vehicles dictionary attribute of the ParkingLot class
Define two methods – updateParkedStatus and getParkingCharges in ParkingLot class.
Method 1: updateParkedStatus:
This method takes one parameter “lot_number“ , which represents the lot number in which the respective vehicle is parked(ParkedVehicle object) and update the “parkedStatus“ attribute of the respective ParkedVehicle object ( in the parkd_vehicles dictionary in ParkedLot class ) to ‘Cleared’.
This method makes use of the parkd_vehicles (dictionary of ParkedVehicle objects) in the ParkingLot class to find the ParkedVehicle in the given lot number and updates the parkedStatus to “Cleared”.
The method should return a tuple where key is the given lot_number (supplied as parameter ) and the value is the updated parkedStatus of the respective ParkedVehicle object, which is “Cleared” .
Ex:- (56, ParkedVehicle_obj.parkedStatus)
Display the Lot number and status (returned by this function) in the main function. Refer the sample output for display format
If the given lot number is not found in the “parkd_vehicles“ dictionary attribute, return None to the main function and accordingly display “Lot Number Invalid” in main function.
Method2: getParkingCharges:
This method will take lot_number as parameter and return the parking charges of the ParkedVehicle object associated with the lot number given. (use the “parkd_vehicles“ attribute in the ParkingLot class). Refer Parking charges calculation below.
If the given lot number is found then calcute the parking charges and return to main function. Display the parking charges returned by this function in the main function. Refer the sample output for display format .
If the given lot number is not found in the “parkd_vehicles“ dictionary attribute, return None to the main function and accordingly display “Lot Number Invalid” in main function.
Important instruction:
Use the same lot number (which is supplied as a parameter to updateParkedStatus function) as a parameter to this function as well.
Parking Charges rules and calculation:
a.Parking is charged on an hourly basis.
b.For a four wheeler, then charge Rs 50 per hour and if the vehicle is not a four wheeler then charge Rs 30 per hour.
c. If valetParking service is used then Rs10 is added to the total parking charges.
d. parkedFor attribute of the respective ParkedVehicle object represents the number of parking hours of the respective parked vehicle.
Case1: if fourWheeler attribute value of the respective ParkedVehicle object is “Yes“ then the parking charges calculated as below;
Parking charges = Charge per hour for four wheeler * ParkedVehicle_obj.parkedFor
Ex: If four wheeler is parked for 5 hours , the parking charge = 50.0 * 5=250.0
If valetParking attribute for the respective ParkedVehicle object is “Yes“ then add Rs10 to the parking charges ie 250.0+10=260.0
Case2: if fourWheeler attribute value of the respective ParkedVehicle object is “No“ then the parking charges are calculated as below:
Parking charges =Charge per hour for Non four wheeler * ParkedVehicle_obj.parkedFor
Ex: If Non four wheeler is parked for 3 hours ; the charges are = 30.0 * 3= 90.0
If valetParking attribute for the respective ParkedVehicle object is “Yes“ then add Rs10 to the parking charges ie 90.0+10=100.0
The two methods should be called from the main function / program in the same sequence as above
Use the dictionary parkd_vehicles in ParkingLot object to find out the parked vehicle object for a given lot number[ by comparing the lot number given with the lot number in the parkd_vehicles].
Instructions to write main and to call the methods of the classes defined above:
a. You would required to write the main program completely, Please follow the below instructions for the same.
b. You would required to write the main program which is inlign to the sample input data section mentioned below and to read the same
c. Create the respective objects(ParkedVehicle and ParkingLot) with the given sequence of arguments to fulfill the constructor requirement defined in the respective classes.
i.Create a ParkedVehicle object after reading the data related to ParkedVehicle and add the ParkedVehicle object to ParkedVehicle dictionary,
where lot_number and Parked vehicle object as a key:value pair. This point repeats for the number of ParkedVechicle objects you want to create and add to parked vehicles dictionary.
ii. Create parkingLot object with the dictionary of ParkedVehicle objects ( created as mentioned in above point# c.i ), as an argument.
d. Call the methods ( updateParkedStatus and getParkingCharges ) mentioned above from the main function in the same order , they appear in the question text.
e. Display the data returned by the functions , in the main program as per the format mentioned in the sample output.
f. If None is returned by any or both of the above functions, indicating that the given lot number does not exists , then display the message “Lot Number Invalid”(excluding the double quotes) in the main function.
Sample Input (below) description:
i. The 1st input taken in the main section is the number of ParkedVehicle objects to be added to the dictionary of ParkedVehicle Objects
ii. The next set of inputs are the vehicleSeq, fourWheeler, parkedFor , valetParking and the lot_number of the ParkedVehicle taken one after other for each ParkedVehicle object and is repeated for number of ParkedVehicle objects given in the first line of input
iii. Last line of input represents the lot_number supplied as a argument to updateParkedStatus function and getParkingCharges function, to find the respective vechcle object ,parked in the given lot number and to return the data as mentioend in the functions specifications above.
Sample Input :
4
1
Yes
2.5
Yes
87
2
No
3.5
No
123
3
Yes
1.5
No
56
4
Yes
2
Yes
104
87
Sample Output :
87 Cleared
135.0
Please note that the first line in the output represents the lot number and the parkedStatus
Second line in the output represents the total parking charge for the parked vehicle, parked in the above lot number before clearing.
Solutions:
class ParkedVehicle:
def __init__(self,vs,fw,pf,vp):
self.vehicleSeq=vs
self.fourWheeler=fw
self.parkedFor=pf
self.valetParking=vp
self.parkedStatus=”Parked”
class ParkingLot:
def __init__(self,parkd_vehicles):
self.parkd_vehicles=parkd_vehicles
def updateParkedStatus(self,lot_number):
if lot_number in self.parkd_vehicles.keys():
self.parkd_vehicles[lot_number].parkedStatus=”Cleared”
status=(lot_number,”Cleared”)
return status
else:
return None
def getParkingCharges(self,lot_number):
if lot_number in self.parkd_vehicles.keys():
charge=0
if self.parkd_vehicles[lot_number].fourWheeler==”Yes”:
charge=charge+(50*self.parkd_vehicles[lot_number].parkedFor)
else:
charge=charge+(30*self.parkd_vehicles[lot_number].parkedFor)
if self.parkd_vehicles[lot_number].valetParking==”Yes”:
charge=charge+10
return charge
else:
return None
if __name__ == ‘__main__’:
n=int(input())
vehicleDict={}
for i in range(n):
vs=int(input())
fw=input()
pf=float(input())
vp=input()
lotnum=int(input())
p=ParkedVehicle(vs,fw,pf,vp)
vehicleDict[lotnum]=p
parkingLot=ParkingLot(vehicleDict)
lotnum=int(input())
status=parkingLot.updateParkedStatus(lotnum)
charge=parkingLot.getParkingCharges(lotnum)
if status==None:
print(“Lot Number Invalid”)
print(“Lot Number Invalid”)
else:
print(status[0],status[1])
print(charge)
Question 11:Online Vegetable Store
Create a class Vegetable with the below attributes:
name of type String name of the vegetable price of type float //price ( in Rupees ) of the Fx: Kilogram quantity of type int ,/ quantity — number of units / Number of Kilograms
Create the init method which takes all parameters in the above sequence. The method should set the value of attributes with the parameter values received from main function.
Create another class Store with the below attribute: storeName of type String /specifies the vegList of type List L ist of Vegetable which takes all sequence. The method should set the value of attributes with the parameter values received from main.
Create method inside the Store class with name categorizeVegetablesAlphabetically
This method use and traverse the list of Vegetables(vegList) and returns a dictionary of alphabetically categorized and sorted vegetable names(name), where in key represent an alphabet character(e.g. ‘a’, ‘b’, se etc) and value represents a tuple, containing vegetable names that starts with that specific character as per key. Both the keys and values are sorted in alphabetically. The comparison needs to be case insensitive. If there are more vegetable names starts with the respective alphabet (which is acting as the key for the respective tuple of vegetable names), then the list of vegitable names also needs to be sorted.
e.g. Ex on fruits, resultant dictionary data looks like : fas:(‘ananas’, ‘apple), ’13: (‘banana’), ‘p’:(‘pineapple)) Here ‘a’ ,’b’ and ‘p’ (excluding the single quote ) represents the keys of dictionary and (‘ananass, ‘apple), (‘banana’), (pineapple’) ,excluding the ‘single quote and brackets’ represents the tuple for respective and corresponding keys(a , b, p ).
For more details refer the sample test case input and respective output
Create another method inside Store class with the name filterVegetablesForPriceRange This method takes minimum price and maximum price in Rupees as input parameters and return a list of alphabetically sorted vegetable names(name), where in the Vegetable unit price falls in the given range(minimum price and maximum price). This method use and traverse the list of Vegetables(vegList) for comparing the price of vegetable per Unit with the given range
If there is no vegetable in given price range, the method returns an empty list and based on the value main function should print “No Vegetable(s) in the given price range” (Excluding the double quotes) .
For more details refer the sample test case input and respective output
You can use/refer the below given sample input and output to verify your solution using ‘ Custom Input ‘ option ,down the coding editor
Instructions to write main and to call the methods of the classes defined above:
a. You would required to write the main function completely, please follow the below instructions for the same.
b. You would required to write the main program which is inlign to the “sample input description section” mentioned below and to read the data in the same sequence.
c. Create the respective objects(Vegetable and Store) with the given sequence of arguments to fulfill the constructor requirement defined in the respective class.
i.Create a Vegetable object after reading the data related to Vegetable and add the Vegetable object to list of Vegetable objects, This point repeats for the number of Vegetable objects you want to create and add to Vegetable list or as mentioned in the first line of input in the input data
ii. Create Store object by passing the Store name and list of Vegetable objects ( created and as mentioned in above point# c.i ) as the arguments to the constructor .
d. Call the methods ( categorizeVegetablesAlphabetically and f ilterVegetablesForPriceRange) mentioned above from the main function in the same order , they appear in the question text. e. Display the data returned by the functions , in the main program as per the order of calling the functions and as per the format mentioned in the sample output. f. If None/empty list is returned.
y 1 terVegeta function then display “No Vegetable found for given prince range” (excluding the double quotes) in the main function.
Sample Input (below) description:
• The first input line represents the count of vegetable objects to create and add to the vegetable list.
• Second set of inputs lines(2nd to 4th ) represents vegetable name, vegetable price and quantity of first vegetable object and this set(Name,Price and Quantity for each different vegetable object ) of input is repeated for the number of vegetable objects mentioned in the first line of input .
• Next inputs represents store name(third line of input from last).
• Last two lines represents the minimum price and maximum price to be supplied to the filterVegetablesForPriceRange to find the vegitables, whose price falls in the range
Sample Testcase Input:
5
corn
20.0
30
onion
10.0
15
potato
30.0
10
cucumber
5.0
10
brocolli
24.5
8
big
bazaar
5.0
25.0
SampleTestcaseOutput:
b
brocolli
c
corn
cucumber
0
onion
P
potato
5.0-25.0
brocolli
corn
cucumber
onion
Solutions:
import string
class Vegetable:
def __init__(self, n, p, q):
self.name = n
self.price = p
self.quantity = q
class Store:
def __init__(self, s, v):
self.storeName = s
self.vegList = v
def categorizeVegetablesAlphabetically(self):
self.vegList.sort(key= lambda x: x.name)
a = list(string.ascii_lowercase)
r = {}
for i in a:
temp = []
for j in self.vegList:
if i == j.name[0]:
temp.append(j.name)
if len(temp) >0:
r[i] = tuple(temp)
return r
def filterVegetablesForPriceRange(self, min, max):
self.vegList.sort(key= lambda x: x.name)
r = []
for i in self.vegList:
if min <= i.price <= max: r.append(i.name) return r count = int(input()) t = [] for i in range(count): n1 = input() p1 = float(input()) q1 = int(input()) v = Vegetable(n1.lower(),p1,q1) t.append(v) name = input() min1 = float(input()) max1 = float(input()) store = Store(name,t) catVegAlpha = store.categorizeVegetablesAlphabetically() priceList = store.filterVegetablesForPriceRange(min1, max1) for keys, value in catVegAlpha.items(): print(keys) for x in value: print(x) print(str(min1) + ‘-‘ + str(max1)) if len(priceList) > 0:
for x in priceList:
print(x)
else:
print(“No Vegetable(s) in the given price range”)
Question 12:Create a class FoodItem with the below attributes:
item_id of type Number
item_name of type String
item_category of type String
item_price of type Number
Create the init method which takes all parameters in the above sequence. The method should set the value of attributes to parameter values.
Create a method inside the class with the name provideDiscount. This method takes a Number value as argument which is the percentage by which the item price should be discounted and discounts the item price of the food item by the given percentage amount. Returns the updated price of the given item.
e.g. If the food item price is 100 and the given percentage is 10, then the updated price of the food item should be 90.Create another class Restaurant with the below attributes:
restaurant_name of type String
fooditem_list of type List having Foodltem objects
Create the init method which takes all parameters in the above sequence. The method should set the value of attributes to parameter values inside the method.
Create another method inside the class with the name retrieveUpdatedPrice. The method takes the update percentage as first argument and item id as the second argument . The method should find the respective food item, whose item id is given as in the argument , discount the price as per the given percentage and return the respective Foodltem object.
If the food item with given item id is not found , then the method returns None . Note: In Python None means NULL Object , Accordingly default maiN will display the message ‘No Food item exists which matches the search criteria’ (excluding the quotes)
If the update discount percent (argument to this function) is less than equals to zero , then return the object as it is , means there would not be any changes to the price.
Note: Use the method provideDiscount defined in the Foodltem class to calculate the discount price of the food items .
Instructions to write the main section of the code:
a. You would require to write the main section completely, hence please follow the below instructions for the same.
b. You would require to write the main program which is inline to the “sample input description section” mentioned below and to read the data in the same sequence.
c. Create the respective objects(Foodltem and Restaurant) with the given sequence of arguments to fulfill the Unit_ method requirement defined in the respective classes referring to the below instructions. i. Create a Foodltem object after reading the data related to it and add the object to the list of Foodltem objects which will be provided to the Restaurant class.This point repeats for the number of Foodltem objects(considered in the first line of input) . ii. Create Restaurant object by passing the Restaurant name(you can hard-code any name you want)and List of Foodltem objects ( created and as mentioned in above point# c.i ) as the arguments.
d. Take two number values as input depicting the item_id and the discount percentage to be provided as arguments to the method retrieveUpdatedPrice. e. Call the method retrieveUpdatedPrice mentioned above from the main section.
e. Display the Item Name and the Item Price separated by a ‘-‘ from the returned Foodltem object. Please refer to the sample output for more clarity on the display format.
f. If None is returned by the method retrieveUpdatedPrice ,then display the message No Food item exists which matches the search criterialexcluding the quotes).
•Input Format For Custom Testing
The 1st input taken in the main section is the number of Foodltem objects to be added to the list of FoodItems.
The next set of inputs are the item id, item name, item category and item price for each food item taken one after other and is repeated for number of objects given in the first line of input
The last but one line of input refers the item id , whose price needs to be discounted with the given percentage , mentioned in the last line
Sample Input
4
11
Pulao
Indian
80
12
Bhel
Snacks
50
13
Pasta
Italian
160
14
Burrito
Mexican
140
12
20
Sample Output
class FoodItem:
def __init__(self,i,name,category,price):
self.item_id = i
self.item_name = name
self.item_category = category
self.item_price = price
def provideDiscount(self,p):
if p>0:
self.item_price-=(self.item_price*p/100)
class Restaurant:
def __init__(self, name, list):
self.restaurant_name = name
self.fooditem_list = list
def retrieveUpdatedPrice(self,i,p):
for food in self.fooditem_list:
if(food.item_id == i):
food.provideDiscount(p)
return food
return None
if __name__==’__main__’:
number=int(input())
fooditem_list=[]
for _ in range(number):
item_id=int(input())
item_name=input()
item_category=input()
item_price=int(input())
fooditem_list.append(FoodItem(item_id,item_name,item_category,item_price))
Rest=Restaurant(“name”,fooditem_list)
item_id=int(input())
percentage=int(input())
result=Rest.retrieveUpdatedPrice(item_id,percentage)
if result==None:
print(“No Food item exists which matches the search criteria”)
else:
print(result.item_name,result.item_price,sep=” – “)
- Get link
- X
- Other Apps
Comments
Post a Comment