Created
January 15, 2014 02:39
-
-
Save ishahid/8429857 to your computer and use it in GitHub Desktop.
Recursive sum of all elements of a given list.
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 sum(args): | |
""" Returns sum of all elements of a given list, recursively """ | |
if len(args) == 0: | |
return 0 | |
return args[0] + sum(args[1:]) | |
if __name__ == "__main__": | |
list1 = [] | |
print 'sum of []:', | |
print sum(list1) | |
list2 = [1] | |
print 'sum of [1]:', | |
print sum(list2) | |
list3 = [1, 2, 3] | |
print 'sum of [1, 2, 3]:', | |
print sum(list3) | |
list4 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
print 'sum of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:', | |
print sum(list4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment