1

I have a list of functions. I want to call each possible combination of these functions, where each function is either called once or not at all. It doesn't matter that order they are in.

Example:

functionList = [function1, function2, function3]

I would like to call function1() on its own and also function1() + function2() and also function1() + function2() + function3() and also function2() etc

How would I implement this in python? I thought to use itertools.combinations however it doesn't seem I can use that for my problem.

Ry-
  • 218,210
  • 55
  • 464
  • 476
5un5h1n3
  • 25
  • 3
  • https://stackoverflow.com/questions/374626/how-can-i-find-all-the-subsets-of-a-set-with-exactly-n-elements – Ry- Mar 31 '17 at 23:24

2 Answers2

2

itertools works fine. But you need to go through the number that you want to use...between 1 and the number in your set. not sure if you need 0 as your degenerate case. The following works. It could be compressed but as-is it's pretty readable. Look up "python function pointer".

import itertools as it

def f1():
    return 1

def f2():
    return 2

def f3():
    return 3

functionList = [f1, f2, f3]
fsets = set([])
for num in range(1, len(functionList)+1):
    for combo in it.combinations(functionList, num):
        fsets.add(combo)

for fc_combo in fsets:
  temp = 0
  for f in fc_combo:
      temp += f()
  print temp
user1269942
  • 3,772
  • 23
  • 33
1

You can use powerset function from the the itertools recipe page:

from itertools import chain, combinations

def powerset(iterable):
    """
    powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
    """
    xs = list(iterable)
    # note we return an iterator rather than a list
    return chain.from_iterable(combinations(xs,n) for n in range(len(xs)+1))

def f1():
    return "f1"

def f2():
    return "f2"

def f3():
    return "f3"

functions = [f1, f2, f3]

for function_comb in powerset(functions):
   out = ""
   if not function_comb:
      continue # skip the empty set of functions
   for f in function_comb:
      out += f()
   print out

It produces the following output:

f1
f2
f3
f1f2
f1f3
f2f3
f1f2f3
pkacprzak
  • 5,537
  • 1
  • 17
  • 37