0

Given an int array length 2, return True if it contains a 2 or a 3. I can't use loops. Most of the test cases work except:

has23([4, 5]) --> False (my code returns True)
has23([7, 7]) --> False (my code returns True)
has23([9, 5]) --> False (my code returns True)

My code:

def has23(nums):
  if 2 or 3 in nums[0:1]:
    return True
  else:
    return False
Mythic-ctrl
  • 37
  • 1
  • 6
  • 1
    Does this answer your question? [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – Asocia May 18 '20 at 00:06

2 Answers2

0

The problem is with the if condition

if 2 or 3 in nums[0:1]

Your condition will return True if either of 2 or 3 in nums[0:1] evaluates to True. In which case, 2 will always evaluate to True and, hence, your code returns True every time.

Side Note: This condition has another problem. It will only check the first element of array (not the complete array). nums[0:1] returns elements starting from the 0th index and ending before the 1st index (1st index excluded). So, in this case, it will only return the first element.

Change it to something like this:

if 2 in nums or 3 in nums:

This condition will return True if either 2 in nums or 3 in nums evaluates to True (searching the element in whole list)

Moosa Saadat
  • 1,159
  • 1
  • 8
  • 20
0

in binds more tightly than or, so the statement 2 or 3 in nums[0:1] is equivalent to 2 or (3 in nums[0:1]). As or will short circuit, and 2 is always true, the second half is never evaluated, and the if statement always evaluates to true.

The comparison could be re-written as 3 in nums or 4 in nums which is equivalent to (3 in nums) or (4 in nums).

The construct:

if foo:
  return True
else:
  return False

Where foo is a boolean value is equivalent to:

return foo

Putting these together the function can be re-written as

def has23(nums):
    return 2 in nums or 3 in nums
Kim
  • 409
  • 3
  • 9