Best way to find similar objects in python

I have 1M numbers: N [] and 1 is the singular n, now I want to find in those 1M numbers that look like this singular, for example, in the field [n-10, n + 10]. what's the best way in python to do this? Do I need to sort the number 1M and iterate?

+3
source share
3 answers

[x for x in N if n - 10 <= x <= n + 10]

+3
source
results=[x for x in numbers if x >= n-10 and x <= n+10]
+1
source

Another solution:

is_close_to_n = lambda x: n-10 <= x <= n+10
result = filter(is_close_to_n, N)

Generalization bits:

def is_close_to(n):
    f = lambda x: n-10 <= x <= n+10
    return f

result12 = filter(is_close_to(12), N)
result123 = filter(is_close_to(123), N)

Do not sort. Sorting is, generally speaking, O (n log n); brute force search is O (n).

+1
source

Source: https://habr.com/ru/post/1739563/


All Articles