DrMankowitz
DrMankowitz

Reputation: 1

How to go through all possibilities efficiently?

I have run into this problem before, but it hasn't been too important until now: going through all combinations given 3 or 4 variables. My current project is in Python, so here is an example:

def function(var1, var2, var3):
    if var1:
        if var2:
            if var3:
                foo(bar)
            else:
                bar(foo)
        else:
            if var3:
                ...

Even this example is a bit simpler than the code I am working with because there are 3 to 4 possibilities for each variable.

I am unfamiliar with many programming concepts and I have a feeling that there is already a good answer to this question. Any help is appreciated. Thanks in advance!

Upvotes: 0

Views: 152

Answers (2)

Jamie Cockburn
Jamie Cockburn

Reputation: 7555

def function(var1, var2, var3):
    def foo():
        pass

    def bar():
        pass

    func = {('past', 'simple', 'first', 'plural'): foo,
            ('past', 'simple', 'first', 'singular'): bar,
            ('past', 'simple', 'second', 'plural'): foo,
            ('past', 'simple', 'secord', 'singular'): bar,
            ...
            }[(var1, var2, var3)]
    func()

Upvotes: 1

jonrsharpe
jonrsharpe

Reputation: 121975

The canonical Python replacement for lots of ifs is a dictionary:

from functools import partial

def function(var1, var2, var3):
    choices = {(True, True, True): partial(foo, bar),
               (True, True, False): partial(bar, foo),
               ...}
    choices[tuple(map(bool, (var1, var2, var3)))]()

(In simple cases like this you could use lambda rather than functools.partial).

Or, in your case:

choices = {("past", "simple", 1, False): ..., 
           ...}

Upvotes: 7

Related Questions