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

Alex Kleider akleider at sonic.net
Sun Mar 5 13:03:12 EST 2017


On 2017-03-05 02:24, Peter Otten wrote:
> 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: .....

New discovery:
This (if exponent ==1) 'special case' ceases to be special if result is 
set to 1 rather than to base. It also simplifies the parameters to the 
range function: range(exponent) rather than range(1, exponent).

>>>   if exponent = 0: .....
>>>   if exponent < 0: .....

If the exponent is negative, one need only reset the base to its 
reciprocal and the the exponent to its absolute value after which the 
same algorithm does the job.
Alternatively you could simply change the exponent to its absolute value 
and set a flag and at the end change res to its reciprocal if your flag 
is set- again avoiding having two separate loops.

>> 
>> 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()


More information about the Tutor mailing list