-3

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)
trincot
  • 317,000
  • 35
  • 244
  • 286
hamsi
  • 3
  • 2
  • 1
    What do you mean by different digits? Do you mean you don't want the digits 0 thru 9 to be repeated; or do you want to select a sequence of 4-digit numbers that don't repeat? – itprorh66 Jul 23 '22 at 19:42
  • 1
    “I am a bit inexperienced”. Fine, fair play. What *research* have you done to try and work this out on your own? – S3DEV Jul 23 '22 at 19:42

3 Answers3

3
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)
progerg
  • 71
  • 2
  • 2
    You can directly select the digits to avoid 0 in the first position, [without trial end error](https://stackoverflow.com/a/73093812/16343464) ;) – mozway Jul 23 '22 at 19:58
1

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)
The Thonnu
  • 3,578
  • 2
  • 8
  • 30
  • but I get the number randomly from the system, I don't enter it myself. @the-thonnu – hamsi Jul 23 '22 at 19:48
  • 1
    @hamsi, *"but I get the number ... from the system"*. Hold on, you wrote in the question you want to **create** it. Which is it? – trincot Jul 23 '22 at 19:51
1

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

mozway
  • 194,879
  • 13
  • 39
  • 75
  • 1
    Nice answer. I prefer `s = range(1, 10)` and `out = a*10**len(b) + sum(num*10**idx for idx, num in enumerate(b))`, but these are minor quibbles. – jpp Jul 23 '22 at 20:02
  • @jpp I don't remember which one is the most efficient – mozway Jul 23 '22 at 20:04