This works almost fine but the number starts with 0 sometimes:
import random
numbers = random.sample(range(10), 4)
print(''.join(map(str, numbers)))
I've found a lot of examples but none of them guarantee that the sequence won't start with 0
.
This works almost fine but the number starts with 0 sometimes:
import random
numbers = random.sample(range(10), 4)
print(''.join(map(str, numbers)))
I've found a lot of examples but none of them guarantee that the sequence won't start with 0
.
This is very similar to the other answers but instead of
sample
orshuffle
you could draw a random integer in the range 1000-9999 until you get one that contains only unique digits:As @Claudio pointed out in the comments the range actually only needs to be 1023 - 9876 because the values outside that range contain duplicate digits.
Generally
random.randint
will be much faster thanrandom.shuffle
orrandom.choice
so even if it's more likely one needs to draw multiple times (as pointed out by @karakfa) it's up to 3 times faster than anyshuffle
,choice
approach that also needs tojoin
the single digits.Here's how I'd do it
More generally, given a generator, you can use the built-ins
filter
andnext
to take the first element that satisfies some test function.This will allow zeros after the first digit -
I don't know Python so I will post a pseudo-code-ish solution for this specific problem:
Create a lookup variable containing a 0-based list of digits:
Generate four 0-based random numbers as follows:
Use the lookup variable to convert random numbers to digits one-by-one. After each lookup, mutate the lookup variable by removing the digit that has been used:
Print the result:
It is possible to generalize this idea a little. For example you can create a function that accepts a list (of digits) and a number (desired length of result); the function will return the number and mutate the list by removing used-up digits. Below is a JavaScript implementation of this solution:
We generate the first digit in the 1 - 9 range, then take the next 3 from the remaining digits:
The generated numbers are equiprobable, and we get a valid number in one step.
I do not know Python well, but something like
A more useful iteration, actually creating a number:
After stealing pieces from other solutions, plus applying the tip from @DavidHammen: