Last active
October 13, 2021 06:32
-
-
Save msyvr/68c553b174f4a75f14dbdfb89cfccc40 to your computer and use it in GitHub Desktop.
recursion - sum recursively, no loops
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 additup(num_list): | |
''' function that returns the sum of the passed list - without using loops; eg: | |
sum([1, 2, 3, 4, 5]) -> 15 | |
sum([]) -> 0 | |
''' | |
if len(num_list) == 1: | |
return num_list[0] | |
else: | |
return num_list[len(num_list)-1] + additup(num_list[0:len(num_list)-1]) | |
if __name__ == "__main__": | |
l = [1, 2, 3, 4, 5] | |
print(f'Sum recursively (no loops) over\n{l}\ngives: {additup(l)}') | |
u = input('Would you like to input your own list? (y/n): ').lower() | |
if u == 'y': | |
ulist = list(input('The numbers in your list (no spaces): ')) | |
l = [int(x) for x in ulist] | |
print(f'Sum recursively (no loops) over\n{l}\ngives: {additup(l)}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment