Check if number is between a range

Question:

I’m trying to write a function that returns 1 if value is between input and 0 if not. Here’s what I tried

def pixel_constraint(hlow, hhigh, slow, shigh, vlow, vhigh):
    """
    H - Hue:       (0-255) e.g red/cyan
    S - Saturation (0-255) e.g bright/not
    V - Value      (0-255) e.g black/white
    
    min = (hlow, slow, vlow)
    high = (hhigh, shigh, vhigh)
    if min >= high:
          return 1
      else:
          return 0
    """

Desired output:

    is_black = pixel_constraint(0, 255, 0, 255, 0, 10) 
    # Between (0 -> 255, 0 -> 255, 0 -> 10)

    is_black((231, 82, 4))
    >>> 1
    is_black((231, 72, 199))
    >>> 0
Asked By: Erik

||

Answers:

Assuming that your real intent is to have pixel_constraint return a function, this matches your desired output:

def pixel_constraint(hlow, hhigh, slow, shigh, vlow, vhigh):
    def f(pixel):
        h,s,v = pixel
        return int(hlow <= h <= hhigh and slow <= s <= shigh and vlow <= v <= vhigh)
    return f

is_black = pixel_constraint(0, 255, 0, 255, 0, 10) 
# Between (0 -> 255, 0 -> 255, 0 -> 10)

print(is_black((231, 82, 4))) #1
print(is_black((231, 72, 199))) #0
Answered By: John Coleman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.