Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Text representation of a list with gaps

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"2, 5-7, 11-12, 19-22, 37-38, 40,"

That is,

  • an isolated integer (example: 2, because the list contains neither 1 nor 3) is represented as 2,
  • a group of adjacent integers (example: 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.

>Solution :

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading