栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

在python3中实现查找数组中最接近与某值的元素操作

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在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))

补充拓展:查询集合中最接近某个数的数

查询集合中最接近某个数的数

解题思路

一、采用C++ 中map容器,因为它可以实时对输入的元素进行排序。(map的使用可自行百度)

二、当集合为空时,输出“Empty!”;当集合中只有一个元素时,直接输出该元素。

三、下面重点看一般的情况。

1.先查找集合中是否有查询的元素,有则输出该元素

2.没有的话,将该元素先插入集合中,再查找该元素处于集合的某个位置。

若该元素在集合的首位,则输出该数的下一位。

若该元素在集合的末位,则输出该数的上一位。

否则,判断它左右元素的值与它的差的绝对值,输出差的绝对值较小的那个元素。若相等,则同时输出。

#include 
#include 
#include  
using namespace std;
map  a;
int main()
{
	a.clear() ;
	int N,t;
	long long int x;
	cin >> N;
	while(N--)
	{
		cin >> t >> x;
		if(t==1)
			a[x]=1;
		else
		{
			if(a.empty() )//判断集合是否为空 
				cout << "Empty!n" ;
			else
			{
				if(a.size() == 1 )//若只有一个元素,则直接输出 
					cout << a.begin()->first << endl;
				else
				{
					map ::iterator it,m,n;
					it=a.find(x);
					if(it!=a.end() )
					{
						cout << x < first << endl;
					} 
					else if(it == a.end() )
					{
						it--;
						cout << it -> first << endl; 
					}
					else
					{
						m=--it;//m和n分别指向it的左右两侧 
						it++;
						n=++it;
						if(abs(m -> first - x) > abs(n -> first - x))
							cout << n -> first << endl;
						else if(abs(m -> first - x) == abs(n -> first - x))	
							cout << m -> first << " " << n -> first << endl;
						else
							cout << m -> first << endl;		
					}
					a.erase(a.find(x) ); 	
				}	 
			}	
		}	
	}
	return 0;
}

以上这篇在python3中实现查找数组中最接近与某值的元素操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/20864.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号