pythonalgorithm

Iterative multiplication program using arrays is providing incorrect results


This program is supposed to iterate through the numbers in an array starting at position 0 and multiply each number with the number before it. For example since 3 is the first element and there is nothing on the left to multiply it by, so it stays unchanged. For the second position you would multiply the 7 by the value to the left of it which is 3, resulting in the 21 being placed in the array where the 7 was. With my math I should be getting [3, 21, 105, 630, 5670] as the output, but I get this instead: [3, 21, 315, 119070, 21266497350]

front = [3,7,5,6,9]
temp = 1
for i in range(len(front)):
    print("before mult " + str(temp))
    front[i] *= temp
    print(front)
    temp *= front[i]
    print("after mult " + str(temp))

The full output is:

before mult 1
[3, 7, 5, 6, 9]
after mult 3
before mult 3
[3, 21, 5, 6, 9]
after mult 63
before mult 63
[3, 21, 315, 6, 9]
after mult 19845
before mult 19845
[3, 21, 315, 119070, 9]
after mult 2362944150
before mult 2362944150
[3, 21, 315, 119070, 21266497350]
after mult 50251545504173002500

Solution

  • You are doing unnecessary multiplication

    front = [3,7,5,6,9]
    temp = 1
    for i, v in enumerate(front):
        temp *= front[i]
        front[i] = temp
    
    print( front )