首页 > 解决方案 > 如何将每个整数“一一”相乘并“按渐进顺序”显示结果,直到所有整数相乘得出整体乘积

问题描述

最近,我尝试创建一个 for 循环,将列表中的每个整数相乘并返回每个顺序乘积,直到给出所有整数的总乘积。

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)

- 请注意,输出会跳过下面 13 的结果。但在列出的输出末尾正确完成所有整数的整体乘积

Enter numbers WITH SPACES: 12 2 3 4 13 133
[24, 72, 288, 497952]
> 12*2*3*4*13
>3744

问题

有没有办法修复这个错误?为什么python会在13处跳过结果?而且,我该如何解决?

标签: python-3.xmultiplication

解决方案


您正在迭代 s 的元素,而不是索引。在删除重复项之前打印列表,它将是:

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

用索引循环替换第一个循环,可以是 byrange(len(s))或 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]))

推荐阅读