Identify groups of continuous numbers in a list

前端 未结 13 1923
误落风尘
误落风尘 2020-11-22 01:12

I\'d like to identify groups of continuous numbers in a list, so that:

myfunc([2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 20])

Returns:

         


        
13条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 01:55

    This doesn't use a standard function - it just iiterates over the input, but it should work:

    def myfunc(l):
        r = []
        p = q = None
        for x in l + [-1]:
            if x - 1 == q:
                q += 1
            else:
                if p:
                   if q > p:
                       r.append('%s-%s' % (p, q))
                   else:
                       r.append(str(p))
                p = q = x
        return '(%s)' % ', '.join(r)
    

    Note that it requires that the input contains only positive numbers in ascending order. You should validate the input, but this code is omitted for clarity.

提交回复
热议问题