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 thenn
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)
CodePudding user response:
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]
CodePudding user response:
The itertools
library has functions for working with permutations. itertools.permutations(digits, n)
will return all n-length permutations of elements of digits
.
Additionally, no permutation should start with a 0. We can apply this condition to every element by iterating over the permutations and keeping only those that match the condition.
We also want to convert each permutation into an integer. We can do this in a similar way to your method by converting each digit to a string, concatenating them all with "".join
, and then converting back to an integer.
Final solution:
import itertools
digits = [0, 1, 2]
n = 3
result = set()
for permutation in itertools.permutations(digits, n):
if permutation[0] != 0:
number = int("".join(map(str, permutation)))
result.add(number)
print(result)