如何将每个整数“一对一"相乘?并“逐步"显示结果.直到所有整数相乘得出总积 [英] How to multiply each integer "one by one" and display result "in progressive order" until all integers multiplied leads to the overall product

查看:70
本文介绍了如何将每个整数“一对一"相乘?并“逐步"显示结果.直到所有整数相乘得出总积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

- 请注意,输出将跳过下面13的结果.但是在列出的输出末尾,所有整数的总积正确完成了

- 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

问题

有什么办法可以解决此错误?为什么python会在13处跳过结果?而且,我该如何解决?

Question

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

推荐答案

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

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

通过索引循环(通过range(len(s))enumerate(s)代替第一个循环):

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

这篇关于如何将每个整数“一对一"相乘?并“逐步"显示结果.直到所有整数相乘得出总积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆