1

I am writing a function that takes a list with sorted integers and returns a string with any found integer ranges. For example:

my_list = [1,2,3,4,5,10,12,13,14,15]

find_range(my_list)  -> "1-5, 10, 12, 13-15"

The function that I've written so far kind of works, but I think it is overly complicated...there must be a better, more pythonic way of accomplishing this.

I am looking for any feedback/comments as to how this task can be solved.

def find_range(int_list):

   range_str = ''
   index_end = len(int_list)
   index_begin = 0

   while (index_begin < index_end):
       val_save = int_list[index_begin]
       index_next = index_begin + 1

       if index_next == index_end:
           if str(val_save) in range_str:
               break
           else:
               range_str += str(val_save)
               break

       value_begin, value_next = int_list[index_begin], int_list[index_next]

       while (value_next == value_begin + 1 and index_next + 1 < index_end):
           index_begin += 1
           index_next += 1
           value_begin, value_next = int_list[index_begin], int_list[index_next]

       index_begin += 1

       if index_begin + 1 == index_end:
           if int(int_list[index_begin]) == (1 + value_begin):
               value_begin +=1

       if val_save != value_begin:
           range_str += str(val_save) + "-" + str(value_begin) + " , "
       else:
           range_str += str(value_begin) + " , "

   return range_str

Thanks in advance for your feedback/comments.

  • 1
    wait where did the 13 go? – m0bi5 Feb 19 '15 at 16:42
  • 7
    I'm voting to close this question as off-topic because it belongs on http://codereview.stackexchange.com – jonrsharpe Feb 19 '15 at 16:44
  • @jonrsharpe Considering the answers this question has received, those answers would not be acceptable on Code Review. For future reference, yes, *the question* is on-topic on Code Review, but would be approached much differently. – Simon Forsberg Feb 19 '15 at 16:50
  • @SimonAndréForsberg the *question* belongs on CR, not the current answers - there weren't any when I voted! – jonrsharpe Feb 19 '15 at 16:56
  • @jonrsharpe Yes, I know. I'm just saying this so that the question isn't flagged for *migration*. Migrating bad answers for target site is bad. I saw your comment was there when the answers appeared. – Simon Forsberg Feb 19 '15 at 16:58

1 Answers1

3

From the docs:

from operator import itemgetter
from itertools import groupby
def contiguous_ints(lst): 
    ranges = [] 
    # Loop through the list of ints, and break it into lists of contiguous ints
    for k, g in grouby(enumerate(lst), lambda (i, x): i-x): 
        ranges.append(map(itemgetter(1), g) 
    # Print the first and last values of each list of contiguous ints
    for i in ranges:       
        print("%s-%s" % (i[0], i[-1]))

fixed the formatting some.

Tui Popenoe
  • 2,098
  • 2
  • 23
  • 44