Search code examples
pythonpython-3.xloopslogicpermutation

How to form all possible combination of given digits to form a n-digit number without repetition of digits?(python)


Question

Let say we have a list of given digits and n (to form n-digit number)

digits = [0, 1, 2]
n = 3

List digit can not contain duplicate values.

How we can form all possible n digit numbers without repetition of digits. n can be any positive integer and list digits can have any length and digits in it.

If length of list digits is less then n then no valid numbers can be formed.


Conditions on number

Valid Numbers

[120, 102, 201, 210]

Invalis Numbers

[012, 112, 221, 212, 121]

012 is invalid because it is equivalent to 12 which is not a 3-digit number


Here is what I tried

def formNum(L):
    num = []
    for i in range(3):
        for j in range(3):
            for k in range(3):
                  
                if (i!=j and i != 0 and j!=k and i!=k):
                    num.append(int(f"{L[i]}{L[j]}{L[k]}"))
                      
    return num

print(formNum([0, 1, 2]))

Output

[102, 120, 201, 210]

But my solution will only work for 3 digits number and is very difficult to expand and for large value of n it is very slow.


My question is not similar to this one as this question ask for all possible arrangements of given digits but mine ask for all possible arrangements of digit to form a number of n-digits (n is given)


Solution

  • This is a possible solution:

    from itertools import permutations
    
    num = [int(''.join(map(str, p))) for p in permutations(digits, n) if p[0] != 0]
    

    The output for your example:

    [102, 120, 201, 210]