3

我遇到了这个 CodingBat 问题:

给定一个长度为 2 的 int 数组,如果它包含 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
4

5 回答 5

7

您的第一个不起作用,因为forPython 中的for循环与其他语言中的循环不同。它不是迭代索引,而是迭代实际元素。

for item in nums大致相当于:

for (int i = 0; i < nums.length; i++) {
    int item = nums[i];

    ...
}

你的第二个不起作用,因为它返回False得太快了。如果循环遇到一个不是2or的值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
于 2013-03-23T00:20:29.323 回答
0

出于学习目的使用索引 A 变体来完成上述操作的另一种方法

 def has23(nums):
  try :
    alpha = nums.index(2)
    return True
  except:
    try:
      beta = nums.index(3)
      return True
    except:
      return False
于 2020-10-03T01:48:30.993 回答
0

老帖子,我知道,但对于未来的读者:

关于 for 循环,我认为值得一提的是另一个选项:使用 range() 函数。

代替

 for i in nums:

您可以将 for 循环切换为如下所示:

for i in range(len(nums)):

这将迭代整数,就像其他语言一样。然后使用nums[i]将获取索引的值。

但是,我注意到您的代码及其既定目标的另一个问题:在 for 循环中,所有执行路径都返回一个变量。无论数组的长度如何,它只会执行一次 for 循环,因为在第一次执行后它返回,结束函数的执行。如果第一个值为 false,则函数将返回 false。

相反,只有当语句为真时,您才希望在循环内结束执行。如果循环遍历所有可能性并且没有什么是错误的,则返回 false:

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
于 2021-07-26T20:50:11.693 回答
-1

此 Java 代码工作正常:-

public boolean has23(int[] nums) {
  if(nums[0]==2||nums[1]==2||nums[0]==3||nums[1]==3){
    return true;
  }
  return false;
}
于 2020-06-22T07:39:29.910 回答
-2
def has23(nums):
  if nums[0] ==2 or nums[0]==3 or nums[1] ==2 or nums[1]==3: 
    return True
  else: 
    return False
于 2018-11-03T14:01:50.243 回答