如何使randint
函数不生成特定的数字列表?我必须创建一个随机的银行卡代码生成器,它不能生成像'1111' '2222'这样的4个重复数字。
import random
bank_codes = int(input("Hur många koder ska genereras: "))
code = 0
unwanted_codes = [0000, 1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999]
while code < bank_codes:
code += 1
a = str(random.randint(1, 10000))
if len(a) == 3:
print('0' + a)
elif len(a) == 2:
print('00' + a)
elif len(a) == 1:
print('000' + a)
else:
print(a)
如果生成1到9998范围内的随机数,则不需要担心0000
或9999
。使用此方法,可以实现非常有效的命中或未命中方法:
from random import randint
unwanted_codes = set([1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888])
def rand_code():
while True:
code = randint(1,9998)
if code not in unwanted_codes:
return str(code).zfill(4)
zfill
方法用0填充左边的字符串。
绝大多数情况下,通过一次循环就足够了。这将是相当罕见的,超过两次将需要。
作为快速检查,len(set(rand_code() for _ in range(100000)))
的计算结果为9990(概率很高——尽管有时也会看到9989),这是有效代码的数量。
您可以使用random.randint
生成序列的长度,使用random.sample
生成序列本身。random.sample
接受一个集合(有时称为"population"),它将从中随机挑选k
个不同的项,给定长度为k
。如果你给它一个集合,在这种情况下,每个数字有三个唯一的实例,那么你保证在最终序列中永远不会有相同的数字出现超过三次。
from random import sample, randint
from string import digits
max_len = 4
length = randint(1, max_len)
population = digits * (max_len - 1)
print("".join(sample(population, k=length)).zfill(max_len))
这对你很有用。
import random
bank_codes = int(input("Hur många koder ska genereras: "))
code = 0
unwanted_codes = [0000, 1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999]
while code < bank_codes:
code += 1
a = (random.randint(1, 10000))
if a not in unwanted_codes:
print(a)