theAlse
theAlse

Reputation: 5747

Refactor a couple of functions into one by accepting sets and returning sets

I have a couple of functions which calculates different statistical data based on input dictionaries, e.g. max, min, sum, average, median.

I would like to combine all these functions into one instead of having them in different methods. so the caller can do something like below:

(minValue, averageValue, maxValue) = myFunction(min, avg, max, data, key, ...)

or

(minValue, maxValue) = myFunction(min, max)

I am new to python, I am trying to understand how this can be achieved using sets! Please do not suggest other ways of solving this problem, as I am trying to learn python and python syntax as well. A small example would be great.

Upvotes: 0

Views: 65

Answers (2)

Andy Hayden
Andy Hayden

Reputation: 375585

def myFunction(data,*args):
    return tuple( f(data) for f in args) )

So for example:

myFunction(data, min, avg, max)
# returns (min(data), avg(data), max(data)), and you can get them by
minValue, averageValue, maxValue = myFunction(data, min, avg, max)

If you want to include key:

def myFunction2(data, *args, **kwargs):
    if 'key' not in kwargs:
        kwargs['key'] = lambda x: x # identity map (pass without a key)
    return tuple( f(data, key=kwargs['key']) for f in args )

So for example:

myFunction2(['a','bc','f'], min, max)          # ('a', 'f')
myFunction2(['a','bc','f'], min, max, key=len) # ('a', 'bc')

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122392

You cannot use sets to do this, because a set has no ordering; thus Python wouldn't know which value was the minValue and which maxValue, for example.

You can return a tuple though:

return value1, value2, value3

Demo:

>>> def foo():
...     return 1, 2, 3
...
>>> retval1, retval2, retval3 = foo()
>>> retval3
3

Upvotes: 0

Related Questions