Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random 4 digit number not starting with 0 and having unique digits?

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.

like image 460
Menon A. Avatar asked Apr 24 '17 16:04

Menon A.


People also ask

What is the smallest 4 digit number with unique digits?

So, smallest 4 digit number is 1023.

How will you get a random number between 0 and 1 in?

The random. uniform() function is perfectly suited to generate a random number between the numbers 0 and 1, as it is utilized to return a random floating-point number between two given numbers specified as the parameters for the function.


2 Answers

We generate the first digit in the 1 - 9 range, then take the next 3 from the remaining digits:

import random

# We create a set of digits: {0, 1, .... 9}
digits = set(range(10))
# We generate a random integer, 1 <= first <= 9
first = random.randint(1, 9)
# We remove it from our set, then take a sample of
# 3 distinct elements from the remaining values
last_3 = random.sample(digits - {first}, 3)
print(str(first) + ''.join(map(str, last_3)))

The generated numbers are equiprobable, and we get a valid number in one step.

like image 163
Thierry Lathuille Avatar answered Oct 20 '22 11:10

Thierry Lathuille


Just loop until you have something you like:

import random

numbers = [0]
while numbers[0] == 0:
    numbers = random.sample(range(10), 4)

print(''.join(map(str, numbers)))
like image 30
aghast Avatar answered Oct 20 '22 13:10

aghast