Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- "You have an array of numbers." \
- "Write three functions that calculate the sum of these numbers:" \
- " with a for-loop," \
- " with a while-loop," \
- " with recursion."
- def sum_for_loop(a):
- s = 0
- for x in a:
- s += x
- return s
- def sum_while_loop(a):
- s = 0
- n = len(a)
- while n:
- n -= 1
- s += a[n]
- return s
- def sum_recursive(a):
- if len(a) == 0:
- return 0
- return a[0] + sum_recursive(a[1:])
- ARR = [5, 3, 4, 1, 7]
- for f in (sum_for_loop, sum_while_loop, sum_recursive):
- print(f(ARR))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement