[Tutor] Calculate 4**9 without using **

Alex Kleider akleider at sonic.net
Sun Mar 5 13:21:17 EST 2017


On 2017-03-05 01:42, Sri Kavi wrote:
> I’ve improved it a bit to meet the following conditions:
> 1. type(base) == int and exponent == 0
> 2. base == 0 < exponent
> 3. (base > 0 or base < 0) and exponent > 0
> 4. base > 0 > exponent
> 5. base < 0 > exponent
> 6. base == 0 > exponent
> 
> def power(base, exponent):
>     if type(base) == int and exponent == 0:
>         return 1
>     elif base == 0 < exponent:
>         return 0
>     elif (base > 0 or base < 0) and exponent > 0:
>         result = base
>         for _ in range(1, exponent):
>             result *= base
>         return result
>     elif base > 0 > exponent:
>         exponent = -(exponent)
>         result = base
>         for _ in range(1, exponent):
>             result *= base
>         return 1 / result
>     elif base < 0 > exponent:
>         exponent = -exponent
>         result = base
>         for _ in range(1, exponent):
>             result *= base
>         return 1 / result
>     elif base == 0 > exponent:
>         print('0 cannot be raised to a negative power.')

> #Testing first condition
> print(power(0, 0))
> print(power(-1, 0))
> print(power(1, 0))

> #Testing second condition
> print(power(0, 3))

> #Testing third condition
> print(power(2, 3))
> print(power(-2, 3))

> #Testing fourth condition
> print(power(2, -3))

> #Testing fifth condition
> print(power(-2, -3))
> 
> #Testing sixth condition
> print(power(0, -3))
> 
> 
> I don’t know if it’s anywhere near built-in pow() function, but your 
> reply
> made me think about all those conditions and try to see if I can make 
> my
> previous function code a little better. I need your feedback please.
> 
> 
> Sri

You've made your code much more complicated than it need be.  Also, what 
I suggested before can be simplified considerably.

The fundamental algorithm is:
     result = 1
     for _ in range(exponent):
         result = result * base

The problem arises if the exponent is 0 or negative, so you only need 
test for 2 special cases and take appropriate action.  You've already 
dealt with the first:
     if exponent == 0:
         return 1
There are two ways of dealing with the other- both mentioned in (a) 
previous post(s).

Keep at it!


More information about the Tutor mailing list