I\'m trying to format a list of integers with Python and I\'m having a few difficulties achieving what I\'d like.
Input is a sorted list of Integers:
Since the other guy who posted this solution deleted his answer...
Here's a O(n)
string building solution:
def stringify(lst):
result = str(lst[0])
end = None
for index, num in enumerate(lst[1:]):
if num - 1 == lst[index]: # the slice shifts the index by 1 for us
end = str(num)
else:
if end:
result += '-' + end
end = None
result += ', ' + str(num)
# Catch the last term
if end:
result += '-' + str(num)
return result
See the repl.it