-
Notifications
You must be signed in to change notification settings - Fork 0
/
374_guess_number_higher_or_lower.py
60 lines (46 loc) · 1.42 KB
/
374_guess_number_higher_or_lower.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
56
57
58
59
60
"""
374. Guess Number Higher or Lower
We are playing the Guess Game. The game is as follows:
I pick a number from 1 to n. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked
is higher or lower than your guess.
You call a pre-defined API int guess(int num), which returns three possible
results:
-1: Your guess is higher than the number I picked (i.e. num > pick).
1: Your guess is lower than the number I picked (i.e. num < pick).
0: your guess is equal to the number I picked (i.e. num == pick).
Return the number that I picked.
"""
class Solution(object):
def guessNumber(self, n):
"""
:type n: int
:rtype: int
"""
left, right = 1, n
while left <= right:
mid = (left + right) // 2
result = guess(mid)
if result == 0:
return mid
elif result == 1:
left = mid + 1
else:
right = mid - 1
return -1
s = Solution()
# Case 1
result1 = s.guessNumber(10)
expected1 = 6
print(f"Result: {result1}, Expected: {expected1}")
assert result1 == expected1
# Case 2
result2 = s.guessNumber(1)
expected2 = 1
print(f"Result: {result2}, Expected: {expected2}")
assert result2 == expected2
# Case 1
result3 = s.guessNumber(2)
expected3 = 1
print(f"Result: {result3}, Expected: {expected3}")
assert result3 == expected3