传送门:https://github.com/Yixiaohan/show-me-the-code,今天是第0001题。
1.题目描述
做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?
2.题目解析
这个题目设计到的知识点包括:ASCII码和字母的转化、从列表中随机选取元素、字符串有关操作,总体来说比较简单。
3.完整代码
#coding=utf-8
import random
#初始化列表
ll=[]
#将10个数字转化成字符串形式并添加到列表里
for i in range(10):
ll.append(str(i))
#将A-Z添加到列表里
for i in range(65,91):
ll.append(chr(i))
#将a-z添加到列表里
for i in range(97,123):
ll.append(chr(i))
#生成激活码的函数
def get_code(length):
code=''
for i in range(length):
#从列表里随机选择一个元素
ss=random.choice(ll)
code=code+ss
print(code)
if __name__=='__main__':
#自己决定激活码的长度
l=int(input('please input the length of the code: '))
#自己决定要生成的激活码的个数
x=int(input('please input the number of the code: '))
for i in range(x):
get_code(l)
4.运行结果
5.举一反三
这里生成的是可以有重复元素的激活码,如果我们要一个激活码的所有元素都不重复呢?这个时候就用到了random模块自带的sample函数。sample(population, k)从population中取样,一次取k个,返回一个k长的列表。
import random
ll=[]
for i in range(10):
ll.append(str(i))
for i in range(65,91):
ll.append(chr(i))
for i in range(97,123):
ll.append(chr(i))
def get_code(length):
a=random.sample(ll,length)
code=''.join(a)
print(code)
if __name__=='__main__':
l=int(input('please input the length of the code: '))
x=int(input('please input the number of the code: '))
for i in range(x):
get_code(l)