英文:
Index out of range even when the value exists
问题
我试图获取两个列表中缺失的数字。例如,输入为3、0和1,预期输出为2。
最终,列表"a"中的值为2。
以下是代码,我得到了索引超出范围的错误。
但是"a"中有值。
class Solution:
def missingNumber(self, nums: List[int]) -> int:
y = sorted(nums)
my_list = [x for x in range(y[0], y[-1])]
a = set(my_list).difference(y)
b = list(a)[0]
return b
nums = [3, 0, 1]
missingNumber(nums)
我无法提供最小可复现的代码示例(MVCE),因为我只有这个问题陈述和答案。我不需要代码问题的答案,而是要理解为什么会出现这个错误。
英文:
I am trying to get the missing number in two lists. The input for example is 3, 0, and 1, and the expected output is 2.
In the end, list "a" has the value 2.
Below is the code and I'm getting index out of range.
But "a" has value in it.
class Solution:
def missingNumber(self, nums: List[int]) -> int:
y=sorted(nums)
my_list = [x for x in range(y[0],y[-1])]
a=set(my_list).difference(y)
b=list(a)[0]
return b
nums = [3,0,1]
missingNumber(nums)
I'm not able to give the MVCE, because I am having the problem statement and the answer like this.
I do not need the answer to the code question, but to understand why this error is occurring.
答案1
得分: 1
以下是翻译好的部分:
自从只有一个数字缺失,你可以更简单地做到这一点:
class Solution:
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)
expected_sum = n * (n+1) // 2
return expected_sum - sum(nums)
你的错误来自于第二个测试案例 [0, 1]
。如果你添加调试打印语句,你会发现第一个测试案例不会产生错误,但第二个测试案例会。你可以看到列表中的最大数字不一定是你必须检查的范围中的最后一个数字。修正你的方法:
class Solution:
def missingNumber(self, nums: List[int]) -> int:
# 范围始终是从0到len(nums)(包括len(nums))
my_set = set(range(0, len(nums)+1))
a = my_set.difference(nums)
return list(a)[0]
英文:
Since there is only one number missing, you can do this much simpler:
class Solution:
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)
expected_sum = n * (n+1) // 2
return expected_sum - sum(nums)
Your error comes from the second test case [0, 1]
. If you add debug prints, you will find that the first test case does not produce the error, but the second one. You can see that the max number in the list is not necessarily the last number in the range that you have to check. Fixing your approach:
class Solution:
def missingNumber(self, nums: List[int]) -> int:
# The range is always from 0 to len(nums) inclusively
my_set = set(range(0, len(nums)+1))
a = my_set.difference(nums)
return list(a)[0]
答案2
得分: 0
我在Python 3中检查了。它返回2作为输出。
尝试打印 missingNumber(3, 0, 1)
。
英文:
I checked in Python 3. It is returning 2 as output.
Try to print missingNumber(3, 0, 1)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论