From 1a17fc480fe047e0bc5754e00ca1af1a522410ce Mon Sep 17 00:00:00 2001 From: ivan Date: Tue, 29 Apr 2025 04:17:55 -0600 Subject: [PATCH] adding algo --- .../top_150_questions_round_15/sqrtx.py | 20 +++++++++++++++ .../test_sqrtx_round_14.py | 25 ++++++++----------- .../test_sqrtx_round_15.py | 18 +++++++++++++ 3 files changed, 49 insertions(+), 14 deletions(-) create mode 100644 src/my_project/interviews/top_150_questions_round_15/sqrtx.py create mode 100644 tests/test_150_questions_round_15/test_sqrtx_round_15.py diff --git a/src/my_project/interviews/top_150_questions_round_15/sqrtx.py b/src/my_project/interviews/top_150_questions_round_15/sqrtx.py new file mode 100644 index 00000000..c58a831e --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_15/sqrtx.py @@ -0,0 +1,20 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod + +class Solution: + def mySqrt(self, x: int) -> int: + + left, right = 0, x + + while left <= right: + + mid = (left + right)//2 + + if mid ** 2 > x: + right = mid - 1 + elif mid ** 2 < x: + left = mid + 1 + else: + return mid + + return min(left, right) \ No newline at end of file diff --git a/tests/test_150_questions_round_14/test_sqrtx_round_14.py b/tests/test_150_questions_round_14/test_sqrtx_round_14.py index 833df0fd..6aa26152 100644 --- a/tests/test_150_questions_round_14/test_sqrtx_round_14.py +++ b/tests/test_150_questions_round_14/test_sqrtx_round_14.py @@ -2,20 +2,17 @@ from src.my_project.interviews.top_150_questions_round_14\ .sqrtx import Solution -class Solution: - def mySqrt(self, x: int) -> int: - left, right = 0, x +class SqrtxTestCase(unittest.TestCase): - while left <= right: + def test_even_sqrtx(self): + solution = Solution() + output = solution.mySqrt(x=4) + target = 2 + self.assertEqual(output, target) - mid = (left + right)//2 - - if mid ** 2 > x: - right = mid - 1 - elif mid ** 2 < x: - left = mid + 1 - else: - return mid - - return min(left, right) + def test_odd_sqrtx(self): + solution = Solution() + output = solution.mySqrt(x=8) + target = 2 + self.assertEqual(output, target) \ No newline at end of file diff --git a/tests/test_150_questions_round_15/test_sqrtx_round_15.py b/tests/test_150_questions_round_15/test_sqrtx_round_15.py new file mode 100644 index 00000000..51ff3317 --- /dev/null +++ b/tests/test_150_questions_round_15/test_sqrtx_round_15.py @@ -0,0 +1,18 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_15\ +.sqrtx import Solution + + +class SqrtxTestCase(unittest.TestCase): + + def test_even_sqrtx(self): + solution = Solution() + output = solution.mySqrt(x=4) + target = 2 + self.assertEqual(output, target) + + def test_odd_sqrtx(self): + solution = Solution() + output = solution.mySqrt(x=8) + target = 2 + self.assertEqual(output, target) \ No newline at end of file