Skip to content

Instantly share code, notes, and snippets.

@willy-r
Last active November 26, 2020 23:44
Show Gist options
  • Select an option

  • Save willy-r/f4c8b91fc82666f7757a159c56e3cad1 to your computer and use it in GitHub Desktop.

Select an option

Save willy-r/f4c8b91fc82666f7757a159c56e3cad1 to your computer and use it in GitHub Desktop.

Revisions

  1. willy-r revised this gist Nov 26, 2020. 1 changed file with 21 additions and 6 deletions.
    27 changes: 21 additions & 6 deletions perfect_square.py
    Original 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('n must be integer and positive')
    raise ValueError(f'{n} -> must be integer and non-negative')

    return int(n ** 0.5) ** 2 == n


    def test_examples():
    assert perfect_square(25) is True
    assert perfect_square(10) is False
    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(num)
    result = perfect_square_binary_search(num)
    assert result == expected, f'{result=} != {expected=}'


    if __name__ == '__main__':
    test_cases()
    test_cases()
  2. willy-r created this gist Nov 25, 2020.
    31 changes: 31 additions & 0 deletions perfect_square.py
    Original 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()