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

后端 未结 12 1955
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  萌比男神i
    2020-12-28 13:04

    rejection sampling method. Create a 4 digit random combination from 10 digits and resample if it doesn't match the criteria.

    r4=0    
    while r4 < 1000:
        r4=int(''.join(map(str,random.sample(range(10),4))))
    

    noticed that this is essentially the same as @Austin Haskings's answer

提交回复
热议问题