Mikhail Genkin
Mikhail Genkin

Reputation: 3460

Return different combinations of outputs depending on input

In my functions I have a list params_to_opt that can include any of the following entries: 'a', 'b', 'c', 'd', 'e'.

Example: params_to_opt=['c', 'e', 'a']. It can contain any number (1 to 5) of the entries I specified. It always contains at least one of the above entries.

Depending on this input, I do various calculations:

def MyFunction(params_to_opt):
    if 'a' in params_to_opt:
        out1 = ...
    if 'b' in params_to_opt:
        out2= ...
    if 'c' in params_to_opt:
        out3 = ...
    if 'd' in params_to_opt:
        out4= ...
    if 'e' in params_to_opt:
        out5 = ...

Now I want to return only those values that were calculated. For example, if params_to_opt=['c', 'e', 'a'], I would return out1, out3 and out5.

The problem is that if I was to use if .. else statement again, I would have to consider 31 possible outputs (5+10+10+5+1 depending on the length of my list).

Is there a way to code it more elegantly? I don't care about performance, as the number of outputs is very small compared to the time of calculations of each out1, out2, out3, out4, out5.

Thanks, Mikhail

Upvotes: 1

Views: 86

Answers (3)

bboumend
bboumend

Reputation: 510

Here is an other solution where you can avoid having multiple if statement in a row, which can become hard to maintain at certain point.

l = ['a', 'b']

l2 = ['a', 'c', 'e']

output = {
    'a': 'out1',
    'b': 'out2',
    'c': 'out3',
    'd': 'out4',
    'e': 'out5',
}


def MyFunction(params_to_opt):
    return [output.get(param) for param in sorted(params_to_opt)]


print(MyFunction(l), end='\n')    # ['out1', 'out2']
print(MyFunction(l2))             # ['out1', 'out3', 'out5']

You can put what ever you want in the dictionary: string, function, condition etc

Upvotes: 1

Troma78
Troma78

Reputation: 121

Alternatively you could also use a generator (and use a dict):

dictionary = {'a': 'alpha', 'b': 'beta'}

def MyFunction(params_to_opt):
    for param in params_to_opt:
        if param in dictionary:
            yield dictionary[param]

result = [x for x in  MyFunction(['a', 'b'])]

I've used a simple a and b as input, but this can obviously be adjusted.

Upvotes: 1

Kevin
Kevin

Reputation: 76254

No need for five independent variables; just declare one list, and append to it as necessary.

def MyFunction(params_to_opt):
    results = []
    if 'a' in params_to_opt:
        results.append(...)
    if 'b' in params_to_opt:
        results.append(...)
    if 'c' in params_to_opt:
        results.append(...)
    if 'd' in params_to_opt:
        results.append(...)
    if 'e' in params_to_opt:
        results.append(...)
    return results

Upvotes: 5

Related Questions