-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_algorithm.py
More file actions
44 lines (36 loc) · 1.07 KB
/
Copy pathbinary_algorithm.py
File metadata and controls
44 lines (36 loc) · 1.07 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
# -*- coding: utf-8 -*-
# @File : 二分法.py
# @Date : 2025/6/11 10:48
# @Desc :
# 定义函数, 传入 function , 计算范围
def calc_range(f):
num = 1
while True:
if f(num):
num *=2
else:
return num
def binary_algorithm(f, max_value):
min_value = max_value // 2
while min_value < max_value-1:
mid = (max_value + min_value) // 2
if f(mid): # 如果成立 说明传入值小于目标值,增大min到mid
min_value = mid
else: # 否则减小区间
max_value = mid
return max_value
if __name__ == '__main__':
sum_ = 0
for target in range(1000):
def qwe(number):
if number < target: # 如果传入值,小于目标值,返回true
return True
return False
max_value = calc_range(qwe)
value = binary_algorithm(qwe,max_value)
if value == target:
print(True)
else:
print(False)
sum_ += 1
print(sum_)