gpt4 book ai didi

python - LeetCode 的两和 - 为什么我自己的代码失败了

转载 作者:行者123 更新时间:2023-12-01 01:48:39 26 4
gpt4 key购买 nike

问题:

给定一个整数数组,返回两个数字的索引,使它们相加达到特定目标。您可以假设每个输入都有一个解决方案,并且您不能两次使用相同的元素。

<小时/>

我的代码:

def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for x in nums:
for y in nums:
if nums.index(x) != nums.index(y) and x + y == target :
return [nums.index(x), nums.index(y)]

print (twoSum ([3, 3],6))

输出:

null

在我看来,第一个“迭代”(我不太确定这是否是正确的术语)看起来像:

If 0 != 0 (False) and 3 + 3= 6 (True)  --> as  the first condition is not met, the y loops

所以下一次迭代看起来像:

If 0 != 1 (True) and 3 + 3 = 6 (True) 

--> 当满足上述条件时,函数将返回 [0,1],但代码实际上返回 null,我不明白原因.

所以,如果有人可以解释发生了什么,或者告诉我一些关键字,以便我自己搜索答案,我将非常感激:)

最佳答案

正如 MoxieBall 指出的,您的代码返回 None,因为 .index() 返回第一个匹配值的索引。

您可以使用enumerate()来获取真实的索引位置:

for x_index, x_value in enumerate(nums):
for y_index, y_value in enumerate(nums):
if x_index != y_index and x_value + y_value == target:
return [x_index, y_index]

关于python - LeetCode 的两和 - 为什么我自己的代码失败了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50955206/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com