信息和要求:
len(variables)
当我自己尝试解决此问题时,我发现了一个可以处理具有2个参数的函数的解决方案,但我不知道如何使其动态化,以便可以扩展到无限个参数
# test input list
# functions = [test_method1, test_method2]
# variables = [1, 2, 3, 4, 5]
for f in functions:
for v in variables: # loop all conditions
try: # checks if combination throws error
f(v)
except TypeError as a: # if amount of parameters is > 1
for v2 in variables: # loop all conditions
try: # tries combination
f(v, v2)
except TypeError as e:
上面显示的代码不是解决方案的一部分,它只是我的最佳尝试,仅用于启发。
结果应该是所有函数都试图以所有可能的变量组合作为参数来运行。
答案 0 :(得分:0)
您可以使用itertools
获取所有子集并创建recursion function
,如下所示:
from itertools import combinations
def test_method1(x):
print("METHOD 1 :", x)
def test_method2(x, y):
print("METHOD 2 :", x, y)
functions = [test_method1, test_method2]
variables = [1, 2, 3, 4, 5]
def run_all_methods(input_num):
if input_num > len(variables):
return
for item in functions:
try:
for var_list in set(combinations(variables * input_num,input_num)):
item(*list(var_list))
input_num += 1
except TypeError as a:
run_all_methods(input_num+1)
run_all_methods(1)
OUT:
===
METHOD 1 : 2
METHOD 1 : 5
METHOD 1 : 3
METHOD 1 : 1
METHOD 1 : 4
METHOD 2 : 1 3
METHOD 2 : 2 1
METHOD 2 : 5 1
METHOD 2 : 2 5
METHOD 2 : 1 2
METHOD 2 : 3 3
METHOD 2 : 5 5
METHOD 2 : 4 4
METHOD 2 : 1 5
METHOD 2 : 2 2
METHOD 2 : 3 4
METHOD 2 : 4 1
METHOD 2 : 1 1
METHOD 2 : 3 2
METHOD 2 : 5 4
METHOD 2 : 4 5
METHOD 2 : 1 4
METHOD 2 : 2 3
METHOD 2 : 4 2
METHOD 2 : 3 5
METHOD 2 : 5 3
METHOD 2 : 3 1
METHOD 2 : 4 3
METHOD 2 : 5 2
METHOD 2 : 2 4
combinations(variables,input_num)
投射到set
以避免重复。input_num += 1
之后添加for
*也可用于打开包装箱。它的原理类似于上面的“使用可变参量”。最简单的示例是,我们具有列表,元组或
dict
形式的数据,并且一个函数接受可变参数。
variables * input_num
可以使重复项exp:a ==> [1, 2]
combinations(a, 2) => (1, 2)
a * 2 ==> [1, 2, 1, 2]
combinations(b, 2) => (1, 2)
(1, 1)
(1, 2)
(2, 1)
(2, 2)
(1, 2)
set(combinations(b, 2)) => (1, 2)
(1, 1)
(2, 1)
(2, 2)