Reputation: 21
I need to write a program that calculates the cheapest combination of big and small bus to transport a certain number of passengers, which is given by the user. A big bus carries 48 passengers and is $200 to hire and a small bus carries 10 passengers and is $95 to hire. I have a solution that calculates a number of big and small buses but I have no clue how to factor in the cost side of things. This is the code I have so far:
passengers = int(input("How many passengers? "))
bigBus = 0
smallBus = 0
while passengers > 0:
if passengers / 48 > 1:
passengers -= 48
bigBus += 1
else:
passengers -= 10
smallBus += 1
cost = (bigBus * 200) + (smallBus * 95)
print("Hire", bigBus, "big buses and", smallBus, "small buses.")
print("Cost =", cost)
The division of passengers by 48 in the if statement is the cause of the problem since you can transport less than 48 passengers in a 1 big bus (for example 30) and it would be cheaper than transporting them in 3 small buses, but I have no clue how I would determine the cost to be cheaper in that case. I think the solution is flying right over my head.
Upvotes: 2
Views: 295
Reputation: 42133
Fill as many large busses as possible passengers // 48
. Then for the remaining passengers you have a simple decision to make based on the fact that 3 small busses cost more than 1 big bus (so you won't use more than two small busses):
passengers remaining = passengers % 48
(remaining+9) // 10
.This can be boiled down to :
remaining = passengers % 48
largeBusses = passengers // 48 + int(remaining > 20)
smallBusses = (remaining+9) // 10 * int(remaining <= 20)
Upvotes: 0
Reputation: 2882
Your average cost per passenger is 200/48
and 95/10
if the bus is full. Obviously the larger bus is more economic so the best solution comes as you use more large buses.
n_large = 0
n_small = 0
n_large += passengers // 48
# people remain unsettled
# [0, 48]
passengers = passengers % 48
But you also need to calculate the cost for the last bus because it's not full of people: if 200/num_people_left > 95/num_people_left
then use smaller bus for the last a few people.
Upvotes: 1