Question

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
Was it helpful?

Solution

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).

OTHER TIPS

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top