Skip to content

Instantly share code, notes, and snippets.

@sina-programer
Created June 26, 2025 08:20
Show Gist options
  • Save sina-programer/4bdb54e6403141392180c64990f3d6b0 to your computer and use it in GitHub Desktop.
Save sina-programer/4bdb54e6403141392180c64990f3d6b0 to your computer and use it in GitHub Desktop.
check if x is in [a, b] with just one comparison! (a <= x <= b)
def in_range(x, a, b):
''' checks if x is in [a, b] '''
if x == a: return True
u = (b - a) / (x - a)
return u >= 1
if __name__ == "__main__":
assert in_range(10, 1, 100)
assert in_range(10, 9, 11)
assert in_range(0, -1, 1)
assert in_range(-1, -10, 0)
assert in_range(1, 0, 1)
assert in_range(1, .99, 1)
assert not in_range(10, 8, 9)
assert not in_range(10, 0, 9)
assert not in_range(100, 1, 10)
assert not in_range(10, 11, 100)
print('All tests passed!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment