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.