Adjacent number algorithm grouper

前端 未结 13 1694
不思量自难忘°
不思量自难忘° 2021-02-15 06:55

By which I mean this:

Given the input set of numbers:

1,2,3,4,5 becomes \"1-5\".

1,2,3,5,7,9,10,11,12,14 becomes \"1-3, 5, 7, 9-12, 14\"

This is

13条回答
  •  余生分开走
    2021-02-15 07:48

    Pure functional Python:

    #!/bin/env python
    
    def group(nums):
        def collect((acc, i_s, i_e), n):
            if n == i_e + 1: return acc, i_s, n
            return acc + ["%d"%i_s + ("-%d"%i_e)*(i_s!=i_e)], n, n
        s = sorted(nums)+[None]
        acc, _, __ = reduce(collect, s[1:], ([], s[0], s[0]))
        return ", ".join(acc)
    
    assert group([1,2,3,5,7,9,10,11,12,14]) == "1-3, 5, 7, 9-12, 14"
    

提交回复
热议问题