0

im trying now for decent time to solve following problem: I have a list of different values, as e.g:

list1 = (17208, 17206, 17203, 17207, 17727, 750, 900, 905)

i want to write a function, which return now all values of this list, which are close to each other for a given correlation length.

So the return in the example should be: res = ([17208,17206,17203,17207],[900,905])

I am already aware of math.isclose(x,y,eps), but i cant apply it to the whole list. If you have any ideas how this function could work like, I would be happy to read about it. Thanks

3 Answers3

1

You can use this:

list1 = [17208, 17206, 17203, 17207, 17727, 750, 900, 905]

list1.sort()
tmp = [list1[0]]
output = []
for i in range(1,len(list1)):
    if list1[i] - tmp[-1]   < eps:
        tmp.append(list1[i])
    else:
        output.append(tmp)
        tmp = [list1[i]]
output.append(tmp)

# for eps = 10 output is [[750], [900, 905], [17203, 17206, 17207, 17208], [17727]]
print(output)
sagi
  • 40,026
  • 6
  • 59
  • 84
0

it depends how want to be close the values, but you could do:

from math import isclose
from itertools import combinations
list1 = (17208, 17206, 17203, 17207, 17727, 750, 900, 905)
res = []
for value in combinations(list1,2):
    print(value[0],value[1],isclose(value[0],value[1]))
    if isclose(value[0],value[1]):
        res.append(list(value))
print(res)
XxJames07-
  • 1,833
  • 1
  • 4
  • 17
  • thanks for your comment, the only issue so far is that i end up with tuples only in the result like [17208,17206],[17208,17203]... instead of an array where all "close" values are included. – William K. Tegtow Jan 23 '22 at 13:20
0

You can use numpy for this:

import numpy as np

l = [17208, 17206, 17203, 17207, 17727, 750, 900, 905]
delta = 10

a = np.array(l)

m = np.abs(np.diff(a, prepend=True)) <= delta
m_roll = np.roll(m, -1)
mask = m + m_roll

indices = np.nonzero(mask[1:] != mask[:-1])[0] + 1
b = np.split(a, indices)
b = b[0::2] if mask[0] else b[1::2]

print(b)
# [array([17208, 17206, 17203, 17207]), array([900, 905])]
Andreas
  • 8,694
  • 3
  • 14
  • 38