user14438233
user14438233

Reputation:

Trying to create a function that can find the closest numbers in an array

def deze(x,y,z):
    nw = map(lambda q: abs(q-y),x)

    minimum = min(nw)

    anw = []
    for i,val in enumerate(x):
        if val == minimum:
            anw.append(i)

    final = []
    for i in an:
        final.append(x[i])

    return final

This is what I have written so far as a way to find the closest number but it doesn't seem to work correctly. The formal parameters are as such x is the list, y is the number to find the closest number to, and z is how many numbers in that list are the closest to y.

For example [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]=x, 5=y, 3=z.

This should yield [5, 4, 6]

Upvotes: 0

Views: 62

Answers (2)

Chris
Chris

Reputation: 16147

This solves your problem, but keep in mind if you have duplicates in our list, like 2 5 for example the you will actually have two numbers 0 digits away (both 5s) and two numbers 1 digit away (4 and 6). This code would return the lower number of the two.

y = 5
z = 3
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def nn(x,y,z):
    d = [(n, abs(n - y)) for n in sorted(x)]
    out = sorted(d, key=lambda x: x[1])
    return [x[0] for x in out[:z]]

Upvotes: 0

sytech
sytech

Reputation: 40901

Here's a slight modification of your approach.

First sort x, ranking elements by how 'close' they are to y. Then, enumerate the sorted object, gathering z elements, then stopping and returning the gathered items.

def nn(x,y,z):
    closest = sorted(x, key=lambda i: abs(i-y))
    ans = []
    for count, item in enumerate(closest):
        if count == z:
            break
        ans.append(item)
    return ans

Upvotes: 1

Related Questions