I have a list of integers that is sorted and contains no duplicates:
mylist = [2, 5,6,7, 11,12, 19,20,21,22, 37,38, 40]
I want a summarized text representation that shows groups of adjacent integers in a compressed form as a hyphenated pair. To be specific: Adjacent implies magnitude differing by 1. So an integer i is considered to be adjacent to j if j = i ± 1. Recall that the list is sorted. That means that adjacent integers will appear in monotonically increasing series in the list.
So I want some elegant Python that will represent mylist
as the string
"2, 5-7, 11-12, 19-22, 37-38, 40,"
That is,
2
, because the list contains neither 1
nor 3
) is represented as 2,
19,20,21,22
because each member of the group differs from one other member by 1) is represented as ‹lowest›-‹highest›,
that is 19-22,
.I can't believe this is a problem nobody has thought important enough to solve. Feel free to point me at a solution I have missed.
You can try this:
mylist = [2, 5, 6, 7, 11, 12, 19, 20, 21, 22, 37, 38, 40]
ans = []
ret = ''
# assuming mylist is sorted
for i in mylist:
if len(ans) == 0 or ans[-1][1] < i - 1: #if the array is empty or we can't add current value to the last range
ans.append([i, i]) # make a new range
else:
ans[-1][1] = i # add to last range
for i in ans:
# formating
if i != ans[0]:
ret = ret + ' '
if i[0] == i[1]:
ret = f'{ret}{i[0]},'
else:
ret = f'{ret}{i[0]}-{i[1]},'
print(ret)
Hope this helps!