第二题的描述为:

做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?

这个题相对上一题就要简单多了(可能是我想简单了),我们控制前五位码不同,再随机生成后面15位码即可。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#0001 - 生成200个激活码
import random
def get_activate_code(num):
string = "abcdefghijklmnopqrstuvwxyz"
string += string.upper()
string += "0123456789"#生成字符范围
for cnt in range(num):
code = "%05d" % cnt#生成5位数字
repeat = 15
while(repeat > 0):
if(repeat % 5 == 0):#每五位后面加‘-’
code += '-'
code += random.choice(string)
repeat -= 1
print(code)
get_activate_code(200)

第三题的描述为:

将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中。

首先我们要解决包的问题,看到网上很多人用的是MySQLdb包,但我没找到python3版本的,因此去mysql官网mysql Connector主页选择Connector/python下载安装就好了

使用过程当然要借助官方文档了,详见python插入mysql数据库示例代码

下面附上我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#0002 - 生成200个激活码
import random
import mysql.connector
def get_activate_code(num):
string = "abcdefghijklmnopqrstuvwxyz"
string += string.upper()
string += "0123456789"#生成字符范围
ans = []
for cnt in range(num):
code = "%05d" % cnt#生成5位数字
repeat = 15
while(repeat > 0):
if(repeat % 5 == 0):#每五位后面加‘-’
code += '-'
code += random.choice(string)
repeat -= 1
ans.append(code)
return ans
def insert_code(query, code):
conn = mysql.connector.connect(user='root', password='root', host='localhost', database='python')
cursor = conn.cursor(buffered=True)
cnt = 0
cursor.execute("delete from python") #删除表python中的所有内容
for line in code:
cursor.execute(query, (cnt, line))#插入所有激活码
cnt += 1
cursor.execute("select * from python")#查看插入结果
res = cursor.fetchall()
for line in res:
print(line)
conn.commit()
cursor.close()
conn.close()
gen_code = get_activate_code(200)
query = ("insert into python"
"(uid, gen_code)"
"values (%s, %s)")
insert_code(query, gen_code)

运行python 0001.py > out.txt,比较打印出的内容与数据库中内容可以发现二者相同,因此程序完成

截图

截图

0003题就跳过去了,因为非关系型数据库没有接触过,这里并不是因为不愿意学习新知识,而是因为如果接触一个新知识,想要系统地学习,而不是走马观花似学习。而且个人觉得mysql能实现,这个难度也不大。