Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return True if array contains a 2 or a 3

I'm having trouble with this CodingBat problem:

Given an int array length 2, return True if it contains a 2 or a 3.

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
like image 306
Jodi Peterson Avatar asked Oct 27 '25 20:10

Jodi Peterson


1 Answers

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
like image 178
Blender Avatar answered Oct 30 '25 10:10

Blender