Recursively calculates the product sum of an array. The product sum of an array is defined as the sum of its elements multiplied by their respective depths. If an element is a list, its product sum is calculated recursively by multiplying the sum of its elements with its depth plu
(arr: list[int | list], depth: int)
| 21 | |
| 22 | |
| 23 | def product_sum(arr: list[int | list], depth: int) -> int: |
| 24 | """ |
| 25 | Recursively calculates the product sum of an array. |
| 26 | |
| 27 | The product sum of an array is defined as the sum of its elements multiplied by |
| 28 | their respective depths. If an element is a list, its product sum is calculated |
| 29 | recursively by multiplying the sum of its elements with its depth plus one. |
| 30 | |
| 31 | Args: |
| 32 | arr: The array of integers and nested lists. |
| 33 | depth: The current depth level. |
| 34 | |
| 35 | Returns: |
| 36 | int: The product sum of the array. |
| 37 | |
| 38 | Examples: |
| 39 | >>> product_sum([1, 2, 3], 1) |
| 40 | 6 |
| 41 | >>> product_sum([-1, 2, [-3, 4]], 2) |
| 42 | 8 |
| 43 | >>> product_sum([1, 2, 3], -1) |
| 44 | -6 |
| 45 | >>> product_sum([1, 2, 3], 0) |
| 46 | 0 |
| 47 | >>> product_sum([1, 2, 3], 7) |
| 48 | 42 |
| 49 | >>> product_sum((1, 2, 3), 7) |
| 50 | 42 |
| 51 | >>> product_sum({1, 2, 3}, 7) |
| 52 | 42 |
| 53 | >>> product_sum([1, -1], 1) |
| 54 | 0 |
| 55 | >>> product_sum([1, -2], 1) |
| 56 | -1 |
| 57 | >>> product_sum([-3.5, [1, [0.5]]], 1) |
| 58 | 1.5 |
| 59 | |
| 60 | """ |
| 61 | total_sum = 0 |
| 62 | for ele in arr: |
| 63 | total_sum += product_sum(ele, depth + 1) if isinstance(ele, list) else ele |
| 64 | return total_sum * depth |
| 65 | |
| 66 | |
| 67 | def product_sum_array(array: list[int | list]) -> int: |