【发布时间】:2022-01-10 14:09:51
【问题描述】:
我的问题是关于 Codewars 上的 this kata。该函数采用两个具有不同元素的排序列表作为参数。这些列表可能有也可能没有共同项目。任务是找到最大路径和。在求总和的同时,如果有任何共同项,您可以选择将路径更改为其他列表。
给定的例子是这样的:
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)
我解决了 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 = l1.index(item)
new_start2 = l2.index(item)
s += max(s1, s2)
s1 = sum(itertools.islice(l1, new_start1, len(l1)))
s2 = sum(itertools.islice(l2, new_start2, len(l2)))
s += max(s1, s2)
return s
【问题讨论】:
-
首先我会通过拨打
time.time几个电话来找出哪个部分花费的时间最多。 -
像这样:
start = time.time(); #do stuff that takes very long; print(time.time() - start)- 您将获得两次time.time调用之间的时间(以毫秒为单位)。 -
当列表长度为 619 和 1352 时,第二个代码的 for 循环需要 0.01697850227355957 毫秒。当我为大列表尝试它们时,我注意到第一个返回错误的总和。但第二个工作正常。但是我仍然不知道该怎么做才能减少长时间输入的时间。
-
啊抱歉……
time.time返回秒数,而不是毫秒数。但这意味着您的代码只需要 16 毫秒 - 我怀疑这可以进一步减少。因此,要么执行您在该网站上提交的代码的服务器超慢并且花费的时间超过这 16 毫秒,要么确定您提交的代码是否太慢的代码存在错误。 -
0
标签: python python-3.x list algorithm