1digit_sum = lambda s: sum(int(digit) for digit in str(s)) #without recursion
2
3#sum of digits using recursion
4
5dsum = 0 # we define dsum outside of the function so its value isn't reset every time the function gets called recursivley
6
7def rdigit_sum(s):
8 global dsum # making dsum 'global' allows us to use it a function
9 if s: # checks if s has digits to add to dsum
10 dsum += s%10 # adds the current units digit to dsum
11 s = s//10 # removes the current units digit
12 else: # if there are no digits left
13 s = dsum # this block reassigns s to dsum, then resets dsum to 0 so dsum doesn't already have a value if this function is called more than once in a program
14 dsum = 0
15 return s
16 return rdigit_sum(s) # this is the 'recursive' part of the program that calls the function again
1def sum_(n):
2 if n == 0:
3 return n
4 else:
5 prev_n = sum_(n - 1)
6 result = prev_n + n
7 return result
8
9
10s = sum_(5)
11
12print(s)
13
14#Output:
15# 15
1def SumNum(mylist):
2 the_sum = sum(filter(lambda i: isinstance(i, (int, long, float)), mylist))
3 return the_sum