Created
June 8, 2018 04:45
-
-
Save CMCDragonkai/f2b3070a8585dd9e3bfe59df49ee9d91 to your computer and use it in GitHub Desktop.
Safe Max or Min (Max/Min Monoid) #python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# sometimes you're streaming through values in a for loop | |
# and you need to maintain a running max or min | |
# it's not elegant to get the head separately from the loop | |
# to solve this, we need a sentinel value to fold the max/min | |
# operation over the stream | |
# also known as the "identity element" of the max/min monoid | |
# in real world use cases, this could be a CSV stream | |
stream = (i for i in [1, 2, 3]) | |
# start with the identity element/sentinel value | |
# of negative infinity for max | |
# and positive infinity for min | |
max_value = float('-inf') | |
min_value = float('inf') | |
for next_value in stream: | |
max_value = max(max_value, next_value) | |
min_value = min(min_value, next_value) | |
# in some cases you want to use None as a sentinel value | |
# you can use these functions | |
# but I don't think it will be as efficient! | |
def max_safe(max_value, next_value): | |
if next_value is None: | |
return max_value | |
elif max_value is None: | |
return next_value | |
else: | |
return max(max_value, next_value) | |
def min_safe(min_value, next_value): | |
if next_value is None: | |
return min_value | |
elif min_value is None: | |
return next_value | |
else: | |
return min(min_value, next_value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment