Advertisement
Guest User

Untitled

a guest
Oct 19th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.57 KB | None | 0 0
  1. "You have an array of numbers." \
  2. "Write three functions that calculate the sum of these numbers:" \
  3. " with a for-loop," \
  4. " with a while-loop," \
  5. " with recursion."
  6.  
  7.  
  8. def sum_for_loop(a):
  9. s = 0
  10. for x in a:
  11. s += x
  12. return s
  13.  
  14.  
  15. def sum_while_loop(a):
  16. s = 0
  17. n = len(a)
  18. while n:
  19. n -= 1
  20. s += a[n]
  21. return s
  22.  
  23.  
  24. def sum_recursive(a):
  25. if len(a) == 0:
  26. return 0
  27. return a[0] + sum_recursive(a[1:])
  28.  
  29.  
  30. ARR = [5, 3, 4, 1, 7]
  31. for f in (sum_for_loop, sum_while_loop, sum_recursive):
  32. print(f(ARR))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement