如何生成不以0开头且具有唯一数字的随机4位数字? [英] How to generate a random 4 digit number not starting with 0 and having unique digits?

查看:555
本文介绍了如何生成不以0开头且具有唯一数字的随机4位数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这几乎可以正常工作,但是数字有时以0开头:

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

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

我找到了很多示例,但是没有一个可以保证序列不会以0开头.

I've found a lot of examples but none of them guarantee that the sequence won't start with 0.

推荐答案

我们生成1-9范围内的第一个数字,然后从其余数字中提取下一个3:

We generate the first digit in the 1 - 9 range, then take the next 3 from the remaining digits:

import random

# We create a set of digits: {0, 1, .... 9}
digits = set(range(10))
# We generate a random integer, 1 <= first <= 9
first = random.randint(1, 9)
# We remove it from our set, then take a sample of
# 3 distinct elements from the remaining values
last_3 = random.sample(digits - {first}, 3)
print(str(first) + ''.join(map(str, last_3)))

生成的数字是等概率的,我们一步就可以得到一个有效的数字.

The generated numbers are equiprobable, and we get a valid number in one step.

这篇关于如何生成不以0开头且具有唯一数字的随机4位数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆