Skip to content

Instantly share code, notes, and snippets.

@nebil
Last active February 2, 2020 23:25
Show Gist options
  • Save nebil/0c11b61c21c4ac237537e19e7d710ff3 to your computer and use it in GitHub Desktop.
Save nebil/0c11b61c21c4ac237537e19e7d710ff3 to your computer and use it in GitHub Desktop.
🔁 extremum -- two recursive functions written in Python
"""
maximum.py -- a recursive maximum finder using Python
This source code is licensed under a Creative Commons CC0 license.
More info at <https://creativecommons.org/publicdomain/zero/1.0/>.
"""
def get_maximum(numbers):
if len(numbers) == 1:
return numbers[0]
aximum = get_maximum(numbers[1:])
return numbers[0] if numbers[0] > aximum else aximum
# Use a more idiomatic approach.
def get_the_maximum_of(numbers):
first, *residuum = numbers
if not residuum:
return first
aximum = get_the_maximum_of(residuum)
return first if first > aximum else aximum
if __name__ == "__main__":
example = [3, 14, 1, -5, 9, 2]
maximum = get_maximum(example)
print(maximum)
another_example = [3, 14, 1, -5, 9, 2, 6, 5, 3, 5, 8]
another_maximum = get_the_maximum_of(another_example)
print(another_maximum)
"""
minimum.py -- a recursive minimum finder using Python
This source code is licensed under a Creative Commons CC0 license.
More info at <https://creativecommons.org/publicdomain/zero/1.0/>.
"""
def get_minimum(numbers):
if len(numbers) == 1:
return numbers[0]
inimum = get_minimum(numbers[1:])
return numbers[0] if numbers[0] < inimum else inimum
# Use a more idiomatic approach.
def get_the_minimum_of(numbers):
first, *residuum = numbers
if not residuum:
return first
inimum = get_the_minimum_of(residuum)
return first if first < inimum else inimum
if __name__ == "__main__":
example = [3, 14, 1, -5, 9, 2]
minimum = get_minimum(example)
print(minimum)
another_example = [3, 14, 1, -5, 9, 2, 6, 5, 3, 5, 8]
another_minimum = get_the_minimum_of(another_example)
print(another_minimum)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment