From 758c00706134dbaa2cb5ba71203567bb66223e38 Mon Sep 17 00:00:00 2001 From: ivan Date: Sat, 7 Dec 2024 04:36:52 -0600 Subject: [PATCH] adding sqrt algo --- .../top_150_questions_round_11/sqrtx.py | 20 +++++++++++++++++++ .../test_sqrtx_round_11.py | 17 ++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_11/sqrtx.py create mode 100644 tests/test_150_questions_round_11/test_sqrtx_round_11.py diff --git a/src/my_project/interviews/top_150_questions_round_11/sqrtx.py b/src/my_project/interviews/top_150_questions_round_11/sqrtx.py new file mode 100644 index 00000000..1e295da6 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_11/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: + left = mid + 1 + elif mid ** 2 > x: + right = mid - 1 + else: + return mid + + return min(left, right) \ No newline at end of file diff --git a/tests/test_150_questions_round_11/test_sqrtx_round_11.py b/tests/test_150_questions_round_11/test_sqrtx_round_11.py new file mode 100644 index 00000000..b2843cf9 --- /dev/null +++ b/tests/test_150_questions_round_11/test_sqrtx_round_11.py @@ -0,0 +1,17 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_11\ +.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