If you have a problem understanding a concept you could post that here and thats where we come in and help you understand or clarify things.
Sorry, i did look up some stuff and i think i get what its saying, but im doing these exercises on pyschools, and they want me to Write a recursive function power(x, y) to calculate the value of x raised to the power of y. I dont understand how to do this, or in this particular case, why?! There are many easier ways to do this.
It's not a real life program, it's an academic exercise. Basic recursion is related to the mathematical notion of 'induction formula'. Here the more obvious induction formula is that x ** y = x * (x ** (y-1)) . From this idea, you should be able to write a recursive function.
Also note that more efficient induction formulas exist for this: x ** y = ((x ** z) ** 2) * (x ** r) if y = 2 * z + r is the euclidian division of y by 2.
Alright, try to think algorithmically. Here is a pseudo code procedure to compute x raised to the power of y
to compute x raised to the power of y:
check that y is an integer >= 1
if y == 1:
compute x raised to the power of y - 1
multiply this result by x
return the result
This algorithm involves computing x raised to the power of (y - 1), that is to say the algorithm calls itself recursively.
Now let's translate this to python code. We are writing a function power(x, y) which computes x raised to the power of y. The best way to understand the code is to use an induction hypothesis like in mathematics: we suppose that if y > 1, the call power(x, y-1) actually returns x raised to the power of y-1. Then we can write our function
def power(x, y):
if not(isinstance(y, (int, long))) or y < 1:
raise ValueError(("invalid value for power()", y))
if y == 1:
# the induction hypothesis is that power(x, y-1) returns x ** (y-1)
return x * power(x, y-1)
Binary verion had elif branches in wrong order and **0 wrong, here corrected:
if y < 0:
raise ValueError('Power can not be negative or fractional: %s.' % y)
elif y == 0:
elif y == 1:
p = power(x, y//2)
return x*p*p if y & 1 else p*p
assert power(6,7) == 6**7
assert power(0, 0) == 0**0
# () is a must in following **
assert power(-3432, 2) == (-3432)**2