Last active
February 2, 2020 23:25
-
-
Save nebil/0c11b61c21c4ac237537e19e7d710ff3 to your computer and use it in GitHub Desktop.
🔁 extremum -- two recursive functions written in 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
""" | |
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) |
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
""" | |
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