-1

An interview question:

I have an array: for example this one:

a,b,c,d,e,f,g!=0

List_1=[a,b,c,d,e,f,g]

and I wan to find an optimum method with least operators to find this result:

Multiplication=[a+bcdefg,ab+cdefg,abc+defg,abcd+efg,abcde+fg,abcdef+g]

I propose to use this method:

mult=a*b*c*d*e*f*g
Multiplication=[]
Temp=List_1[0]
while(i<(len(List_1))-1):
    mult/=List_1[i]
    Multiplication.append(Temp+mult)
    Temp*=List_1[i+1]

This line mult=a*b*c*d*e*f*g take $n-1$ multiplication, while loop take $(n-1)$ multiplication, $(n-1)$ division and $(n-1)$ addition. So overall time is approximately $3n-3$ multiplication and $(n-1)$ addition.

Is this simplest method or there are other methods with minimum memory and time?

BarzanHayati
  • 637
  • 2
  • 9
  • 22

2 Answers2

3

Create [a, ab, abc, …] first:

l = [a, b, c, d, e, f, g]
result = []
p = 1

for i in range(0, len(l) - 1):
    p *= l[i]
    result.append(p)

Then add […, efg, fg, g] to it:

p = 1

for i in range(len(l) - 1, 0, -1):
    p *= l[i]
    result[i - 1] += p

This takes 2(n − 1) multiplications and n − 1 additions of list elements, which is better than 2(n − 1) multiplications, 2(n − 1) divisions, and n − 1 additions.

It’s also what Primusa described.

Ry-
  • 218,210
  • 55
  • 464
  • 476
1

Propose following without division which is much more slower:

myList=[1,2,3,4,5,6,7,8]
arrLen = len(myList)
leftOp = [1] * arrLen
rightOp = [1] * arrLen
result =  [1] * (arrLen - 1)
leftOp[0] = myList[0]
rightOp[arrLen - 1] = myList[arrLen - 1]
for i in range(1, arrLen - 1):
    leftOp[i] = myList[i] * leftOp[i-1]
    rightOp[arrLen - 1 - i] = myList[arrLen - 1 - i] * rightOp[arrLen - i]

for i in range(0, arrLen - 1):
    result[i] = leftOp[i] + rightOp[i + 1]