python练习册第一题

题目

做为 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, string

str = ''
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+'
')

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 uuid

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

别人的解题方法

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

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_code


def save_coupon(c_code):
    with open('coupon.txt', 'a+') as file:
        file.write(c_code+'
')


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