This works almost fine but the number starts with 0 sometimes:
import random
numbers = random.sample(range(10), 4)
print(\'\'.join(map(str, numbers)))
You could use full range for 3 numbers, then choose the leading number among the remaining numbers:
import random
numbers = random.sample(range(0,10), 3)
first_number = random.choice(list(set(range(1,10))-set(numbers)))
print(''.join(map(str, [first_number]+numbers)))
Another way if the choice needs to be repeated (and if you remain reasonable on the number of digits), is to pre-compute the list of the possible outputs using itertools.permutations
, filtering out the ones with a leading zero, and building a list of integers from it:
import itertools,random
l = [int(''.join(map(str,x))) for x in itertools.permutations(range(10),4) if x[0]]
That's some computation time, but after than you can call:
random.choice(l)
as many times you want. It's very fast and provides an evenly distributed random.