📜  Python程序查找给定数量的连续元素的乘积

📅  最后修改于: 2022-05-13 01:55:49.989000             🧑  作者: Mango

Python程序查找给定数量的连续元素的乘积

给定一个列表,任务是编写一个Python程序,该程序可以构造一个列表,其中包含给定数量元素的连续元素的乘积。

方法 1:使用列表切片循环

在这里,我们使用列表切片执行获取 K 切片的任务,获取产品的任务由外部函数调用完成。

例子:

Python3
# getting product
def prod(sub):
    res = 1
    for ele in sub:
        res = ele * res
    return res
  
  
# initializing lists
test_list = [5, 6, 2, 1, 7, 5, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 3
  
res = []
for idx in range(len(test_list) - K + 1):
  
    # getting product using external function
    res.append(prod(test_list[idx: idx + K]))
  
# printing result
print("Computed Products : " + str(res))


Python3
from functools import reduce
from operator import mul
  
# generator function
  
  
def sliced_prod(sub, K):
    for idx in range(len(sub) - K + 1):
  
        # slicing and returning intermediate product
        sliced = sub[idx: idx + K]
        yield reduce(mul, sliced)
  
# generator function
  
  
# initializing lists
test_list = [5, 6, 2, 1, 7, 5, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 3
  
# calling fnc.
res = list(sliced_prod(test_list, K))
  
# printing result
print("Computed Products : " + str(res))


输出:

方法 2:使用generator slicing reduce()mul运算符

其中,生成器用于计算和返回中间结果。使用内置函数reduce() 和 mul 运算符完成切片乘法的任务。

例子:

蟒蛇3

from functools import reduce
from operator import mul
  
# generator function
  
  
def sliced_prod(sub, K):
    for idx in range(len(sub) - K + 1):
  
        # slicing and returning intermediate product
        sliced = sub[idx: idx + K]
        yield reduce(mul, sliced)
  
# generator function
  
  
# initializing lists
test_list = [5, 6, 2, 1, 7, 5, 3]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 3
  
# calling fnc.
res = list(sliced_prod(test_list, K))
  
# printing result
print("Computed Products : " + str(res))

输出: