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
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor