M
M
Michael2015-08-23 21:03:52
Python
Michael, 2015-08-23 21:03:52

How to check closest to given value?

Hello,
there is a sheet, for example
a = [56,34,25,43,21,65,23,56,23,54]
, then some number comes to the input and you need to take the first 10 numbers that are closest to the sample, both to the left and to the right of it, sets are not an option because they remove duplicates
the question is - how ??

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
ColdSpirit, 2015-08-23
@nextel

Well, here for anyone, I think, to check each number, I would make a rating relative to the number - the modulus of the difference between the incoming and the i-th.
Or, let's say we have an array of 100 numbers. If it is not sorted, we sort it in order and insert the incoming number in its place, then select the ones closest to this number.
The most interesting thing is that in your case the next 10 are the entire presented array =)

Z
zooks, 2015-08-24
@zooks

What if we sort the array and then take 5 numbers to the left and five to the right of the given number?

N
neomichi, 2015-08-24
@neomichi

if initially stored not as a list, but as a binary tree, then good speeds can be achieved
ps Search O(log n) . Insertion, O(log n). Removal, O(log n)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question