I want to generate a random 4 digit number in which none of the digits are repeated.
import random
sets = random.sample(range(0,9), 4)
This generates a random set of 4 digits but I want this as an integer. how do I do that?
I want to generate a random 4 digit number in which none of the digits are repeated.
import random
sets = random.sample(range(0,9), 4)
This generates a random set of 4 digits but I want this as an integer. how do I do that?
(Assuming OP meant all the digits)
Instead of using numbers and have to manipulate to str
and back to int
, just start with ascii digits:
>>> import string
>>> ''.join(random.sample(string.digits, 4))
'4561'
You can convert to int()
if necessary.
It's unclear what the OP intends to do if the first digit is 0
.
For a purely numerical approach you can use functools.reduce
:
>>> import functools as ft
>>> ft.reduce(lambda s, d: 10*s + d, random.sample(range(10), 4))
2945
You can do this by converting each digit to a string, joining them, and casting them as an integer.
int("".join(map(str,random.sample(range(0,9),4))))
if you need to generate 4 digit number, just for knowledge purpose use.
As suggested by AChampion this solution can contain duplicates
from random import randint randint(1000, 9999)
Use bernie Solution to generate a random 4 digit number in which none of the digits are repeated.
int("".join(map(str,random.sample(range(0,9),4))))
In case if you want potentially infinite sequence of numbers with 4 unique digits (or any other condition – write your own)
import random
def numbers_gen(left_end, right_end):
while True:
yield random.randint(left_end, right_end)
def are_digits_unique(number):
number_string = str(number)
return list(set(number_string)) == list(number_string)
four_digits_numbers_gen = number_gen(left_end=1000,
right_end=9999)
four_digits_numbers_with_unique_digits_gen = filter(are_digits_unique,
four_digits_numbers_gen)
Works only in Python 3 because filter
returns iterator-object (in Python 2.7 it returns list
, more at docs)
You can multiply with powers of 10:
sum(10**a*b for a, b in enumerate(reversed(sets)))
This works as long as the first element of sets
is not zero.
You could try:
import random
my_set = set()
while len(my_set) < 4:
x = random.choice(range(0,9))
my_set.add(x)
my_num = int("".join(map(str, my_set)))