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

后端 未结 12 1975
没有蜡笔的小新
没有蜡笔的小新 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 12:59

    This is very similar to the other answers but instead of sample or shuffle you could draw a random integer in the range 1000-9999 until you get one that contains only unique digits:

    import random
    
    val = 0  # initial value - so the while loop is entered.
    while len(set(str(val))) != 4:  # check if it's duplicate free
        val = random.randint(1000, 9999)
    
    print(val)
    

    As @Claudio pointed out in the comments the range actually only needs to be 1023 - 9876 because the values outside that range contain duplicate digits.

    Generally random.randint will be much faster than random.shuffle or random.choice so even if it's more likely one needs to draw multiple times (as pointed out by @karakfa) it's up to 3 times faster than any shuffle, choice approach that also needs to join the single digits.

提交回复
热议问题