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

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

    Combine generators with next

    A Pythonic way to write would be to use 2 nested generators and next:

    from random import randint
    from itertools import count
    
    print(next(i for i in (randint(1023, 9876) for _ in count()) if len(set(str(i))) == 4))
    # 8756
    

    It's basically a one-liner variant of @MSeifert's answer

    Preprocess all the acceptable numbers

    If you need many random numbers, you could invest some time and memory for preprocessing all the acceptable numbers:

    import random    
    possible_numbers = [i for i in range(1023, 9877) if len(set(str(i))) == 4]
    

    1023 and 9877 are used as boundaries because no int lower than 1023 or greater than 9876 can have 4 unique, distince numbers.

    Then, you'd just need random.choice for a very fast generation:

    print(random.choice(possible_numbers))
    # 7234
    

提交回复
热议问题