Is there a way to enumerate a sequence that meets the following conditions?
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
.
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]]
© 2024 OneMinuteCode. All rights reserved.