in python, I want to get all n-digit numbers with digits 1 to n (n <10, each exactly once). How can I ??
Can similar things be done? thanks
CodePudding user response:
You can use itertools.permutations()
to get the digits of each number, and then use map()
with str()
and int()
to turn the generated digits into the desired numbers:
import itertools
n = 3
for item in itertools.permutations(range(1, n 1), n):
result = int(''.join(map(str, item)))
print(result)
This outputs (only first three / last three lines shown):
123
132
213
231
312
321
CodePudding user response:
Just use itertools.permutations
import itertools
n = 3
for item in itertools.permutations(range(1, n 1), n):
print(*item, sep='')
# In case you want to do something with the integer value:
result = int(''.join(map(str, item)))
Output:
123
132
213
231
312
321