Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate a for loop x times [duplicate]

Tags:

python

I have this piece of code that will generate all combinations of a 3-digit number

for n1 in range(10):
    for n2 in range(10):
        for n3 in range(10):
            print(n1,n2,n3)

input()

so this will generate 001,002,003... all the way to 999 and this works fine, my question is how do I extend this code to run with a custom amount of digits that I can input? For example, if I say 5, it should run 5 for loops and print all the results in order to get 00001,00002... 99999. So how do I dynamically create more for loops without writing them myself?

like image 573
BlockCoder Avatar asked Jan 20 '26 10:01

BlockCoder


1 Answers

You can use recursion

def func(n, k, *args):
  if n:
    for i in range(k):
      func(n - 1, k, *args, i)
  else:
    print(*args)

func(3, 10)
like image 75
JoshuaCS Avatar answered Jan 23 '26 01:01

JoshuaCS