How to multiply each integer “one by one” and display result “in progressive order” until all integers multiplied leads to the overall product

我们两清 提交于 2019-12-11 14:54:58

问题


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

Question

Is there any way to fix this bug? Why would python skip the result at 13? And, how do I fix it?


回答1:


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]))


来源:https://stackoverflow.com/questions/59112685/how-to-multiply-each-integer-one-by-one-and-display-result-in-progressive-ord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!