Code golf: combining multiple sorted lists into a single sorted list

前端 未结 26 2007
余生分开走
余生分开走 2020-12-29 12:42

Implement an algorithm to merge an arbitrary number of sorted lists into one sorted list. The aim is to create the smallest working programme, in whatever language you like.

26条回答
  •  半阙折子戏
    2020-12-29 12:59

    I don't think you can get much better than @Sykora's response, here, for Python.

    Changed to handle your inputs:

    import heapq
    def m(i): 
        return list(heapq.merge(*i))
    
    print m(((1, 4, 7), (2, 5, 8), (3, 6, 9)))
    

    For the actual function, 59 characters, or the 52 in reduced version:

    import heapq
    def m(i): return list(heapq.merge(*i))
    

    This also has the benefit of using a tested and true implementation built into Python

    Edit: Removed the semi-colons (thanks @Douglas).

提交回复
热议问题