如果数组包含2或3,则返回True

时间:2013-03-23 00:17:23

标签: python python-2.7

我遇到了这个CodingBat问题:

  

给定一个int数组长度为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 :(得分:6)

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

for item in nums大致相当于:

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

    ...
}

你的第二个不起作用,因为它过早地返回False。如果循环遇到的值不是23,则会返回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

答案 1 :(得分:0)

此Java代码可以正常运行:-

public boolean has23(int[] nums) {
  if(nums[0]==2||nums[1]==2||nums[0]==3||nums[1]==3){
    return true;
  }
  return false;
}

答案 2 :(得分:0)

使用索引执行上述操作的另一种方法 学习目的的变种

 def has23(nums):
  try :
    alpha = nums.index(2)
    return True
  except:
    try:
      beta = nums.index(3)
      return True
    except:
      return False

答案 3 :(得分: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

答案 4 :(得分:-1)

def has23(nums):
  if nums[0] ==2 or nums[0]==3 or nums[1] ==2 or nums[1]==3: 
    return True
  else: 
    return False
相关问题