How would you display an array of integers as a set of ranges? (algorithm)

后端 未结 16 2887
我在风中等你
我在风中等你 2021-02-15 18:04

Given an array of integers, what is the simplest way to iterate over it and figure out all the ranges it covers? for example, for an array such as:

$numbers = ar         


        
16条回答
  •  抹茶落季
    2021-02-15 18:19

    Python (>= 2.6)

    This version additionally handles duplicates and unsorted sequences.

    from __future__ import print_function
    
    def ranges(a):
        a.sort()
        i = 0
        while i < len(a):
            start = i
            while i < len(a)-1 and a[i] >= a[i+1]-1:
                i += 1
            print(a[start] if a[start] == a[i] else "%d-%d" % (a[start], a[i]),
                  end="," if i < len(a)-1 else "\n")
            i += 1
    

    Example:

    import random
    r = range(10)
    random.shuffle(r)
    ranges(r)
    ranges([1,3,4,5,6,8,11,12,14,15,16]);
    ranges([])
    ranges([1])
    ranges([1, 2])
    ranges([1, 3])
    ranges([1, 3, 4])
    ranges([1, 2, 4])
    ranges([1, 1, 2, 4])
    ranges([1, 2, 2, 4])
    ranges([1, 2, 2, 3, 5, 5])
    

    Output:

    0-9
    1,3-6,8,11-12,14-16
    1
    1-2
    1,3
    1,3-4
    1-2,4
    1-2,4
    1-2,4
    1-3,5
    

提交回复
热议问题