I am struggling with this since I am sure that a dozen for-loops are not a solution to this problem:
There is a sorted list of numbers like
numbers = [123, 124, 128, 160, 167, 213, 215, 230, 245, 255, 257, 400, 401, 402, 430]
and I want to create a dict with lists of numbers, with the difference in numbers (following each other) not more than 15. Thus, the output will be as follows:
clusters = { 1 : [123, 124, 128], 2 : [160, 167], 3 : [213, 215, 230, 245, 255, 257], 4 : [400, 401, 402], 5 : [430] }
My current solution is a bit ugly (I need to remove duplicates at the end ...), I'm sure it can be done with pythonic.
Here is what I am doing now:
clusters = {} dIndex = 0 for i in range(len(numbers)-1) : if numbers[i+1] - numbers[i] <= 15 : if not clusters.has_key(dIndex) : clusters[dIndex] = [] clusters[dIndex].append(numbers[i]) clusters[dIndex].append(numbers[i+1]) else : dIndex += 1