[Tutor] Calculate 4**9 without using **
gvmcmt at gmail.com
Mon Mar 6 14:17:46 EST 2017
def power(base, exponent):
""" Returns base**exponent. """
if exponent < 0:
base = 1 / base
exponent = abs(exponent)
result = 1
for _ in range(exponent):
result *= base
On Mon, Mar 6, 2017 at 11:53 PM, Alex Kleider <akleider at sonic.net> wrote:
> On 2017-03-05 23:52, Sri Kavi wrote:
> This version deals with both negative and non-negative exponents in a
>> single loop. I like this.
>> def power(base, exponent):
>> """ Returns base**exponent. """
>> if exponent == 0:
>> return 1
>> result = 1
>> for _ in range(abs(exponent)):
>> result *= base
>> if exponent < 0:
>> return 1 / result
>> return result
>> I'm learning a lot. Thank you for being so helpful.
> I have enjoyed this little exercise, so thank you for drawing attention to
> it and continuing to work at it.
> Note that you don't need the 1st if/else- and even if you did, you
> wouldn't need the 'else': just 'de-iondent' everything that is in its code
> I believe the following (your code with some deletions) will work:
> def power(base, exponent):
> """ Returns base**exponent. """
> result = 1
> for _ in range(abs(exponent)):
> result *= base
> if exponent < 0:
> return 1 / result
> return result
> An alternative way to deal with the negative exponent possibility is to
> test for it at the beginning and if True, set base to its reciprocal and
> exponent to its absolute value (no need for an else component.)
More information about the Tutor