在python3中实现查找数组中最接近与某值的元素操作
作者:笔筒188 发布时间:2023-10-30 22:35:19
标签: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))
补充拓展:查询集合中最接近某个数的数
查询集合中最接近某个数的数
/*
★实验任务
给你一个集合,一开始是个空集,有如下两种操作:
向集合中插入一个元素。
询问集合中最接近某个数的数是多少。
★数据输入
输入第一行为一个正整数 N,表示共有 N 个操作。
接下来 N 行,每行一个操作。
对于第一个操作,输入格式为 1 x,表示往集合里插入一个值为 x 的元素。
对于第二个操作,输入格式为 2 x,表示询问集合中最接近 x 的元素是什么。
1<=N<=100000,1<=x<=1000000000。
★数据输出
对于所有的第二个操作,输出一个或者两个整数,表示最接近 x 的元素,有
两个数的情况,按照升序输出,并用一个空格隔开。
如果集合为空,输出一行“Empty!”
数据保证插入的元素两两不同。
输入示例 输出示例
5 Empty!
2 1 2
1 2 2 4
2 3
1 4
2 3
*/
解题思路
一、采用C++ 中map容器,因为它可以实时对输入的元素进行排序。(map的使用可自行百度)
二、当集合为空时,输出“Empty!”;当集合中只有一个元素时,直接输出该元素。
三、下面重点看一般的情况。
1.先查找集合中是否有查询的元素,有则输出该元素
2.没有的话,将该元素先插入集合中,再查找该元素处于集合的某个位置。
若该元素在集合的首位,则输出该数的下一位。
若该元素在集合的末位,则输出该数的上一位。
否则,判断它左右元素的值与它的差的绝对值,输出差的绝对值较小的那个元素。若相等,则同时输出。
#include <iostream>
#include <map>
#include <cmath>
using namespace std;
map <long long ,int> 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 <long long ,int>::iterator it,m,n;
it=a.find(x);
if(it!=a.end() )
{
cout << x <<endl;
continue;
}
a[x]=1;
it=a.find(x);
if(it == a.begin() )
{
it++;
cout << it -> 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;
}
来源:https://blog.csdn.net/GIS_BT/article/details/92004228
0
投稿
猜你喜欢
- 内容介绍将日常工作中遇到的数数据冲突和样本源的方法进行总结,其中主要包括实际业务数据冲突、样本选取问题、数据共线性 等思路,并且长期更新。实
- 爬取xxx天气爬取网址:https://tianqi.2345.com/today-60038.htm安装pip install scrap
- 现在网上出现了很多在线换底色的网页版工具是这么做的呢?其实用Python就可以实现。环境要求Python3 numpy函数库 opencv库
- 我一直都不喜欢在访问数据库时采用拼接SQL的方法,原因有以下几点: 1. 不安全:有被SQL注入的风险。 2. 可能会影响性能:每条SQL语
- 本文实例讲述了Flask框架学习笔记之消息提示与异常处理操作。分享给大家供大家参考,具体如下:flask通过flash方法来显示提示消息:f
- 基本映射映射使用在根据不同URLs请求来产生相对应的返回内容.Bottle使用route() 修饰器来实现映射.from bottle im
- 在面向对象的理论中,有两个核心的概念:类和实例。类可以看成是一个模板,实例就是根据这个模板创建出来的对象。但在 Python 里面,类和实例
- 适配器设计模式是懒得改动某些代码,或者某些接口不方便改动的时候,使用一个特定的封装,一些特定的编写办法,使不同的接口可以使用同种调用方式使用
- pip是常用的python包管理工具,用python的同学,都离不开pip ~~第一种 在系统自带的python2.7的路径下pip是pyt
- 本文内容速览1、绘图数据准备还是使用鸢尾花iris数据集#导入本帖要用到的库,声明如下:import matplotlib.pyplot a
- 本文实例讲述了python中栈的原理及实现方法。分享给大家供大家参考,具体如下:栈(stack),有些地方称为堆栈,是一种容器,可存入数据元
- 程序流Python 解释器在其最简单的级别,以类似的方式操作,即从程序的顶端开始,然后一行一行地顺序执行程序语句。例如,清单 1 展示了几个
- 本文实例为大家分享了python实现抠图的具体代码,供大家参考,具体内容如下其中使用了opencv中的grabcut方法直接上代码# enc
- 一、re模块的基本使用Python里数量词默认是贪婪的,总是尝试匹配尽可能多的字符。正则表达式是用来匹配处理字符串的。假如你需要匹配文本中的
- 例如:[‘a', ‘b', ‘c'] 输出 [‘a', ‘b', ‘c'] [‘a'
- 在使用完模型之后,添加这两行代码即可清空之前model占用的内存:import tensorflow as tffrom keras imp
- 代码如下_init_.pyfrom flask import Flask, request, url_for, redirect, rend
- 原文:Creating a Star Rater using CSS链接:http://komodomedia.com/blog/index
- 问题描述在spring-boot启动时,希望能执行相应的sql文件来初始化数据库。使用配置文件初始化数据库可以在spring-boot的配置
- 本文实例讲述了python监控网站运行异常并发送邮件的方法。分享给大家供大家参考。具体如下:这是一个简单的python开发的监控程序,当指定