Search code examples
pythonroundinginteger-division

how to write script to round up in python


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

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