8.1 - Bus hire

Problem

A bus compnay needs a program to calculate how many buses are required for each hire.

The program should:

  • Use a function to calculate the number fo buses needed for a hire

Example run

Enter the number of people: 100
Enter bus capacity:30

4 buses are required.
1 Calculate number of buses needed IN

num_people,

bus_capacity

OUT buses
1.1 set buses to (num_people / bus_capacity) converted to integer
1.2 if num_people / bus_capcity returns a remainder then
1.3     Add 1 to buses
1.4 return buses

 

 

# Main
num_people = int(input("Enter the number of people: "))
bus_capacity = int(input("Enter the bus capacity: "))

num_buses = buses_needed(num_people, bus_capacity)

print(num_buses, "buses are required.")
def buses_needed(num_people, bus_capacity):
    buses = int(num_people / bus_capacity)
    if num_people % bus_capacity != 0:
        buses = buses + 1
    return buses

# Main
num_people = int(input("Enter the number of people: "))
bus_capacity = int(input("Enter the bus capacity: "))

num_buses = buses_needed(num_people, bus_capacity)

print(num_buses, "buses are required.")
"""
- int(num_people / bus_capacity) is used to calculate how many *full buses* fit 
  into the total number of people (integer division).
- num_people % bus_capacity is used to check if there are any people left over 
  after filling those buses. If the remainder is not zero, one extra bus is needed.
"""

def buses_needed(num_people, bus_capacity):
    buses = int(num_people / bus_capacity)   # full buses
    if num_people % bus_capacity != 0:       # check for leftovers
        buses = buses + 1
    return buses


# Main
num_people = int(input("Enter the number of people: "))
bus_capacity = int(input("Enter the bus capacity: "))

# Call: use the function to calculate how many buses are needed
num_buses = buses_needed(num_people, bus_capacity)

print(num_buses, "buses are required.")

Extension

Write a new function to calculate how many buses are required for several journeys at once.

The function should:

  • Accept two arrays:

    • people[] – the number of people for each journey

    • capacities[] – the bus capacity for each journey

  • Return a new array showing the number of buses required for each journey.

People:     [50, 120, 101]
Capacities: [20, 60, 50]
Result:     [3, 2, 3]

Target

Write code to calculate the remainder of a division

Write code to convert a floating point number to integer