Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Recursion solution in Clear category for The Cheapest Flight by libertypi
from typing import List
def cheapest_flight(costs: List, a: str, b: str) -> int:
cheapest = price = 0
for index, flight in enumerate(costs):
for start, end in (flight[0], flight[1]), (flight[1], flight[0]):
if start == a:
if end == b:
price = flight[2]
else:
price = cheapest_flight(
costs[:index] + costs[index+1:], end, b)
if price != 0:
price += flight[2]
if price != 0 and price < cheapest or cheapest == 0:
cheapest = price
break
return cheapest
if __name__ == '__main__':
print("Example:")
print(cheapest_flight([['A', 'C', 100],
['A', 'B', 20],
['B', 'C', 50]],
'A',
'C'))
# These "asserts" are used for self-checking and not for an auto-testing
assert cheapest_flight([['A', 'C', 100],
['A', 'B', 20],
['B', 'C', 50]],
'A',
'C') == 70
assert cheapest_flight([['A', 'C', 100],
['A', 'B', 20],
['B', 'C', 50]],
'C',
'A') == 70
assert cheapest_flight([['A', 'C', 40],
['A', 'B', 20],
['A', 'D', 20],
['B', 'C', 50],
['D', 'C', 70]],
'D',
'C') == 60
assert cheapest_flight([['A', 'C', 100],
['A', 'B', 20],
['D', 'F', 900]],
'A',
'F') == 0
assert cheapest_flight([['A', 'B', 10],
['A', 'C', 15],
['B', 'D', 15],
['C', 'D', 10]],
'A',
'D') == 25
print("Coding complete? Click 'Check' to earn cool rewards!")
June 18, 2020
Comments: