Recently, I've tried creating a for loop that multiplies each integer in the list and returns each sequential product until the overall product of all integers is given.
import operator
from operator import mul
from functools import reduce
s = list(map(int, input('Enter numbers WITH SPACES: ').split(' ')))
progression_product = [];
for i in s:
progression_product.append(reduce(mul, s[0:i]))
#This loop below removes repeating results. As for progressive order multiplication of positive
#integers. It's impossible to have a repeating result.(excluding multiple 1's and 0)
for ss in progression_product:
if progression_product.count(ss) > 1:
progression_product.remove(ss)
print(progression_product)
- Notice that the output skips the result for 13 below. But finishes correctly for the overall product of all integers at the end of the listed output
Enter numbers WITH SPACES: 12 2 3 4 13 133
[24, 72, 288, 497952]
> 12*2*3*4*13
>3744
Is there any way to fix this bug? Why would python skip the result at 13? And, how do I fix it?
You are iterating over the elements of s, not the indexes. Print the list before removing the duplicates, it will be:
[497952, 24, 72, 288, 497952, 497952]
# Which are the products of:
[s[0:12], s[0:2], s[0:3], s[0:4], s[0:13], s[0:133]]
Replace the first loop by a index loop, either by range(len(s))
or by enumerate(s)
:
# Either this:
progression_product = [];
for i in range(len(s)):
progression_product.append(reduce(mul, s[0:i]))
# Or this:
progression_product = [];
for i, v in enumerate(s):
progression_product.append(reduce(mul, s[0:i]))