Raise the power

suggest change

Let’s suppose we want to raise x to a number y.

You’d write this as:

def raise_power(x, y):
    return x**y

What if your y value can assume a finite set of values?

Let’s suppose y can be one of [3,4,5] and let’s say you don’t want to offer the end user the possibility to use such a function since it is very computationally intensive. In fact you would check if the provided y assumes a valid value and rewrite your function as:

def raise(x, y):
    if y in (3,4,5):
        return x**y
    raise NumberNotInRangeException("You should provide a valid exponent")

raise is a keyword, so this definition is a SyntaxError. NumberNotInRangeException is not a built-in exception.

Messy? Let’s use the abstract form and specialize it to all three cases: let’s implement them partially.

from functors import partial
raise_to_three = partial(raise, y=3)
raise_to_four = partial(raise, y=4)
raise_to_five = partial(raise, y=5)

The module is functools, not functors. partial was not run, because this import and the name raise fail first.

What happens here? We fixed the y params and we defined three different functions.

No need to use the abstract function defined above (you could make it private) but you could use partial applied functions to deal with raising a number to a fixed value.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents