Sunday, December 5, 2010

call a function with all possible inputs

>>> import itertools
>>> def try_all(f, *possible_inputs):
...    inputs = itertools.product(*possible_inputs)
...    while True: yield f(*(inputs.next()))
...
>>> def fp(a,b,c): return a,b,c
...
>>> [a for a in try_all(fp, [1], ["a","b"], [2.75, 3.5, 1.375])]
[(1, 'a', 2.75), (1, 'a', 3.5), (1, 'a', 1.375), (1, 'b', 2.75), (1, 'b', 3.5), (1, 'b', 1.375)]

The output is kept in generator form rather than being returned as a list since it is likely to be extremely large.

No comments:

Post a Comment