Many a times, I've had the need to use a permutations with replacement function.
So, I've written a function to do just that:
from sys import setrecursionlimit
setrecursionlimit(10 ** 9)
def permutations_with_replacement(n: int, m: int, cur=None):
if cur is None:
cur = []
if n == 0:
yield cur
return
for i in range(1, m + 1):
yield from permutations_with_replacement(n - 1, m, cur + [i])
if __name__ == '__main__':
n = int(input("Please enter 'N': "))
m = int(input("Please enter 'M': "))
for i in permutations_with_replacement(n, m):
print(*i)
There's a better way to do this if we used itertools.product, but there's no fun in that!
from itertools import product
def permutations_with_replacement(n, m):
for i in product(list(range(1, m + 1)), repeat=n):
yield i
if __name__ == '__main__':
n = int(input("Please enter 'N': "))
m = int(input("Please enter 'M': "))
for i in permutations_with_replacement(n, m):
print(*i)
I don't like the way I've implemented cur in my code. Is there any better way to do that?