check if all the digits of the given number are different
Question:
I want to create a 4-digit number between 1000 and 10000 with different digits, but I am a bit inexperienced as I am new to this stuff. Can you help me?
import random
number = random.choice(range(1000,10000))
print(number)
Answers:
You need to iterate through the digits of the number and check if that digit is in the number more than once.
def different_digits(num):
for d in str(num):
if str(num).count(d) > 1:
return False
return True
print(different_digits(1234)) # True
print(different_digits(1224)) # False
This can even be simplified with all
:
def different_digits(num):
return all(str(num).count(d) == 1 for d in str(num))
print(different_digits(1234)) # True
print(different_digits(1224)) # False
Now to get the 4-digit number just use a while
loop:
x = random.randint(1000, 9999)
while not different_digits(x):
x = random.randint(1000, 9999)
import random
a = 0
while a == 0:
a, b, c, d = random.sample(range(10), 4)
k = 1000*a + 100*b + 10*c + d
print(k)
Using a direct selection of the digits, without any trial and error:
import random
s = '123456789'
# select first digit
a = random.sample(s, 1)
# select last 3 digits
b = random.sample(list(set(s).difference(a))+['0'], 3)
out = int(''.join(a+b))
Example output: 6784
I want to create a 4-digit number between 1000 and 10000 with different digits, but I am a bit inexperienced as I am new to this stuff. Can you help me?
import random
number = random.choice(range(1000,10000))
print(number)
You need to iterate through the digits of the number and check if that digit is in the number more than once.
def different_digits(num):
for d in str(num):
if str(num).count(d) > 1:
return False
return True
print(different_digits(1234)) # True
print(different_digits(1224)) # False
This can even be simplified with all
:
def different_digits(num):
return all(str(num).count(d) == 1 for d in str(num))
print(different_digits(1234)) # True
print(different_digits(1224)) # False
Now to get the 4-digit number just use a while
loop:
x = random.randint(1000, 9999)
while not different_digits(x):
x = random.randint(1000, 9999)
import random
a = 0
while a == 0:
a, b, c, d = random.sample(range(10), 4)
k = 1000*a + 100*b + 10*c + d
print(k)
Using a direct selection of the digits, without any trial and error:
import random
s = '123456789'
# select first digit
a = random.sample(s, 1)
# select last 3 digits
b = random.sample(list(set(s).difference(a))+['0'], 3)
out = int(''.join(a+b))
Example output: 6784