问题描述
我遇到了这个 CodingBat 问题:
给定一个长度为 2 的 int 数组,如果它包含一个 2 或一个 3,则返回 True.
我尝试了两种不同的方法来解决这个问题.谁能解释一下我做错了什么?
#这个说index超出范围,为什么?def has23(nums):对于我在 nums:如果 nums[i]==2 或 nums[i]==3:返回真别的:返回错误
#如果用户输入了 4,3,这个就不会通过测试.#它应该为真时会产生假.为什么?def has23(nums):对于我在 nums:如果 i==2 或 i==3:返回真别的:返回错误
你的第一个不起作用,因为 Python 中的 for
循环与 for
不同其他语言中的代码>循环.它不是遍历索引,而是遍历实际元素.
for item in nums
大致相当于:
for (int i = 0; i
您的第二个不起作用,因为它过早地返回
>False
.如果循环遇到不是 2
或 3
的值,它会返回 False
并且不会遍历任何其他元素.
把你的循环改成这样:
def has23(nums):对于我在 nums:如果 i == 2 或 i == 3:return True # 仅当值为 2 或 3 时才返回 `True`return False # `for` 循环结束,因此列表中没有 2 或 3.
或者直接使用in
:
def has23(nums):返回 2 in nums 或 3 in nums
I'm having trouble with this CodingBat problem:
I've tried two different ways to solve this. Can anyone explain what I'm doing wrong?
#This one says index is out of range, why?
def has23(nums):
for i in nums:
if nums[i]==2 or nums[i]==3:
return True
else:
return False
#This one doesn't past the test if a user entered 4,3.
#It would yield False when it should be true. Why?
def has23(nums):
for i in nums:
if i==2 or i==3:
return True
else:
return False
Your first one doesn't work because the for
loop in Python isn't the same as the for
loop in other languages. Instead of iterating over the indices, it iterates over the actual elements.
for item in nums
is roughly equivalent to:
for (int i = 0; i < nums.length; i++) {
int item = nums[i];
...
}
Your second one doesn't work because it returns False
too soon. If the loop encounters a value that isn't 2
or 3
, it returns False
and doesn't loop through any other elements.
Change your loop to this:
def has23(nums):
for i in nums:
if i == 2 or i == 3:
return True # Only return `True` if the value is 2 or 3
return False # The `for` loop ended, so there are no 2s or 3s in the list.
Or just use in
:
def has23(nums):
return 2 in nums or 3 in nums
这篇关于如果数组包含 2 或 3,则返回 True的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!