📜  Python|连续块产品

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

Python|连续块产品

编程领域的一些经典问题来自不同的类别,其中之一是寻找子集的乘积。当我们需要计算产品并存储连续的组产品价值时,这个特殊问题也很常见。让我们在Python语言中尝试不同的方法来解决这个问题。

方法#1:使用列表理解+循环
列表推导可用于执行此特定任务以过滤掉连续的组,并且产品显式函数可用于获得过滤后的解决方案的产品。

# Python3 code to demonstrate
# Consecutive chunks Product
# using list comprehension + loop
  
# getting Product
def prod(val) :
    res = 1 
    for ele in val:
        res *= ele
    return res 
  
# initializing list
test_list = [4, 7, 8, 10, 12, 15, 13, 17, 14]
  
# printing original list 
print("The original list : " + str(test_list))
  
# using list comprehension + loop
# Consecutive chunks Product
res = [ prod(test_list[x : x + 3]) for x in range(0, len(test_list), 3)]
  
# printing result
print("The chunked product list is : " + str(res))
输出 :
The original list : [4, 7, 8, 10, 12, 15, 13, 17, 14]
The chunked product list is : [224, 1800, 3094]

方法 #2:使用循环 + itertools.islice()
将列表切成块的任务在这里通过 islice 方法完成,而获取产品的常规任务是通过上述方法的显式乘积函数完成的。

# Python3 code to demonstrate
# Consecutive chunks Product
# using itertools.islice() + loop
import itertools
  
# getting Product
def prod(val) :
    res = 1 
    for ele in val:
        res *= ele
    return res 
  
# initializing list
test_list = [4, 7, 8, 10, 12, 15, 13, 17, 14]
  
# printing original list 
print("The original list : " + str(test_list))
  
# using itertools.islice() + loop
# Consecutive chunks Product
res = [prod(list(itertools.islice(test_list, i, i + 3))) for i in range(0, len(test_list), 3)]
  
# printing result
print("The chunked product list is : " + str(res))
输出 :
The original list : [4, 7, 8, 10, 12, 15, 13, 17, 14]
The chunked product list is : [224, 1800, 3094]