In this particular case, and using your data structure, it seems that you should be able to run two scripts in parallel:
You can maintain the current value, and the data you collect provides the “cost of switching” in the third element.
So, you need to ask: what is cheaper? Staying on the starting line or switching to another way?
path_list = [ (50, 10, 30), (5, 90, 20), (40, 2, 25), (10, 8, 0), ] A = 0 B = 1 Switch = 2 def cheapest_path(path_list, path=None, history=None): if history is not None: # Terminate when path_list is empty if not path_list: return history # Determine cost to stay this path, vs. cost to switch step = path_list[0] path_list = path_list[1:] stay_on_path = cheapest_path(path_list, path, history + [step[path]]) switch_path = cheapest_path(path_list, B if path == A else A, history + [step[path], step[Switch]]) return switch_path if sum(switch_path) < sum(stay_on_path) else stay_on_path else: pathA = cheapest_path(path_list, A, []) pathB = cheapest_path(path_list, B, []) return pathA if sum(pathA) < sum(pathB) else pathB print(", ".join(map(str, cheapest_path(path_list))))
Austin hastings
source share