Python|三倍积到 K
获得导致特定解决方案的对的产品编号的问题已经处理过很多次,本文旨在将其扩展到 3 个数字,并讨论可以解决此特定问题的几种方法。让我们讨论可以执行此操作的某些方式。
方法#1:使用嵌套循环
这是一种简单的方法,可以解决这个特定问题,并采用外循环迭代每个元素,内循环检查剩余的差异,将配对乘以结果。
# Python3 code to demonstrate
# 3 element product
# using nested loops
# initializing list
test_list = [4, 1, 3, 2, 6, 12]
# initializing product
product = 24
# printing original list
print("The original list : " + str(test_list))
# using nested loops
# 3 element product
res = []
for i in range(0, len(test_list)-2):
for j in range(i + 1, len(test_list)-1):
for k in range(j + 1, len(test_list)):
if test_list[i] * test_list[j] * test_list[k] == product:
temp = []
temp.append(test_list[i])
temp.append(test_list[j])
temp.append(test_list[k])
res.append(tuple(temp))
# print result
print("The 3 product element list is : " + str(res))
输出 :
The original list : [4, 1, 3, 2, 6, 12]
The 3 product element list is : [(4, 1, 6), (4, 3, 2), (1, 2, 12)]
方法 #2:使用itertools.combination()
这个特定的问题也可以使用函数的内置函数以简洁的方式完成。组合函数找到所有采用 K 参数导致特定产品的组合。
# Python3 code to demonstrate
# Triple Product to K
# using itertools.combination()
from itertools import combinations
# function to get the product
def test(val):
prod = 1
for ele in val:
prod *= ele
return (prod == 24)
# initializing list
test_list = [4, 1, 3, 2, 6, 12]
# initializing product
product = 24
# printing original list
print("The original list : " + str(test_list))
# using itertools.combination()
# 3 element product
res = list(filter(test, list(combinations(test_list, 3))))
# print result
print("The 3 product element list is : " + str(res))
输出 :
The original list : [4, 1, 3, 2, 6, 12]
The 3 product element list is : [(4, 1, 6), (4, 3, 2), (1, 2, 12)]