在在python3中实现查找数组中最接近与某值的元素操作中实现查找数组中最接近与某值的元素操作
我就废话不多说了,直接上代码吧!
import datetime
def find_close(arr, e):
start_time = datetime.datetime.now()
size = len(arr)
idx = 0
val = abs(e - arr[idx])
for i in range(1, size):
val1 = abs(e - arr[i])
if val1 < val:
idx = i
val = val1
use_time = datetime.datetime.now() - start_time
return arr[idx], use_time.seconds * 1000 + use_time.microseconds / 1000
def find_close_fast(arr, e):
start_time = datetime.datetime.now()
low = 0
high = len(arr) - 1
idx = -1
while low <= high:
mid = int((low + high) / 2)
if e == arr[mid] or mid == low:
idx = mid
break
elif e > arr[mid]:
low = mid
elif e < arr[mid]:
high = mid
if idx + 1 < len(arr) and abs(e - arr[idx]) > abs(e - arr[idx + 1]):
idx += 1
use_time = datetime.datetime.now() - start_time
return arr[idx], use_time.seconds * 1000 + use_time.microseconds / 1000
if __name__ == "__main__":
arr = []
f = open("1Mints.txt")
for line in f:
arr.append(int(line))
f.close()
arr.sort()
while 1:
e = int(input("input a number:"))
print("find_close ", find_close(arr, e))
print ("find_close_fast ", find_close_fast(arr, e))
补充拓展:查询集合中最接近某个数的数补充拓展:查询集合中最接近某个数的数
查询集合中最接近某个数的数查询集合中最接近某个数的数
/*
★实验任务
给你一个集合,一开始是个空集,有如下两种操作:
评论0
最新资源