list a monotonically increasing sequence over a range

Asked 1 years ago, Updated 1 years ago, 484 views

Is there a way to enumerate a sequence that meets the following conditions?

  • A positive integer column of length N
  • 1<=A_1<=A_2<=...=A_N<=M
  • 1<=N,M<=10

By using the recursive function, I was able to achieve my goal first, but I imagine that the performance is poor because of the array copy.

N=2
M = 3

a = [0]*N
def dfs(pre_a, depth):
    if depth == N:
        pool.append(a.copy())
        return
    for i in range (pre_a, M+1):
        a[depth] = i
        dfs(i, depth+1)

pool = [ ]
dfs(10)
pool#[[1,1],[1,2],[1,3],[2,2],[2,3]]

Please let me know if there is a smart way to write using itertools.

python python3 algorithm

2022-12-28 01:25

1 Answers

Use combinations_with_replacement.

from ittertools import combinations_with_replacement

N = 2
M = 3

print(list(combinations_with_replacement(range(1,M+1),N)))
#[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]

If you want each element to be listed instead of a tuple, enclose it with map(list,...).

print(list(map(list, combinations_with_replacement(range(1,M+1),N)))))
#[[1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3, 3]]


2022-12-28 07:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.