Reputation: 13
If 33 people with 33 cars show up to a carpool parking lot, how many cars will be needed if each car can hold 4 people? How many cars will be left at the parking lot?
I know the answer is 9 but how do I write the script for that. I have been struggling for hours on this.
cars = 33
people = 33
people_per_car = 4
cars_needed = people / people_per_car
cars_left_at_lot = cars - cars_needed
print cars_needed
print cars_left_at_lot
I get 8 - Wrong!
8
25
Upvotes: 0
Views: 171
Reputation: 6854
Ok, you need to use either python 3.3 or the float command in order to disable the automatic rounding:
from math import ceil
cars = 33
people = 33
people_per_car = 4
cars_needed = int(ceil(1.* people / people_per_car))
cars_left_at_lot = cars - cars_needed
print cars_needed
print cars_left_at_lot
In python 2.7 numbers are rounded automatically if their type is int. Thats why I used 1. * which converts the number to float. The ceil will do rounding up instead of rounding down.
Upvotes: 0
Reputation: 122061
You need to add an extra car if there is any remainder:
cars_needed = people / people_per_car
if people % people_per_car:
cars_needed += 1
Upvotes: 1
Reputation: 23955
This is because in python2 when both operands are integers you perform integer division that by default rounds down:
>>> 33/4
8
>>> 33/4.0 # Note that one of operands is float
8.25
>>> math.ceil(33/4.0)
9.0
In python3 division is performed in float fashion by default (but I guess it is irrelevant).
Upvotes: 1