您可以生成所有可能的路径,然后按权重对其进行排序。注意我已经将数据中的权重更改为数字,而不是字符串:
data = [ ('Abe', 'Bob', 3), ('Abe', 'Frank', 5), ('Abe', 'George', 4), ('Carl', 'Bob', 1), ('Dan', 'Carl', 2),]WEIGHT = 0NODES = slice(1, None)def get_path_and_weight(data, start, end): paths = [[0, start]] added = True while added: added = False for first, second, weight in data: for path in paths: candidate = None if (first in path[NODES]) and (second not in path[NODES]): candidate = second elif (first not in path[NODES]) and (second in path[NODES]): candidate = first if candidate: new_path = list(path) new_path.append(candidate) new_path[WEIGHT] += weight if new_path not in paths: paths.append(new_path) added = True for path in sorted(paths): if end in path[NODES]: return path return None然后,您可以将其命名为:
weight, *path = get_path_and_weight(data, "Abe", "Dan")print(path, "with weight", weight)
给出结果:
['Abe', 'Bob', 'Carl', 'Dan'] with weight 6
并且由于它返回路径or
None,因此您仍然可以将其用作谓词函数:
if get_path_and_weight(data, "Abe", "Dan"): print("connected")


