[Tutor] Calculate 4**9 without using **
Alan Gauld
alan.gauld at yahoo.co.uk
Mon Mar 6 14:27:40 EST 2017
On 06/03/17 19:03, Sri Kavi wrote:
> Wow, this works like a charm!
> def power(base, exponent):
> """ Returns base**exponent. """
> result = 1
> for _ in range(abs(exponent)):
> result *= base
> if exponent < 0:
> return 1 / result
> return result
And just to add to the mix, here's a functional (as in FP)
version:
from functools import reduce
def power(base,exponent):
result = reduce(lambda a,b: a*b, [1] + [base]*abs(exponent))
return result if exponent >= 0 else 1/result
It basically does the same as the previous version
but moves the loop into the reduce function.
All to produce an inferior version of a builtin!
what fun :-)
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list