0

I'm doing python bats and the question 'has23' says the following:

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

I have written this code so far expecting it to work as intended with the else statement but I cannot trigger the False if 2 or 3 is not found within the array.

def has23(nums):
  if 2 or 3 in nums:
    return True

  else:
    return False
Camnaz
  • 11
  • 5

2 Answers2

2

You need to completely write conditions that are separated by and or or. You code was actually checking if 2 or if 3 in nums. if 2 actually checks if 2 is nonzero, which is always true.

def has23(nums):
  if 2 in nums or 3 in nums:
    return True
  else:
    return False
Dominic D
  • 1,778
  • 2
  • 5
  • 12
  • Thanks so much! I knew it was probably something small but I thought my logic was correct. This made sense and helped me out. – Camnaz Jun 07 '20 at 03:37
  • 3
    good answer and correct but effectively doubles the complexity this has an unnesscessary loop `set([2,3]).intersection(nums)` would probably be more efficient(but honestly unlikely to make much of a difference(depending on size of nums)) – Joran Beasley Jun 07 '20 at 03:38
0

Writing 2 or 3 in nums actually means, in Python, (2) or (3 in nums). Which will always evaluate to True because 2 is a truthy value. What you should write instead to perform your intent here is 2 in nums or 3 in nums.

michaeldel
  • 2,204
  • 1
  • 13
  • 19