Search code examples
pythonlistlexicographic

List of increasing lists


Given integers n >= m, I want to build the list of all increasing lists of length m with elements the set {1,...,n}.

For instance, if n= 4 and m=2, I want [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]].

Is there a nice way to do that with very few lines of Python code?

I would like to build an efficient function

def listOfLists(n, m):
    ????
    return ? # the list of all increasing lists of m elements in {1, 2, ..., n}

Thanks!

Remark: I have basically done this, but my code is ridiculously long https://sagecell.sagemath.org/?z=eJxVkcFuwyAQRO98xR5Bdqo66ikq-YJIvfRm5eDIuF2ZbBB21H5-FpYWh4PFmHmzHjy6Ccj9rp_34J2eWyBzUMArvQQLc384Zx1YeEd6NlkiywA76LL6-Ubv2ItnsJbPGiA-C5Ik9p0t3hScjI19ghHeJbBC4mw6Dq1UgST0PyO69R4pu5QauZPHZf2YTvxcNLUQSiuceMgRqA4pZC8tZx7Vv8p-ukUegQRxoC-nu5qSnS9DCI5GjXIhl2HBJdEVjk_wBel2xcHL56Qim7RM_yWmOzd1UGm_-UPbyplUKkSkVW9bv7WwN-YBIpR8dQ==&lang=python&interacts=eJyLjgUAARUAuQ==


Solution

  • Use combinations from itertools

    In [29]: from itertools import combinations
    
    In [30]: def get_list(n, m):
        ...:     return [i for i in combinations(range(1, n+1), m)]
    
    In [31]: get_list(4, 2)
    Out[31]: [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]