Grid search function in Python
Question: I am trying to write a parameter search function to loop over one of the
parameters and repeatedly call a function with all other parameters the same,
other than the one I am searching over. Here is some sample code:

    
    
    def worker1(a, b, c):
        return a + b + c
    
    
    def worker2(d, e, f):
        return d * e * f
    
    
    def search(model, params):
        res = []
    
        # Loop over one of the parameters and repeatedly append to res
        if model == 1:
            res.append(worker1(**params))
        elif model == 2:
            res.append(worker2(**params))
    
        return res
    
    params = dict(a=1, b=2, c=3)
    print search(1, params)
    

I have two workers and they are called depending on the value of the `model`
flag I pass to `search()`. The problem I am trying to solve here is to write a
loop (commented in the code) over the if statements to repeatedly call say
`worker1` by varying only one of the parameters. I want my code to be flexible
- sometimes I want to loop through `a` and keep `b` and `c` the same, but
sometimes I want to loop through `b` and keeping `a` and `c` the same.

I'm open whatever solution suggested, but I think I would be specifying the
search parameters in the `params` dictionary. E.g. To loop `a` over 1,2,3,4, I
would say:

    
    
    `params = dict(a=[1,2,3,4], b=2, c=3)`
    

Also it would be nice if I don't have to modify the code for `worker1` and
`worker2`.

Thank you!


Answer: You could perhaps use `itertools.product` to call your workers with all
combinations of params:  
<http://docs.python.org/2/library/itertools.html#itertools.product>

eg

    
    
    from itertools import product
    
    def worker1(a, b, c):
        return a + b + c
    
    def worker2(d, e, f):
        return d * e * f
    
    def search(model, *params):
        res = []
    
        # Loop over one of the parameters and repeatedly append to res
        for current_params in product(*params):
            if model == 1:
                res.append(worker1(*current_params))
            elif model == 2:
                res.append(worker2(*current_params))
    
        return res
    
    print search(1, [1,2,3,4], [2], [3])
    
    # more complicated combinations are possible:
    print search(1, [1,2,3,4], [2,7,9], [3,13,23,43])
    

I've avoided using keyword arguments as your worker functions take
differently-named args so it wouldn't make much sense.

I'm assuming your worker functions don't actually look like the ones above as
if they did you could further simplify the code using the builtin `sum` and
`reduce` functions.

