How to generate a random 4 digit number not starting with 0 and having unique digits?

后端 未结 12 1958
没有蜡笔的小新
没有蜡笔的小新 2020-12-28 12:48

This works almost fine but the number starts with 0 sometimes:

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


        
12条回答
  •  遥遥无期
    2020-12-28 13:17

    I do not know Python well, but something like

    digits=[1,2,3,4,5,6,7,8,9] <- no zero
    random.shuffle(digits)
    first=digits[0] <- first digit, obviously will not be zero
    digits[0]=0 <- used digit can not occur again, zero can
    random.shuffle(digits)
    lastthree=digits[0:3] <- last three digits, no repeats, can contain zero, thanks @Dubu
    

    A more useful iteration, actually creating a number:

    digits=[1,2,3,4,5,6,7,8,9]   # no zero
    random.shuffle(digits)
    val=digits[0]                # value so far, not zero for sure
    digits[0]=0                  # used digit can not occur again, zero becomes a valid pick
    random.shuffle(digits)
    for i in range(0,3):
      val=val*10+digits[i]       # update value with further digits
    print(val)
    

    After stealing pieces from other solutions, plus applying the tip from @DavidHammen:

    val=random.randint(1,9)
    digits=[1,2,3,4,5,6,7,8,9]
    digits[val-1]=0
    for i in random.sample(digits,3):
      val=val*10+i
    print(val)
    

提交回复
热议问题