Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Creative category for The Cheapest Flight by KareeO
from typing import List
def cheapest_flight_1(costs, a: str, b: str):
if a == b: return 0
else:
costs += [[s[1],s[0],s[2]] for s in costs]
try: return min(s[2] + cheapest_flight_1([t for t in costs if a not in t], s[1], b) for s in costs if a==s[0] )
except ValueError: return 2e30
def cheapest_flight(costs, a,b):
return 0 if cheapest_flight_1(costs,a,b)>=2e30 else cheapest_flight_1(costs,a,b)
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!")
April 13, 2020
Comments: