forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperfect_cube.py
55 lines (48 loc) · 1.32 KB
/
perfect_cube.py
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
defperfect_cube(n: int) ->bool:
"""
Check if a number is a perfect cube or not.
>>> perfect_cube(27)
True
>>> perfect_cube(4)
False
"""
val=n** (1/3)
return (val*val*val) ==n
defperfect_cube_binary_search(n: int) ->bool:
"""
Check if a number is a perfect cube or not using binary search.
Time complexity : O(Log(n))
Space complexity: O(1)
>>> perfect_cube_binary_search(27)
True
>>> perfect_cube_binary_search(64)
True
>>> perfect_cube_binary_search(4)
False
>>> perfect_cube_binary_search("a")
Traceback (most recent call last):
...
TypeError: perfect_cube_binary_search() only accepts integers
>>> perfect_cube_binary_search(0.1)
Traceback (most recent call last):
...
TypeError: perfect_cube_binary_search() only accepts integers
"""
ifnotisinstance(n, int):
raiseTypeError("perfect_cube_binary_search() only accepts integers")
ifn<0:
n=-n
left=0
right=n
whileleft<=right:
mid=left+ (right-left) //2
ifmid*mid*mid==n:
returnTrue
elifmid*mid*mid<n:
left=mid+1
else:
right=mid-1
returnFalse
if__name__=="__main__":
importdoctest
doctest.testmod()