From 6f2ef84a833e21d08680c42777d4d569165ab41d Mon Sep 17 00:00:00 2001 From: ivan Date: Mon, 17 Feb 2025 04:17:45 -0600 Subject: [PATCH] adding pow x n --- .../top_150_questions_round_13/pow_x_n.py | 14 +++++++++ .../test_pow_x_n_round_13.py | 30 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_13/pow_x_n.py create mode 100644 tests/test_150_questions_round_13/test_pow_x_n_round_13.py diff --git a/src/my_project/interviews/top_150_questions_round_13/pow_x_n.py b/src/my_project/interviews/top_150_questions_round_13/pow_x_n.py new file mode 100644 index 00000000..c48b4f0f --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_13/pow_x_n.py @@ -0,0 +1,14 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod + +class Solution: + def myPow(self, x, n): + + if not n: + return 1 + elif n < 0: + return self.myPow(1/x, -n) + elif n % 2: + return x*self.myPow(x,n-1) + else: + return self.myPow(x*x, n//2) \ No newline at end of file diff --git a/tests/test_150_questions_round_13/test_pow_x_n_round_13.py b/tests/test_150_questions_round_13/test_pow_x_n_round_13.py new file mode 100644 index 00000000..2a7e60e8 --- /dev/null +++ b/tests/test_150_questions_round_13/test_pow_x_n_round_13.py @@ -0,0 +1,30 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_13\ +.pow_x_n import Solution + + +class PowxnTestCase(unittest.TestCase): + + def test_powxn_zero_power(self): + solution = Solution() + output = solution.myPow(x=2, n=0) + target = 1 + self.assertEqual(output, target) + + def test_powxn_negative_power(self): + solution = Solution() + output = solution.myPow(x=2, n=-1) + target = 0.5 + self.assertEqual(output, target) + + def test_powxn_odd_power(self): + solution = Solution() + output = solution.myPow(x=2, n=1) + target = 2 + self.assertEqual(output, target) + + def test_powxn_even_power(self): + solution = Solution() + output = solution.myPow(x=2, n=2) + target = 4 + self.assertEqual(output, target) \ No newline at end of file