Last active
November 26, 2020 23:44
-
-
Save willy-r/f4c8b91fc82666f7757a159c56e3cad1 to your computer and use it in GitHub Desktop.
Revisions
-
willy-r revised this gist
Nov 26, 2020 . 1 changed file with 21 additions and 6 deletions.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -1,17 +1,32 @@ 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), @@ -23,9 +38,9 @@ def test_cases(): ) for num, expected in CASES: result = perfect_square_binary_search(num) assert result == expected, f'{result=} != {expected=}' if __name__ == '__main__': test_cases() -
willy-r created this gist
Nov 25, 2020 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,31 @@ def perfect_square(n: int) -> bool: if n < 0 or not isinstance(n, int): raise ValueError('n must be integer and positive') return int(n ** 0.5) ** 2 == n def test_examples(): assert perfect_square(25) is True assert perfect_square(10) is False def test_cases(): CASES = ( (0, True), (1, True), (9, True), (49, True), (64, True), (2, False), (3, False), (15, False), ) for num, expected in CASES: result = perfect_square(num) assert result == expected, f'{result=} != {expected=}' if __name__ == '__main__': test_cases()