# ZerotoPandas Lesson 2: Practice Question (Writing Reusable Code Using Functions)

Has anyone done the practice question?

``````import math

vacay = {
"Paris": [200, 20, 200],
"London": [250, 30, 120],
"Dubai": [370, 15, 80],
"Mumbai": [450, 10, 70]
}

def trip_cost(dictionary, duration=7, budget=1000):

cost = 0

for k, v in dictionary.items():
city = k
flight_cost = v[0]
hotel_cost_per_day = v[1]
car_cost_per_week = v[2]

cost += flight_cost
cost += hotel_cost_per_day * duration
cost += car_cost_per_week * math.ceil((duration/7))
print(f'For a {duration}-day trip to {city}, the cost is \${cost}.')
if cost > budget:
print(f'This trip exceeds your budget of \${budget}.')
elif cost < budget:
print(f'This trip is within your budget of \${budget}!')

print('\n')

trip_cost(vacay)
trip_cost(vacay, 4, 600)

``````

Also have a simpler version where you can enter all the parameters of each city as the arguments to the function:

``````import math

def total_cost(city, flight_cost, hotel_cost, car_cost, duration=7, budget=1000):
cost = 0
cost += flight_cost
cost += hotel_cost * duration
cost += car_cost * math.ceil((duration/7))
print(f'For a {duration}-day trip to {city}, the cost is \${cost}.')
if cost > budget:
print(f'This trip exceeds your budget of \${budget}.')
elif cost < budget:
print(f'This trip is within your budget of \${budget}!')
total_cost('Paris', 200, 20, 200)
``````

Show me your code! Would like to see how you did it.

4 Likes

Wow, thatâ€™s actually really good. I just made functions for each of the questions. So I have a function for getting the â€śTotal Trip Costâ€ť, â€śFinding the Cheapest Tripâ€ť, â€śFinding the Number of Days for the Trip given the Budgetâ€ť and then â€śFinding the Maximum and Minimum Duration Given the Budgetâ€ť.

In your first code you used a dictionary. How do you know when is a good time to use a dictionary in a code?

How does your â€śFinding the Number of Days for the Trip given the Budget" function differ from your â€śFinding the Maximum and Minimum Duration Given the Budget" function? Ignoring the minimum duration bit since I assume that always will result in an answer of 1 day?

I just used a dictionary cause I thought it would be easier than using lists especially since I wanted to iterate through all the cities automatically. You could probably write it with each city as a list itself and code it that way.

Hi Denton! this is my solution

for different durations:

Nice! Very nicely commented too.