GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Python-1/maths/perfect_square.py at master · https-github-com-nzysoft/Python-1 Expand file tree/ Copy pathperfect_square.pyMore file actions 73 lines (64 loc) · 1.77 KB / Copy pathperfect_square.pyFile metadata and controls73 lines (64 loc) · 1.77 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 import math def perfect_square(num: int) -> bool: """ Check if a number is perfect square number or not :param num: the number to be checked :return: True if number is square number, otherwise False >>> perfect_square(9) True >>> perfect_square(16) True >>> perfect_square(1) True >>> perfect_square(0) True >>> perfect_square(10) False """ 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 >>> perfect_square_binary_search(-1) False >>> perfect_square_binary_search(1.1) False >>> perfect_square_binary_search("a") Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'str' >>> perfect_square_binary_search(None) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'NoneType' >>> perfect_square_binary_search([]) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'list' """ 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 doctest.testmod() |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |