Created
January 18, 2020 09:23
-
-
Save tamayonauta/1b6c5333874b5ab95f499c1ea6670df7 to your computer and use it in GitHub Desktop.
Recursive Sum
This file contains hidden or 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
| def recursive_sum(numbers): | |
| length = len(numbers) | |
| if length == 0: | |
| return 0 | |
| elif length == 1: | |
| return numbers[0] | |
| return numbers[0] + recursive_sum(numbers[1:]) | |
| def run_tests(): | |
| assert recursive_sum([]) == 0 | |
| assert recursive_sum([0]) == 0 | |
| assert recursive_sum([0, 0]) == 0 | |
| assert recursive_sum([1]) == 1 | |
| assert recursive_sum([1, 2]) == 3 | |
| assert recursive_sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) == 45 | |
| assert recursive_sum([100000000, 1000000000, 10000000000]) == 11100000000 | |
| assert recursive_sum([-1]) == -1 | |
| assert recursive_sum([-1, -2]) == -3 | |
| assert recursive_sum([-1, 2]) == 1 | |
| assert recursive_sum([20, -2, 10]) == 28 | |
| def run(): | |
| numbers = [] | |
| while True: | |
| print("SUMA RECURSIVA DE NÚMEROS") | |
| command = str(input( | |
| """ | |
| Selecciona una opción: | |
| [a] Agregar número a la suma | |
| [b] Mostrar resultado | |
| [c] Salir | |
| """ | |
| )) | |
| if command == "a": | |
| number = int(input("Ingresa un número: ")) | |
| numbers.append(number) | |
| elif command == "b": | |
| result = recursive_sum(numbers) | |
| print(f"La sumatoria total es: {result}") | |
| break | |
| else: | |
| break | |
| if __name__ == "__main__": | |
| # Tests | |
| # run_tests() | |
| run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment