Skip to content
Advertisement

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?

JavaScript
JavaScript

Advertisement

Answer

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:

JavaScript

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:

JavaScript

Or just use in:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement