Search code examples
pythoncountnumbers

Count Odd Numbers in an Interval Range. Leetcode problem №1523. Python


I tried to solve this problem from leetcode and I came up with the following code but the testcase where low = 3 and high = 7 gives 2 as an output and 3 is expected by leetcode. I will be grateful if you explain what is wrong and how it should be done.

class Solution:
   def countOdds(self, low: int, high: int) -> int:
      count = 0
      for i in range(low, high):
         if i % 2 != 0:
            count += 1
      return count

Solution

  • range(low, high) will result in a range of (low, low+1, low+2, ..., high -1). Meaning that in your case high will not be considered.

    If high should also be considered use:

    range(low, high + 1)