info & requirements:
len(variables)
When trying to solve this myself I found a solution that could handle functions with 2 parameters, but I don't know how to make it dynamic so it can scale to infinite parameters
# 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:
The above-shown code is not part of the solution, it's just my best try and is just for inspiration.
The result should be that all functions have tried to run with all possible combination of variables as parameters.
You can use itertools
to get all subsets and create recursion function
like this:
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)
to set
to avoid duplication. input_num += 1
after for
The * can also be used for unpacking the containers. Its principles are similar to “For using the variadic arguments” above. The easiest example is that we have data in the form of a list, tuple or
dict
, and a function takes variable arguments.
variables * input_num
can make the duplicated item 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.