In: Computer Science
Python - No libraries - No count() function allowed
You need to travel 100 miles via rental car. There are several cars on the lot to choose from, each with their own MPG (miles per gallon) rating. Some cars have a manual transmission, while others do not (they're automatic). The price for gas in the area is $3 per gallon. Cars that have a manual transmission get a 10% discount at the pump.
To streamline your selection, the car rental place can supply you with a dictionary that represents the cars on their lot. The keys of this dictionary are names of cars, and their values are another dictionary. The inner dictionary has a key for the MPG of this car, and a key for whether or not the car is manual.
Write a function called def cheapest(cars) that returns the name of the car that costs the least amount of money to travel 100 miles.
Here is an example (there could be more than just two cars):
cars_on_lot = {'Civic':{'mpg':40,'manual':True},'Volt':{'mpg':50,'manual':False}}
print(cheapest(cars_on_lot)) # Volt
The "Civic" gets 40 miles to the gallon and is a manual transmission. 100 miles in this car requires 2.5 gallons of gas. The manual transmission deduction is $0.75. Therefore, it costs $6.75 to travel 100 miles in this car.
The "Volt" gets 50 miles to the gallon but is not a manual transmission. 100 miles in this car requires 2 gallons of gas. There is no manual transmission deduction. Therefore, it costs $6 to travel 100 miles in this car.
Of these two options, the Volt is the cheapest car you can use to travel 100 miles.
Source code:
def cheapest(cars_on_lot):
result="" #for storing result
g=0 #for stroing gallons
cost=0 #for calculating cost
minimum=65535
for car in cars_on_lot:
a=cars_on_lot[car]
speed=a['mpg']
m=a['manual']
g=(100.0/speed)
cost=g*3;
# if car is manual applying 10% discount
if(m):
cost=cost-(cost*0.10)
# finding minimum cost
if(cost<minimum):
minimum=cost
#cor with minimum cost
result=car
return result
cars_on_lot =
{'Civic':{'mpg':40,'manual':True},'Volt':{'mpg':50,'manual':False}}
#calling function
print(cheapest(cars_on_lot))
Code screenshot:
Output: