Skip to content

Instantly share code, notes, and snippets.

@h2rashee
Last active March 4, 2020 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h2rashee/a1c643648e71392123eea6b13e12bfac to your computer and use it in GitHub Desktop.
Save h2rashee/a1c643648e71392123eea6b13e12bfac to your computer and use it in GitHub Desktop.
Given a list, determine if the list is monotonic
# 1, 2, 3, 4, 5 -> True
# 64, 32, 16, 8 -> True
# 1, 1, 2, 3, 5 -> True
# 10, 20, 15 -> False
# 0, 0, 0, 0 -> True
# 1 -> True
# -> True
def is_monotonic(nums):
is_ascending = None
# Single item list is monotonic by definition
if len(nums) == 1:
return True
# Let's compare each pair of numbers to check and ensure uni-directionality
for i in xrange(len(nums)-1):
if nums[i] > nums[i+1]:
if is_ascending is None:
is_ascending = False
if is_ascending is True:
return False
if nums[i] < nums[i+1]:
if is_ascending is None:
is_ascending = True
if is_ascending is False:
return False
return True
assert is_monotonic([1, 2, 3, 4, 5])
assert is_monotonic([64, 32, 16, 8])
assert is_monotonic([1, 1, 2, 3, 5])
assert not is_monotonic([10, 20, 15])
assert is_monotonic([0, 0, 0, 0])
assert is_monotonic([1])
assert is_monotonic([])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment