Last active
November 26, 2020 23:44
-
-
Save willy-r/f4c8b91fc82666f7757a159c56e3cad1 to your computer and use it in GitHub Desktop.
Given a positive integer n, write a function that returns true if it is a perfect square and false otherwise. Don’t use any built-in math functions like sqrt.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def perfect_square(n: int) -> bool: | |
if n < 0 or not isinstance(n, int): | |
raise ValueError(f'{n} -> must be integer and non-negative') | |
return int(n ** 0.5) ** 2 == n | |
def perfect_square_binary_search(n: int) -> bool: | |
if n < 0 or not isinstance(n, int): | |
raise ValueError(f'{n} -> must be integer and non-negative') | |
low = 0 | |
high = n | |
while low <= high: | |
mid = (high - low) // 2 + low | |
if mid ** 2 > n: | |
high = mid - 1 | |
elif mid ** 2 < n: | |
low = mid + 1 | |
else: | |
return True | |
# Can't be a perfect square. | |
return False | |
def test_cases(): | |
CASES = ( | |
(25, True), | |
(10, False), | |
(0, True), | |
(1, True), | |
(9, True), | |
(49, True), | |
(64, True), | |
(2, False), | |
(3, False), | |
(15, False), | |
) | |
for num, expected in CASES: | |
result = perfect_square_binary_search(num) | |
assert result == expected, f'{result=} != {expected=}' | |
if __name__ == '__main__': | |
test_cases() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment