【发布时间】:2019-10-09 23:43:53
【问题描述】:
谁能给我一些建议,让我使用 for 循环让这个长长的 Python 代码运行得更快?这是一个在最接近“目标”的名为“nums”的列表中查找 3 个整数的代码。此代码完全有效,但我可能需要更有效的方法。:
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
clse = 2**31-1
for a in range(len(nums)):
for b in range(len(nums)):
for c in range(len(nums)):
if a is not b and b is not c and c is not a:
if abs(nums[a]+nums[b]+nums[c]-target) < clse:
print(a,b,c)
clse = abs(nums[a]+nums[b]+nums[c]-target)
anum = nums[a]+nums[b]+nums[c]
return anum
【问题讨论】:
-
在不改变算法的情况下,可以并行化最外层的循环。
-
由于使用了
is not(检查对象身份)而不是!=(比较相等性),您的代码从根本上被破坏了。
标签: python algorithm performance