@@ -92,6 +92,78 @@ def product_sum_array(array: list[int | list]) -> int:
9292 return product_sum (array , 1 )
9393
9494
95+ def product_sum_iterative (arr : list [int | list | set | tuple ]) -> int :
96+ """
97+ Calculates the product sum of an array using iterative approach.
98+
99+ Logic :
100+ 1. Loop until input list have nested list/tuple/set
101+ 1. iterate on each item in input array
102+ 2. if item is nested list/tuple/set then
103+ - multiply the nested item with it's depth and add it's elements
104+ to new array
105+ 3. if item is not nested then
106+ add item to total sum
107+ 4. update old array with new array and increment depth value
108+
109+ Algorithm flow example ->
110+ Step 1 --> Array - [5, 2, [-7, 1], 3, [6, [-13, 8], 4]]
111+ total sum = 0 + () = 0
112+ Step 2 --> Array - [-7, 1, -7, 1, 6, [-13, 8], 4, 6, [-13, 8], 4]
113+ total sum = 0 + (5 + 2 + 3) = 10
114+ Step 3 --> Array - [-13, 8, -13, 8, -13, 8, -13, 8, -13, 8, -13, 8]
115+ total sum = 10 + (-7 + 1 -7 + 1 + 6 + 4 + 6 + 4) = 18
116+ Step 4 --> Array - [-13, 8, -13, 8, -13, 8, -13, 8, -13, 8, -13, 8]
117+ total sum=18 +(-13 + 8 -13 + 8 -13 + 8 -13 + 8 -13 + 8 -13 + 8)= -12
118+
119+ Args:
120+ array(List[Union[int, List, Set, Tuple]]): The array of integers/lists/tuple/set
121+
122+ Returns:
123+ int: The product sum of the array.
124+
125+ Examples:
126+ >>> product_sum_iterative([1, 2, 3])
127+ 6
128+ >>> product_sum_iterative([1, [2, 3]])
129+ 11
130+ >>> product_sum_iterative([1, [2, [3, 4]]])
131+ 47
132+ >>> product_sum_iterative([0])
133+ 0
134+ >>> product_sum_iterative([-3.5, [1, [0.5]]])
135+ 1.5
136+ >>> product_sum_iterative([1, -2])
137+ -1
138+
139+ """
140+
141+ # depth of the nested list/tuple/set
142+ next_depth = 2
143+
144+ # flag to check whether list has nested items or not
145+ nested_list_check = True
146+
147+ total_sum = 0
148+
149+ while nested_list_check :
150+ # list to store new items
151+ new_arr = []
152+ nested_list_check = False
153+
154+ for item in arr :
155+ if isinstance (item , list | tuple | set ):
156+ new_arr .extend (list (item ) * next_depth )
157+ nested_list_check = True
158+ else :
159+ total_sum += item
160+
161+ arr = new_arr
162+ next_depth += 1
163+
164+ return total_sum
165+
166+
95167if __name__ == "__main__" :
96168 import doctest
97169
0 commit comments