[Tutor] Calculate 4**9 without using **
Sri Kavi
gvmcmt at gmail.com
Sat Mar 4 23:43:46 EST 2017
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 2.7.12
def power(base, exponent):
if exponent == 0:
return 1
elif exponent > 0:
result = base
for _ in xrange(1, exponent):
result *= base
return result
else:
exponent = -exponent
result = base
for _ in xrange(1, exponent):
result *= base
return 1.0 / result
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.
On Sun, Mar 5, 2017 at 7:37 AM, Alex Kleider <akleider at sonic.net> wrote:
> On 2017-03-04 08:17, Sri Kavi wrote:
>
> I'm a beginner learning to program with Python. I'm trying to explain a
>> solution in plain English. Please correct me if I'm wrong.
>>
>
> Create a function that takes base and exponent as arguments.
>>
>
> Is seems that you are facing the same problem as Tasha Burman.
> Sounds like an assignment meant to exercise your use of iteration.
> i.e. ** and various built in power functions that have been suggested are
> out of bounds.
>
> In the body of the function:
>> set a result variable to the base.
>>
>
> def pwr(base, exponent):
> ....
> res = base
> ...
>
>> User a for-loop with a range of 1 to the exponent.
>>
>
> for i in range(begin, end): # The challenge is to pick begin and end.
>
> end will be a function of exponent but not exponent itself.
> I don't think 1 is a good choice for begin.
> Picking the correct begin is related to dealing with the following:
>
> 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: .....
> Each of the first two might deserve its own return statement.
>
>
>> With each iteration, set the result to the product of result times base.
>>
>
> res *= base # same as res = res * base
>
>
> It's a fun little exercise- a bit more complex than I initially thought it
> would be.
>
> Please share your implementation.
>
More information about the Tutor
mailing list