Reputation: 85
I'm pretty new to python as a whole so apologies, but i'm tasked with building a standalone power function for exponents upto 4.
So far i have;
def power(x,n):
if(n==1):
return x
if(n==2):
return square(x)
if(n==3):
return cube(x)
if(n==4):
return hypercube(x)
with the square, cube and hypercube functions being;
def square(x):
return x*x
def cube(x):
return x*x*x
def hypercube(x):
return x*x*x*x
I'm trying to replace the square, cube and hypercube functions with calls to the power function itself, but i'm having trouble understanding recursive call. I tried the following thinking you just have to call from within directly to the end result. I'm struggling just being able to visualise this
def power(x,n):
if(n==1):
return x
if(n==2):
return power(x^)
if(n==3):
return power(x^n)
if(n==4):
return power(x^n)
Upvotes: 0
Views: 683
Reputation: 29089
You can use direct recursion like so
def power(x, n):
if n == 0:
return 1
return x * power(x, n - 1)
Upvotes: 2