0

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
bereal
  • 32,519
  • 6
  • 58
  • 104
Boaz
  • 13
  • 1
  • https://www.google.no/search?q=python+round+up&oq=python+round+up&aqs=chrome..69i57j0l3j69i60j69i64.3138j0j4&sourceid=chrome&ie=UTF-8 – M4rtini Feb 09 '14 at 19:08

3 Answers3

1

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

jb.
  • 23,300
  • 18
  • 98
  • 136
1

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
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
0

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.

varantir
  • 6,624
  • 6
  • 36
  • 57