Return True if array contains a 2 or a 3

后端 未结 4 1820
南笙
南笙 2021-01-20 15:01

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 trie

相关标签:
4条回答
  • 2021-01-20 15:12

    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
    
    0 讨论(0)
  • 2021-01-20 15:15

    This Java code works fine:-

    public boolean has23(int[] nums) {
      if(nums[0]==2||nums[1]==2||nums[0]==3||nums[1]==3){
        return true;
      }
      return false;
    }
    
    0 讨论(0)
  • 2021-01-20 15:16
    def has23(nums):
      if nums[0] ==2 or nums[0]==3 or nums[1] ==2 or nums[1]==3: 
        return True
      else: 
        return False
    
    0 讨论(0)
  • 2021-01-20 15:31

    Another way to do the above using index A variation for learning purpose

     def has23(nums):
      try :
        alpha = nums.index(2)
        return True
      except:
        try:
          beta = nums.index(3)
          return True
        except:
          return False
    
    0 讨论(0)
提交回复
热议问题