Print the result
- Algorithms course
- Advanced
- Lesson 20/56
- 4 min
Print the cheapest cost.
Print the result
In the final step we add the print_route() function. It calls init_cost and dp_min_cost to print the result.
This completes the project: the user sees the lowest cost with a single function call. All pieces come together.
Output format
print_route() prints the result as an integer. The output shows the lowest cost from the start city to the last city.
This is the single value the project offers to the user. All computation is summarized in this number.
Practice print_route function
Write print_route(). Call init_cost(), pass it to dp_min_cost, print the result with print. Call print_route() to print 55.
Starter code
def init_cities():
# Return city list
return ['A', 'B', 'C', 'D']
def init_cost():
# Return cost matrix
return [[0, 10, 25, 60], [0, 0, 20, 50], [0, 0, 0, 30], [0, 0, 0, 0]]
def dp_min_cost(cost):
# Find the lowest cost
n = len(cost)
dp = [0] * n
for i in range(1, n):
best = float('inf')
for j in range(i):
cand = dp[j] + cost[j][i]
if cand < best:
best = cand
dp[i] = best
return dp[n - 1]
def print_route():
# Print resultSample solution
def init_cities():
# Return city list
return ['A', 'B', 'C', 'D']
def init_cost():
# Return cost matrix
return [[0, 10, 25, 60], [0, 0, 20, 50], [0, 0, 0, 30], [0, 0, 0, 0]]
def dp_min_cost(cost):
# Find the lowest cost
n = len(cost)
dp = [0] * n
for i in range(1, n):
best = float('inf')
for j in range(i):
cand = dp[j] + cost[j][i]
if cand < best:
best = cand
dp[i] = best
return dp[n - 1]
def print_route():
# Print result
cost = init_cost()
result = dp_min_cost(cost)
print(result)
print_route()Expected output
55
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does print_route do?
- Returns city list
- Sorts array
- Returns matrix
- Prints the cost Correct answer
Explanation: print_route prints the cost.
2 dp_min_cost call
cost = init_cost()
result = ____(cost)
cost = init_cost()
result = dp_min_cost(cost)
Explanation: dp_min_cost is right.
3 Print the result: match the terms
| Term | Meaning |
|---|---|
init_cities |
Cities |
init_cost |
Cost |
dp_min_cost |
DP |
print_route |