Skip to content

Commit fea4d8b

Browse files
committed
Add problem 50 - Pow (x, n)
1 parent 436a82b commit fea4d8b

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

problems/math/pow_xn.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
class PowXN:
2+
def myPow(self, x: float, n: int) -> float:
3+
if n == 0:
4+
return 1
5+
if n < 0:
6+
return 1 / x * self.myPow(1 / x, -n - 1)
7+
return self.myPow(x * x, n // 2) if n % 2 == 0 else x * self.myPow(x * x, n // 2)

tests/math/pow_xn_test.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import unittest
2+
3+
from problems.math.pow_xn import PowXN
4+
5+
6+
class TestPowXN(unittest.TestCase):
7+
8+
def setUp(self):
9+
self.pow_xn = PowXN()
10+
11+
def test_power_zero_exponent(self):
12+
self.assertAlmostEqual(self.pow_xn.myPow(2.0, 0), 1.0, places=5)
13+
14+
def test_power_negative_exponent(self):
15+
self.assertAlmostEqual(self.pow_xn.myPow(2.0, -2), 0.25, places=5)
16+
17+
def test_power_positive_exponent_even(self):
18+
self.assertAlmostEqual(self.pow_xn.myPow(2.0, 4), 16.0, places=5)
19+
20+
def test_power_positive_exponent_odd(self):
21+
self.assertAlmostEqual(self.pow_xn.myPow(2.0, 3), 8.0, places=5)
22+
23+
def test_power_base_zero(self):
24+
self.assertAlmostEqual(self.pow_xn.myPow(0.0, 5), 0.0, places=5)
25+
26+
def test_power_base_one(self):
27+
self.assertAlmostEqual(self.pow_xn.myPow(1.0, 5), 1.0, places=5)
28+
29+
def test_power_base_negative_one_odd(self):
30+
self.assertAlmostEqual(self.pow_xn.myPow(-1.0, 3), -1.0, places=5)
31+
32+
def test_power_base_negative_one_even(self):
33+
self.assertAlmostEqual(self.pow_xn.myPow(-1.0, 2), 1.0, places=5)
34+
35+
36+
if __name__ == '__main__':
37+
unittest.main()

0 commit comments

Comments
 (0)