Advertisement
UniQuet0p1

Untitled

Oct 31st, 2020
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.78 KB | None | 0 0
  1. def sum_squares(nested_list):
  2. """
  3. Write a function that sums squares of numbers in list.
  4.  
  5. That list may contain additional lists.
  6. (Hint use the type() or isinstance() function)
  7.  
  8. sum_squares([1, 2, 3]) -> 14
  9. sum_squares([[1, 2], 3]) -> sum_squares([1, 2]) + 9 -> 1 + 4 + 9 -> 14
  10. sum_squares([[[[[[[[[2]]]]]]]]]) -> 4
  11.  
  12. :param nested_list: list of lists of lists of lists of lists ... and ints
  13. :return: sum of squares
  14. """
  15. assert nested_list >= 0
  16. if nested_list == 0:
  17. return 0
  18. else:
  19. return sum_squares(nested_list - 1) + nested_list * nested_list
  20.  
  21.  
  22. if __name__ == "__main__":
  23. print(sum_squares([1, 2, 3])) # -> 14
  24. print(sum_squares([[1, 2], 3])) # -> 14
  25. print(sum_squares([[[[[[[[[2]]]]]]]]])) # -> 4
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement