Skip to main content
3 of 3
deleted 176 characters in body
Ludisposed
  • 11.6k
  • 2
  • 39
  • 91

As I completely misunderstood the question before, here is my second try.

from operator import itemgetter
from itertools import groupby

def r_reduce(r):   
    # Building set items in the range
    range_set = set()
    for sublist in r:
        range_set = range_set | set(range(sublist[0], sublist[1]+1))

    # ! When using the example input !
    # At this stage sets is {2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17}
    
    # And you can clearly see this is a full range
    # Now we can chop the set up in smaller sub_ranges

    # Making ranges of the set
    reduced = []    
    for key, group in groupby(enumerate(sets), lambda i: i[0] - i[1]):        
        r = list(map(itemgetter(1), group))
        reduced.append([r[0], r[-1]])
    return reduced

When you are overcomplicating stuff things get progressively more difficult and prone to bugs. Shorter most of the time really is better.

Now let's break down your code and review:

  1. while loops per se are not a bad idea, it is just using a while loop for this example is overcomplicating stuff. That makes it a bad idea.
  2. reduced_zip_ranges[-1] is awkward because you keep appending that item to the list and refering last element, you could also have stored the range as a variable and keep overwritting it.
Ludisposed
  • 11.6k
  • 2
  • 39
  • 91