MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / can_complete_journey

Function can_complete_journey

greedy_methods/gas_station.py:62–92  ·  view source on GitHub ↗

This function returns the index from which to start the journey in order to reach the end. Args: gas_quantities [list]: Amount of gas available at each station cost [list]: The cost of gas required to move from one station to the next Returns: start [int]:

(gas_stations: tuple[GasStation, ...])

Source from the content-addressed store, hash-verified

60
61
62def can_complete_journey(gas_stations: tuple[GasStation, ...]) -> int:
63 """
64 This function returns the index from which to start the journey
65 in order to reach the end.
66
67 Args:
68 gas_quantities [list]: Amount of gas available at each station
69 cost [list]: The cost of gas required to move from one station to the next
70
71 Returns:
72 start [int]: start index needed to complete the journey
73
74 Examples:
75 >>> can_complete_journey(get_gas_stations([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]))
76 3
77 >>> can_complete_journey(get_gas_stations([2, 3, 4], [3, 4, 3]))
78 -1
79 """
80 total_gas = sum(gas_station.gas_quantity for gas_station in gas_stations)
81 total_cost = sum(gas_station.cost for gas_station in gas_stations)
82 if total_gas < total_cost:
83 return -1
84
85 start = 0
86 net = 0
87 for i, gas_station in enumerate(gas_stations):
88 net += gas_station.gas_quantity - gas_station.cost
89 if net < 0:
90 start = i + 1
91 net = 0
92 return start
93
94
95if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected