Python rounding list

Asked

Viewed 71 times

-4

a = [1.2,2.3,3.4]
b = [4.1,5.2,6.3]
x = 3.4
y = a.index(x)
print (y)
y1 = b[y]
print (y1)

As I would in the code if x were 3. and I wanted to show the nearest value. in the case if x = 3, y would receive position 2 ie 3.4

  • 1

    Ever heard of binary search (Binary search)?

2 answers

1

I see both the a and b list are ordered.

Assuming that all the lists for which you belong to test are also ordered, what I recommend is to do a binary search for the nearest value.

My suggestion is this::

def binary_search_closest(l, item):
    last = len(l) - 1
    mid = last // 2

    if l[mid] == item:
        return mid

    else:
        if last == 1:  # apenas 2 elementos
            if abs(l[0] - item) < abs(l[1] - item):
                return 0
            else:
                return 1
        elif item < l[mid]:
            return binary_search_closest(l[:mid + 1], item)  # incluir o l[mid] para o caso de arredondamento
        else:
            return mid + binary_search_closest(l[mid:], item)

If the lists are not sorted, I will just go through the whole list and save the next one, as well as its difference in relation to the item.

My hiccup:

def find(l, item):
    closest = (0, abs(item - l[0]))  # tuplo com indice do valor mais proximo e a sua diferença em relação ao item
    for i in range(len(l)):
        dif = abs(item - l[i])
        if dif == 0:  # se encontrou o item na lista
            return i
        elif dif < closest[1]:
            closest = (i, dif)

    return closest[0]

Note that in this case if there are 2 elements of the list with the same difference it will only return the Dice of the first one that appears.

For example in: a=[1.0, 2.5, 3.5] If you search for the value 3 it will return the Dice 1, to the value 2.5

0

Good night!

Try to do it this way: * need to import numpy library

import numpy as np

a = np.array([1.2,2.3,3.4])
b = np.array([4.1,5.2,6.3])

x = 3.0

idx = (np.abs(a-x)).argmin()
print(idx)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.