本帖最后由 jackz007 于 2021-10-19 15:18 编辑 #coding:gbk
'''本程序产生出 40 个值在 -100~100 之间的随机数,然后,利用二分法找出其中 x , -x 同时存在的数据对'''
import random
def gen(d , n):
k = 0
while k < n :
x = random . randint(-100 , 100)
if not x in d:
d . append(x)
k += 1
def find(d , x):
a , c , r = 0 , len(d) - 1 , -1
while d[a] <= x <= d[c]:
b = a + (c - a) // 2
if d[b] == x:
r = b
break
else:
if d[b] > x:
c = b
else:
a = b + 1
return r
e , d = [] , []
gen(d , 40)
d . sort()
for i in range(len(d)):
x = d[i]
if x and not x in e and not -x in e:
k = find(d , -x)
if k >= 0:
e . append(x)
print('found %d and %d' % (x , -x))
print(*d)
|