e-bird14
e-bird14

Reputation: 13

Python 3: How to get a random 4 digit long number with no repeated digits inside that number?

Ok so I need my program to be able to get a random number that has no repeated digits inside that number. So like 0012 has two 0s and therefore I don't need that, however, 1234 would work. The numbers also need to be JUST 4 digits long.

import random

Upvotes: 1

Views: 7164

Answers (5)

Shurong Ge
Shurong Ge

Reputation: 1

You can turn the number into a string:

list_number = list(range(1, 10))
w = random.choice(list_number)
list_number.remove(w)
list_number.append(0)
x = random.choice(list_number)
list_number.remove(x)
y = random.choice(list_number)
list_number.remove(y)
z = random.choice(list_number)
x = int(str(w)+str(x)+str(y)+str(z))
print("x")

Upvotes: 0

Aaron
Aaron

Reputation: 2083

You could use sample:

import random
numbers = random.sample(range(10), 4)
print(''.join(map(str, numbers)))

@Copperfield variation in the comments is elegant as it forgoes the need to cast (since you are sampling from a string).

import random
number = ''.join(random.sample("0123456789", 4))
print(number)

Upvotes: 5

John La Rooy
John La Rooy

Reputation: 304393

There are only 5040 choices. If you need to generate these numbers many times, you may like to precompute a list of choices.

>>> import random, itertools
>>> choices = [''.join(x) for x in itertools.permutations('0123456789', 4)]
>>> random.choice(choices)
'0179'
>>> random.choice(choices)
'7094'

Upvotes: 2

Vinay Padmanabhi
Vinay Padmanabhi

Reputation: 21

You can use random.sample in order to ensure no digits are repeated,

>>> import random
>>> l = random.sample(range(10), 4)
>>> int((''.join([str(x) for x in l])))
>>> 4265

Upvotes: 0

lakshayg
lakshayg

Reputation: 2173

from random import shuffle
l = [i for i in range(10)]
shuffle(l)
n = l[0] + 10 * (l[1] + 10 * (l[2] + 10 * l[3])) 

Here's a oneliner

import random
from functools import reduce # you need this for python3
n = reduce(lambda a,b: 10*a+b, random.sample(range(10), 4))

Note: Both of the methods above might occasionally give a 3 digit number due to 0 appearing at the front

Upvotes: 4

Related Questions