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

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

    You could use full range for 3 numbers, then choose the leading number among the remaining numbers:

    import random
    numbers = random.sample(range(0,10), 3)
    first_number = random.choice(list(set(range(1,10))-set(numbers)))
    print(''.join(map(str, [first_number]+numbers)))
    

    Another way if the choice needs to be repeated (and if you remain reasonable on the number of digits), is to pre-compute the list of the possible outputs using itertools.permutations, filtering out the ones with a leading zero, and building a list of integers from it:

    import itertools,random
    
    l = [int(''.join(map(str,x))) for x in itertools.permutations(range(10),4) if x[0]]
    

    That's some computation time, but after than you can call:

    random.choice(l)
    

    as many times you want. It's very fast and provides an evenly distributed random.

提交回复
热议问题