I wrote a function that tries to partition a list of values into contiguous chunks. A chunk is a set of values in which values from the start through to the end would be present in the list. As an example, consider the list [1,2,3,7,7,8,9]
. This would be partitioned into {1:3, 7:3}
. I could later read that as an interval that starts at 1 of length 3 and an interval that starts at 7 of length 3
.
I came up with the following code :-
values = list(set(values))
values.sort()
ranges = {}
for value in values:
if value - i in ranges:
ranges[value-i] += 1
i += 1
else:
i = 1
ranges[value] = 0
I'm curious if this is the best way to do it. What would be the time complexity of converting a list to a set and back into a list? I'm guessing that would be O(n).
Do you have any suggestions on how this could be done better?