python-3.x - 如何将每个整数“一一”相乘并“按渐进顺序”显示结果,直到所有整数相乘得出整体乘积
问题描述
最近,我尝试创建一个 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处跳过结果?而且,我该如何解决?
解决方案
您正在迭代 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]))
推荐阅读
- typescript - 如何拥有基于不同返回类型的输入对象?
- c# - 如何跟踪 EF Core 中的身份更改?
- javascript - React useImperativeHandle 和 forwardRef 被设置,引用似乎没有更新
- swift - 从 Firebase 下载文件 - 错误域 = FIRStorageErrorDomain 代码 = -13000 - Swift
- python - 如何检查一个 Pandas 时间序列是否存在于另一个长时间序列中?
- css - LESS 为带有正斜杠的网格模板声明生成错误代码
- angular - fileInput.click() 未定义
- javascript - 提取和验证
- visual-studio-code - 在 VS 代码中取消隐藏活动栏
- javascript - Javascript循环初始化中定义的变量范围?