栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从Python中的元组列表中查找路径

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从Python中的元组列表中查找路径

您可以生成所有可能的路径,然后按权重对其进行排序。注意我已经将数据中的权重更改为数字,而不是字符串:

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")


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/611385.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号