Back to Freecodecamp

Challenge 215: Parking Fee Calculator

curriculum/challenges/english/blocks/daily-coding-challenges-python/699c8e045ee7cb94ed2322d6.md

latest2.8 KB
Original Source

--description--

Given two strings representing the time you parked your car and the time you picked it up, calculate the parking fee.

  • The given strings will be in the format "HH:MM" using a 24-hour clock. So "14:00" is 2pm for example.
  • The first string will be the time you parked your car, and the second will be the time you picked it up.
  • If the pickup time is earlier than the entry time, it means the parking spanned past midnight into the next day.

Fee rules:

  • Each hour parked costs $3.
  • Partial hours are rounded up to the next full hour.
  • If the parking spans overnight (past midnight), an additional $10 overnight fee is applied.
  • There is a minimum fee of $5 (only used if the total would be less than $5).

Return the total cost in the format "$cost", "$5" for example.

--hints--

calculate_parking_fee("09:00", "11:00") should return "$6".

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(calculate_parking_fee("09:00", "11:00"), "$6")`)
}})

calculate_parking_fee("10:00", "10:30") should return "$5".

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(calculate_parking_fee("10:00", "10:30"), "$5")`)
}})

calculate_parking_fee("08:10", "10:45") should return "$9".

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(calculate_parking_fee("08:10", "10:45"), "$9")`)
}})

calculate_parking_fee("14:40", "23:10") should return "$27".

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(calculate_parking_fee("14:40", "23:10"), "$27")`)
}})

calculate_parking_fee("18:15", "01:30") should return "$34".

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(calculate_parking_fee("18:15", "01:30"), "$34")`)
}})

calculate_parking_fee("11:11", "11:10") should return "$82".

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(calculate_parking_fee("11:11", "11:10"), "$82")`)
}})

--seed--

--seed-contents--

py
def calculate_parking_fee(park_time, pickup_time):

    return park_time

--solutions--

py
import math

def calculate_parking_fee(park_time, pickup_time):
    def to_minutes(time_str):
        hours, minutes = map(int, time_str.split(":"))
        return hours * 60 + minutes

    entry_minutes = to_minutes(park_time)
    exit_minutes = to_minutes(pickup_time)

    overnight = False

    if exit_minutes < entry_minutes:
        overnight = True
        total_minutes = (24 * 60 - entry_minutes) + exit_minutes
    else:
        total_minutes = exit_minutes - entry_minutes

    hours = math.ceil(total_minutes / 60)

    cost = hours * 3

    if overnight:
        cost += 10

    if cost < 5:
        cost = 5

    return f"${cost}"