Say I have a list of 50 random numbers. I want to group the numbers in a way that each subset has a min-max gap less than a cutoff 0.05. Below is my code.
JavaScript
x
18
18
1
import random
2
3
def cluster(data, cutoff):
4
data.sort()
5
res = []
6
old_x = -10.
7
for x in data:
8
if abs(x - old_x) > cutoff:
9
res.append([x])
10
else:
11
res[-1].append(x)
12
old_x = x
13
return res
14
15
cutoff = 0.05
16
data = [random.random() for _ in range(50)]
17
res = cluster(data, cutoff)
18
Check if all subsets have min-max gaps less than the cutoff:
JavaScript
1
2
1
print(all([(max(s) - min(s)) < cutoff for s in res]))
2
Output:
JavaScript
1
2
1
False
2
Obviously my code is not working. Any suggestions?
Advertisement
Answer
Following @j_random_hacker’s answer, I simply change my code to
JavaScript
1
12
12
1
def cluster(data, cutoff):
2
data.sort()
3
res = []
4
old_x = -10.
5
for x in data:
6
if abs(x - old_x) > cutoff:
7
res.append([x])
8
old_x = x
9
else:
10
res[-1].append(x)
11
return res
12
Now it is working as expected
JavaScript
1
3
1
>>> print(all([(max(s) - min(s)) < cutoff for s in res]))
2
True
3