From List of Integers, Get Number Closest to a Given Value

From list of integers, get number closest to a given value

If we are not sure that the list is sorted, we could use the built-in min() function, to find the element which has the minimum distance from the specified number.

>>> min(myList, key=lambda x:abs(x-myNumber))
4

Note that it also works with dicts with int keys, like {1: "a", 2: "b"}. This method takes O(n) time.


If the list is already sorted, or you could pay the price of sorting the array once only, use the bisection method illustrated in @Lauritz's answer which only takes O(log n) time (note however checking if a list is already sorted is O(n) and sorting is O(n log n).)

from list of integers, get number closest to and less than a given value

What you have is close; you just need to accept only numbers that are less than real_price:

def price(my_list, real_price):
closest_number = min((number for number in my_list if number < real_price), key=lambda x: abs(x - real_price))
return closest_number

my_list = [101,90,70]
real_price = 100
closest_number = price(my_list, real_price)
print(closest_number)

Output:

90

Find the closest elements above and below a given number

Sorting is not necessary, and makes this time complexity O(n logn) when it should be just O(n).

I believe this is what you're looking for, taking advantage of numpy array indexing:

>>> # the smallest element of myArr greater than myNumber
>>> myArr[myArr > myNumber].min()
44

>>> # the largest element of myArr less than myNumber
>>> myArr[myArr < myNumber].max()
4

Find The Closest Number To Numbers Given In A List ~ Python

If you are too new to understand lambda functions yet,

   minimum = float("inf")
setted_list = [2, 9, 6, 20, 15]
value_chosen = 17

for val in setted_list:
if abs(val - value_chosen) < minimum:
final_value = val
minimum = abs(val - value_chosen)


print final_value

Finding index of an item closest to the value in a list that's not entirely sorted

Try the following:

min(range(len(a)), key=lambda i: abs(a[i]-11.5))

For example:

>>> a = [25.75443, 26.7803, 25.79099, 24.17642, 24.3526, 22.79056, 20.84866, 19.49222, 18.38086, 18.0358, 16.57819, 15.71255, 14.79059, 13.64154, 13.09409, 12.18347, 11.33447, 10.32184, 9.544922, 8.813385, 8.181152, 6.983734, 6.048035, 5.505096, 4.65799]
>>> min(range(len(a)), key=lambda i: abs(a[i]-11.5))
16

Or to get the index and the value:

>>> min(enumerate(a), key=lambda x: abs(x[1]-11.5))
(16, 11.33447)

How to get the closest number from a List int with LINQ?

If you use LINQ to Objects and the list is long, I would use:

List<int> list = new List<int> { 2, 5, 7, 10 };
int number = 9;

int closest = list.Aggregate((x,y) => Math.Abs(x-number) < Math.Abs(y-number) ? x : y);

This method is slightly more complex than the solution that Anthony Pegram suggested, but it has as advantage that you don't have to sort the list first. This means that you have a time complexity of O(n) instead of O(n*log(n)) and a memory usage of O(1) instead of O(n).

get closest value to a number in array

int myNumber = 490;
int distance = Math.abs(numbers[0] - myNumber);
int idx = 0;
for(int c = 1; c < numbers.length; c++){
int cdistance = Math.abs(numbers[c] - myNumber);
if(cdistance < distance){
idx = c;
distance = cdistance;
}
}
int theNumber = numbers[idx];

Always initialize your min/max functions with the first element you're considering. Using things like Integer.MAX_VALUE or Integer.MIN_VALUE is a naive way of getting your answer; it doesn't hold up well if you change datatypes later (whoops, MAX_LONG and MAX_INT are very different!) or if you, in the future, want to write a generic min/max method for any datatype.

How to find closest number from a given value using lamba expression with java8 when i receive an Iterable from the parameter?

If you need a collection of n closest values, you will need to sort and slice the result:

public Iterable<Integer> findClosestNumbers(int givenValue, 
Iterable<Integer> numbers, int n) {

return StreamSupport.stream(numbers.spliterator(), false)
.sorted(Comparator.comparingInt(i -> Math.abs(i - givenValue)))
.limit(n)
.collect(Collectors.toList());
}

This will return n (or fewer) numbers in ascending order of their distance from givenValue.



Related Topics



Leave a reply



Submit