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

Peter Otten __peter__ at web.de
Sun Mar 5 05:24:38 EST 2017


Sri Kavi wrote:

> Like I just said in my other message, I was trying to reply to Tasha
> Burman, but I was in digest mode and I didn't know how to change my
> subscription options in order to reply to individual messages. I also
> don't know if it's an assignment, but I'm a beginner learning to program,
> too :)
> 
>>What if any of the following are true, and what should be done in each
> case?
>>   if exponent ==1: .....
>>   if exponent = 0: .....
>>   if exponent < 0: .....
> 
> Here's my implementation.

> In Python 3.6.0
> 
> def power(base, exponent):
>     if exponent == 0:
>         return 1
>     elif exponent > 0:
>         result = base
> 
>         for _ in range(1, exponent):
>             result *= base
> 
>         return result
>     else:
>         exponent = -exponent
>         result = base
> 
>         for _ in range(1, exponent):
>             result *= base
>         return 1 / result
> 
> Please share your thoughts.

You can try to simplify that a bit:

- Handle the case with non-negative exponents in one branch
- Avoid duplicating the for loop for negative exponents, e. g. by calling
  power() from within power()

Once you have that working you can play around a bit, e. g.

- try an alternative implementation using recursion instead of a loop
- modify the code to minimize the number of multiplications it needs to
  perform to get the result



More information about the Tutor mailing list