设计内容:
假如你要为一个应用搞限时促销,生成激活码(或者优惠券)请用 Python 如何生成 100 个激活码(或者优惠券)。
激活码的格式为asqE-9xRK-lqWU-QkMT
设计要求:
1、使用随机生成时,生成数字概率为1/5,大写字母和小写字母概率各为2/5;
2、这100个激活码,他们各不相同。
import random
lst_upper=[] #大写列表
lst_lower=[] #小写列表
lst_digital=[] #数字列表
lst_probability=[1, 2, 3, 4, 5] #概率列表
lst_license=[] #激活码列表
"""
初始化大小写和数字列表
"""
for i in range(97, 123):
lst_lower.append(chr(i))
for i in range(65, 91):
lst_upper.append(chr(i))
for i in range(48, 58):
lst_digital.append(chr(i))
def get_100_license(): #生成激活码函数
license_amount = 0 #激活码数目
while license_amount < 100:
license_code = "" #一个字符串激活码
for i in range(1,5):
for i in range(1,5):
probability = random.choice(lst_probability)
if probability == 1:
license_code += random.choice(lst_digital)
elif probability >=2 and probability<=3:
license_code += random.choice(lst_lower)
else:
license_code += random.choice(lst_upper)
license_code += '-' #加上斜杠
if license_code[0:-2] not in lst_license:
lst_license.append(license_code[0:-2])
license_amount += 1
return lst_license
if __name__ == '__main__':
license_show = get_100_license()
print(license_show)
print(len(license_show))