0

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==

Julien
  • 125
  • 9
  • 1
    "Is there a nice way to do that with very few lines of Python code?" Have you tried anything at all? – juanpa.arrivillaga May 30 '20 at 19:57
  • @juanpa.arrivillaga Yes I have... It works but it is painfully long, which is why I am asking. – Julien May 30 '20 at 19:58
  • what is the point of m here ? – fireball.1 May 30 '20 at 20:02
  • @juanpa.arrivillaga Here is my code https://sagecell.sagemath.org/?z=eJxVkcFuhCAQhu88xSS9QNSmNj2Z2ido0svezB4wYDtBR4Juto_fAeyqnBj4v59_BmMHIPu7Xm5-tNKVQKoRwCseQguua66p9lyMlqRTqUQuPVRQp-r-g6NlLV6hbfmuAOI7n52yvGo3bTSOwqI9wQjv2XCHsrKo2XSnNiibPjyCXW-BkkoIwz31esHla_jUU2-0pBK8agCeYJgD-GqN3S6gyYDBydKCM8O5sYFjfADtMTbvLs_BcZjuJe-jGQISBE3fVtbplQfnnrX3lozEPLIUKdI7HE5wjzRPqMccN7Z6cEv0v2P8FbU_tM3n8IfHoSRSCB-QVnmey1sJr0r9Ab9liHA=&lang=python&interacts=eJyLjgUAARUAuQ== – Julien May 30 '20 at 20:02
  • @fireball.1 m is the length of the lists in the list. – Julien May 30 '20 at 20:03

3 Answers3

2

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)]
Osman Mamun
  • 2,864
  • 1
  • 16
  • 22
1

You can use itertools:

from itertools import combinations

m = 2
n = 4

list(combinations(list(range(1, n+1)), m))

EDITED: If you want a function, just return it:

from itertools import combinations

m = 2
n = 4

def listOfLists(n, m):
    return list(combinations(list(range(1, n+1)), m))

listOfLists(n, m)
João Victor
  • 407
  • 2
  • 10
0

I think this might work :

n=4
m=2
result=[]
for i in range(1,n):
    for j in range(i+1,n+1):
        result.append([i,j])
fireball.1
  • 1,413
  • 2
  • 17
  • 42
  • This I can do, but thanks. In the end, I want a function that returns the list of lists for any given (n, m). – Julien May 30 '20 at 20:06