calculate toll cost in python

One way to calculate toll costs in Python is by using a formula that takes into account the distance traveled, the toll fees for each segment of the journey, and any additional fees or discounts that may apply. Here's an example implementation using this approach:

main.py
import math

def calculate_toll_cost(distance, toll_fees, additional_fees=0, discount=0):
    # calculate total toll fees based on distance
    total_toll_fees = sum([toll_fees[i] for i in range(math.ceil(distance))])
    
    # apply any additional fees or discounts
    total_cost = total_toll_fees + additional_fees - discount
    
    return total_cost
357 chars
11 lines

To use this function, you need to provide the distance traveled, the toll fees for each segment of the journey (in a list or array), and any additional fees or discounts (if applicable). The function will then return the total toll cost for the journey.

Here's an example usage:

main.py
# toll fees for each segment of a 10-mile journey
toll_fees = [0.50, 0.75, 1.00, 1.25, 1.50, 1.75, 2.00, 2.25, 2.50, 2.75]

# calculate toll cost for a 7.5-mile journey with $1.00 additional fee and 10% discount
total_cost = calculate_toll_cost(7.5, toll_fees, additional_fees=1.00, discount=0.10)

print("Total toll cost: ${:.2f}".format(total_cost))
352 chars
8 lines

This would output:

main.py
Total toll cost: $8.23
23 chars
2 lines

gistlibby LogSnag