140k views
3 votes
Python’s pow function returns the result of raising a number to a given power. Define a function expo that performs this task, and state its computational com- plexity using big-O notation. The first argument of this function is the number, and the second argument is the exponent (nonnegative numbers only). You may use either a loop or a recursive function in your implementation. Caution: do not use Python’s ** operator or pow function in this exercise!

User DomQ
by
6.0k points

1 Answer

1 vote

Python:

import math

def expo(base,power):

#Result variable

res = 1

#Special cases

if(power==0 and base!=0): return 1

if(power==0 and base==0): return -1

if(base==0 and power!=0): return 0

if(base!=0 and power==1): return base

#Evaluating

if(power>=1):

for i in range(1,int(power)+1):

res*=base

return res

if(power>0 and power<1):

#Natural logarithm implementation and approx. result

#First, determine the McLaurin Series expansion

nominator = power*math.log(base)

res+=nominator

for i in range(2,7):

idx = 1

for j in range(i):

idx*=nominator

res+=idx/math.factorial(i)

return res

#Input section

b = float(input("Enter base: "))

p = float(input("Enter power: "))

assert p>=0

print()

print("Result:","Undefined!" if (b==0 and p==0) else expo(b,p),"\\Time Complexity: O("+str(b)+"^"+str(p)+")\\")

Python’s pow function returns the result of raising a number to a given power. Define-example-1
User LeChatNoir
by
5.6k points