RosettaCodeData/Task/Exponentiation-operator/Python/exponentiation-operator.py

16 lines
397 B
Python
Raw Permalink Normal View History

2015-11-18 06:14:39 +00:00
MULTIPLY = lambda x, y: x*y
2013-04-10 16:57:12 -07:00
2015-11-18 06:14:39 +00:00
class num(float):
# the following method has complexity O(b)
# rather than O(log b) via the rapid exponentiation
2013-04-10 16:57:12 -07:00
def __pow__(self, b):
2015-11-18 06:14:39 +00:00
return reduce(MULTIPLY, [self]*b, 1)
2013-04-10 16:57:12 -07:00
2015-11-18 06:14:39 +00:00
# works with ints as function or operator
print num(2).__pow__(3)
print num(2) ** 3
2013-04-10 16:57:12 -07:00
2015-11-18 06:14:39 +00:00
# works with floats as function or operator
print num(2.3).__pow__(8)
print num(2.3) ** 8