如果数组包含2或3则返回True
我在解决这个CodingBat的问题时遇到了困难:
给定一个长度为2的整数数组,如果里面包含2或3,就返回True。
我尝试了两种不同的方法来解决这个问题。有没有人能告诉我我哪里做错了?
#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
5 个回答
0
这是一篇旧帖子,我知道,但为了未来的读者,我想分享一些内容:
关于for循环,我觉得还有一个值得提的选择:使用range()函数。
你可以把
for i in nums:
的for循环改成这样:
for i in range(len(nums)):
这样做会遍历整数,和其他编程语言的做法一样。然后使用 nums[i]
就可以获取到对应索引的值。
不过,我注意到你的代码还有另一个问题,和你想要实现的目标有关:在for循环里,所有的执行路径都会返回一个变量。无论数组的长度是多少,for循环只会执行一次,因为在第一次执行后就会返回,结束函数的执行。如果第一个值是假的,函数就会返回假。
相反,你应该在循环内部只在条件为真的时候结束执行。如果循环遍历了所有可能性而没有出现假的情况,那么就返回假:
def has23(nums):
for i in range(len(nums)): # iterate over the range of values
if nums[i]==2 or nums[i]==3:# get values via index
return true # return true as soon as a true statement is found
return false # if a true statement is never found, return false
0
另一种使用索引来实现上述功能的方法
这是为了学习而做的一个变体
def has23(nums):
try :
alpha = nums.index(2)
return True
except:
try:
beta = nums.index(3)
return True
except:
return False
7
你第一个写的代码不行,因为Python里的for
循环和其他语言的for
循环不一样。它不是通过索引来循环,而是直接遍历实际的元素。
for item in nums
大致可以理解为:
for (int i = 0; i < nums.length; i++) {
int item = nums[i];
...
}
你第二个写的代码也不行,因为它返回False
的太早了。如果循环遇到一个不是2
或3
的值,它就会返回False
,然后就不再检查其他元素了。
把你的循环改成这样:
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.
或者直接用in
:
def has23(nums):
return 2 in nums or 3 in nums