Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading