Skip to content

Instantly share code, notes, and snippets.

@msyvr
Last active October 13, 2021 06:32
Show Gist options
  • Save msyvr/68c553b174f4a75f14dbdfb89cfccc40 to your computer and use it in GitHub Desktop.
Save msyvr/68c553b174f4a75f14dbdfb89cfccc40 to your computer and use it in GitHub Desktop.
recursion - sum recursively, no loops
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