博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python练习册第一题
阅读量:6872 次
发布时间:2019-06-26

本文共 2342 字,大约阅读时间需要 7 分钟。

题目

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


解题思路

上网搜了一下生成随机字符串的方法,除了猜想中类似C的random()方法,令我惊讶的是uuid模块也可以起到随机的作用,甚至它不会重复。我想要是不限制激活码的长度的话,两种都试一下吧。


random()内置方法

random.sample(population, k)

Return a k length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.

这是从一个博客中看到的例子:

# 多个字符中选取特定数量的字符组成新字符串:>>> import random>>> import string>>> string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).replace(" ","")'fih'

如果能创造一个包含数字和所有字母的序列,再随机生成一定长度的字符串,最后用一定格式输出这个字符串,就可以得到我们想要的随机激活码。

String模块

这个String是一个模块,和String数据类型不是同一个。

string.hexdigits

The string '0123456789abcdefABCDEF'.

干脆就用这个十六进制的String方法生成一个序列

解决代码1

因为也没要求储存,就直接打印出来了。粗粗看了一下没有太大的重复可能性,但概率上还是有可能的;如果需要严谨,可以使用uuid方法。

import random, stringstr = ''seq = []for d in string.hexdigits:    seq.append(d)for i in range(200):    key = str.join(random.choices(seq, k=20))    with open('cokey.txt', 'a') as fp:        fp.write(key+'\n')

uuid

uuid.uuid1(node=None, clock_seq=None)

Generate a UUID from a host ID, sequence number, and the current time. If node is not given, getnode() is used to obtain the hardware address. If clock_seq is given, it is used as the sequence number; otherwise a random 14-bit sequence number is chosen.

解题代码2

由于uuid的唯一性,它生成的序列作为激活码倒是没什么问题。

import uuidfor i in range(200):    seq=str(uuid.uuid1())    string=''.join(seq.split('-'))    with open('cokey.txt', 'a') as fp:        fp.write(string+'\n')

别人的解题方法

对这个优惠券,我光想到随机性了,没想到还要做到与奖品号一一对应。这位大佬的代码就很好的解决了这一点。

import base64# base64编码方便使用# 通过id检验优惠券是否存在,通过goods查找商品coupon = {    'id': '1231',    'goods': '0001',}def gen_coupon(id, goods):    coupon['id'] = id    coupon['goods'] = goods    raw = '/'.join([k + ':' + v for k, v in coupon.items()])    raw_64 = base64.urlsafe_b64encode(raw.encode('utf-8'))    c_code = raw_64.decode()    return c_codedef save_coupon(c_code):    with open('coupon.txt', 'a+') as file:        file.write(c_code+'\n')def show_coupon(c_code):    print('优惠码:', c_code)def parse_coupon(c_code):    print('解析优惠码:', base64.urlsafe_b64decode(c_code.encode('utf-8')))def gen_all():    for i in range(1000, 1200):        c_code = gen_coupon(str(i), str(int(i/2)))        save_coupon(c_code)if __name__ == '__main__':    gen_all()

转载于:https://www.cnblogs.com/ChanWunsam/p/10018279.html

你可能感兴趣的文章
CRUX下实现进程隐藏(2)
查看>>
【转载】mysql 开启慢查询 清空slow_log日志或者slow_log表
查看>>
在电子商务里,一般会提到这样几个词:商品、单品、SPU、SKU
查看>>
【转】mysql-5..6.23-win64.zip安装及配置
查看>>
dotnet Core 学习(三):多项目
查看>>
个人总结阅读作业
查看>>
Superset 制作图表
查看>>
国有航空为啥“放下身段”读春秋?
查看>>
Pinpoint 安装部署
查看>>
TCP/UDP常见端口参考
查看>>
[转] VB6.0 Dictionary 排序,生成Sign
查看>>
selenium IDE安装与使用
查看>>
GNU C - Using GNU GCC __attribute__ mechanism 02 Variable Attribute && Type Attribute
查看>>
java 反射机制的概念
查看>>
回调函数和钩子函数的区别
查看>>
jsp之tomcat安装
查看>>
Vue导航守卫
查看>>
Xsocket学习
查看>>
lnmp下django学习
查看>>
2016年全国高中数学联合竞赛试题及详细解答
查看>>