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

Has anyone done the practice question?

This is my answer:

``````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
hotel_cost_per_day = v
car_cost_per_week = v

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:

1 Like

Nice! Very nicely commented too.