-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecursion_ProdofArray.py
More file actions
38 lines (28 loc) · 959 Bytes
/
Copy pathRecursion_ProdofArray.py
File metadata and controls
38 lines (28 loc) · 959 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#Given an array of integers, Replace each element with the product of the rmaining elements.
# input: {1,2,3,4,5}
#output: {120,60,40,30,24}
#Brute force approach
def prod_array(arr):
result = []
for i in range(len(arr)):
prod = 1
for j in range(len(arr)):
if i != j:
prod = prod * arr[j]
result += [prod]
print (result)
return result
arr = [1,2,3,4,5]
prod_array(arr)
def rec_Prodarr(arr, prodleft, index):
#Termination Condition
if index >= len(arr):
return 1
currentValue = arr[index]
productTillcurrentIndex = currentValue * prodleft
productOfElementRightOfCurrentIndex = rec_Prodarr(arr, productTillcurrentIndex, index+1)
arr[index] = prodleft * productOfElementRightOfCurrentIndex
return currentValue * productOfElementRightOfCurrentIndex
print (productOfElementRightOfCurrentIndex)
arr = [1,2,3,4,5]
rec_Prodarr(arr, 1, 0)