Skip to content

Perfect square using binary search #2351

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 25, 2020
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions maths/perfect_square.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,36 @@ def perfect_square(num: int) -> bool:
return math.sqrt(num) * math.sqrt(num) == num


def perfect_square_binary_search(n: int) -> bool:
"""
Check if a number is perfect square using binary search.
Time complexity : O(Log(n))
Space complexity: O(1)

>>> perfect_square_binary_search(9)
True
>>> perfect_square_binary_search(16)
True
>>> perfect_square_binary_search(1)
True
>>> perfect_square_binary_search(0)
True
>>> perfect_square_binary_search(10)
False
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tests for -1, 1.1, "a", None, []?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should I first add input validation inside the function, or should I just include those tests ?

Copy link
Member

@cclauss cclauss Aug 25, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Write the tests first and see how your function deals with unexpected input. The trick is to not write validation code if you don't have to. If your function is already going to raise an IndexError, TypeError, ValueError, etc. then you have no work to do. Just look for cases where your code would silently fail or would deliver nonsense results.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it.Thank you so much !
Things should be good now.

"""
left = 0
right = n
while left <= right:
mid = (left + right) // 2
if mid ** 2 == n:
return True
elif mid ** 2 > n:
right = mid - 1
else:
left = mid + 1
return False


if __name__ == "__main__":
import doctest

Expand Down