Python程序查找给定数量的连续元素的乘积
给定一个列表,任务是编写一个Python程序,该程序可以构造一个列表,其中包含给定数量元素的连续元素的乘积。
Input : test_list = [5, 6, 2, 1, 7, 5, 3], K = 3
Output : [60, 12, 14, 35, 105]
Explanation : 5 * 6 * 2 = 60, 6 * 2 * 1 = 12.. And so on.
Input : test_list = [5, 6, 2, 1, 7, 5, 3], K = 4
Output : [60, 84, 70, 105]
Explanation : 5 * 6 * 2 * 1 = 60, 6 * 2 * 1 * 7 = 84.. And so on.
方法 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))
输出:
The original list is : [5, 6, 2, 1, 7, 5, 3]
Computed Products : [60, 12, 14, 35, 105]
方法 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))
输出:
The original list is : [5, 6, 2, 1, 7, 5, 3]
Computed Products : [60, 12, 14, 35, 105]