2

What is most pythonic way to convert a set of integers into ranges (there is question about that already converting a list of integers into range in python) BUT with some sort of accepted margin?

Example, we have: 1, 2, 3, 4, 5, 10, 11, 15, 45, 46, 47, 75, 76, 80, 85

so normally we would get: {1,5}, {10, 11}, {15, 15}, {45, 47}, {75, 76}, {80, 80}, {85, 85}

but we want to allow margin of 20, so next range will be created only if the difference between previous item and next item is bigger than 20

As result we should get: {1, 15}, {45, 47}, {75, 85}

Community
  • 1
  • 1
arekm
  • 56
  • 5
  • 7
    If you could start by providing your current solution, we could determine if there is a more Pythonic alternative available. – chepner May 08 '14 at 13:27
  • 1
    If you are looking for comments on/improvements to working code, that is on-topic at http://codereview.stackexchange.com – jonrsharpe May 08 '14 at 13:30
  • I suspect you start by "filling any holes in the sequence less than N", then create the list. This means - find the "opposite" set - the numbers not contained; use the method in the link to find the run lengths; delete the ones with run lengths greater than N; then merge the two sets. – Floris May 08 '14 at 13:30

1 Answers1

1
def to_ranges(nums):
  rngs = []
  start = nums[0]
  curr = start
  for n in nums[1:]:
    if n > curr + 20:
      rngs.append(range(start, curr + 1))
      start = n
    curr = n
  rngs.append(range(start, curr + 1))
  return rngs

>>> to_ranges([1, 2, 3, 4, 5, 10, 11, 15, 45, 46, 47, 75, 76, 80, 85])
[range(1, 16), range(45, 48), range(75, 86)]
jdehesa
  • 58,456
  • 7
  • 77
  • 121