0

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.

theAlse
  • 5,577
  • 11
  • 68
  • 110

2 Answers2

1
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')
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
0

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343