简体   繁体   中英

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
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

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)

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'

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

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM