小编Ümi*_*ara的帖子

2 个列表的最大路径总和

我的问题是关于Codewars 上的这个型。该函数采用两个具有不同元素的排序列表作为参数。这些列表可能有也可能没有共同的项目。任务是找到最大路径和。在查找总和时,如果有任何常见项目,您可以选择更改到其他列表的路径。

给出的例子是这样的:

list1 = [0, 2, 3, 7, 10, 12]
list2 = [1, 5, 7, 8]
0->2->3->7->10->12 => 34
0->2->3->7->8      => 20
1->5->7->8         => 21
1->5->7->10->12    => 35 (maximum path)
Run Code Online (Sandbox Code Playgroud)

我解决了 kata,但我的代码不符合性能标准,因此执行超时。我能为它做些什么呢?

这是我的解决方案:

def max_sum_path(l1:list, l2:list):
    common_items = list(set(l1).intersection(l2))
    if not common_items:
        return max(sum(l1), sum(l2))
    common_items.sort()
    s = 0
    new_start1 = 0
    new_start2 = 0
    s1 = 0
    s2 = 0
    for item in common_items:
        s1 = sum(itertools.islice(l1, new_start1, l1.index(item)))
        s2 = sum(itertools.islice(l2, new_start2, l2.index(item)))
        new_start1 = …
Run Code Online (Sandbox Code Playgroud)

python algorithm list python-3.x

8
推荐指数
1
解决办法
704
查看次数

标签 统计

algorithm ×1

list ×1

python ×1

python-3.x ×1