0

Possible Duplicate:
Get the cartesian product of a series of lists in Python

Suppose I have an array of length n, representing n variables, and a function f of n variables. I want to sum over f applied to all values of the n variables in some finite set (i.e. {0,1}). Conceptually, it would be something like

for x[1] in {0,1}:
  for x[2] in {0,1}:
     ... 
       sum += f(x[1], ..., x[n])

but obviously you can't write this.

Is there a nice way to do it, say in Python? (For the particular case of values in {0,1}, I could just loop over binary representations of integers from 0 to 2^n-1, but I want a more general solution).

Community
  • 1
  • 1
Tony
  • 173
  • 1
  • 6
  • 2
    You want the Cartesian product; see [this question](http://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists-in-python) among many duplicates-- the hard part is knowing what phrase to search for. Once you have the values, you can use `f(*some_tuple)` to feed the values to the function. – DSM Nov 15 '12 at 03:50
  • Looks like you want a cartesian product. Lookup [`itertools.product`](http://docs.python.org/2/library/itertools.html) – inspectorG4dget Nov 15 '12 at 03:51

1 Answers1

0
# f is a function
# K is a list of possible values your variable may take
# n is number of args that f takes
import itertools

def sum_of_f_over_K_n(f,K,n):
    K_to_the_n = [K for i in xrange(n)]
    return sum(map(lambda(x):f(*x),itertools.product(*K_to_the_n)))

some_list = [0,1] # where your variables come from
def sample_func(a,b,c,d,e):
    return a or b or c or d or e
sum_of_f_over_K_n(sample_func, some_list, 5) == 2**5 -1
gabe
  • 2,521
  • 2
  • 25
  • 37