|
| 1 | +# coding: utf-8 |
| 2 | + |
| 3 | +''' |
| 4 | +做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券), |
| 5 | +使用 Python 如何生成 200 个激活码(或者优惠券)? |
| 6 | +
|
| 7 | +笔记参见: |
| 8 | +http://liam0205.me/2015/05/07/generator-of-invitation-code-in-python/ |
| 9 | +''' |
| 10 | + |
| 11 | +import random, string |
| 12 | + |
| 13 | +class LengthError(ValueError): |
| 14 | + def __init__(self, arg): |
| 15 | + self.args = arg |
| 16 | + |
| 17 | +def pad_zero_to_left(inputNumString, totalLength): |
| 18 | + ''' |
| 19 | + takes inputNumString as input, |
| 20 | + pads zero to its left, and make it has the length totalLength |
| 21 | + 1. calculates the length of inputNumString |
| 22 | + 2. compares the length and totalLength |
| 23 | + 2.1 if length > totalLength, raise an error |
| 24 | + 2.2 if length == totalLength, return directly |
| 25 | + 2.3 if length < totalLength, pads zeros to its left |
| 26 | + ''' |
| 27 | + lengthOfInput = len(inputNumString) |
| 28 | + if lengthOfInput > totalLength: |
| 29 | + raise LengthError("The length of input is greater than the total\ length.") |
| 30 | + else: |
| 31 | + return '0' * (totalLength - lengthOfInput) + inputNumString |
| 32 | + |
| 33 | +poolOfChars = string.ascii_letters + string.digits |
| 34 | +random_codes = lambda x, y: ''.join([random.choice(x) for i in range(y)]) |
| 35 | + |
| 36 | +def invitation_code_generator(quantity, lengthOfRandom, LengthOfKey): |
| 37 | + ''' |
| 38 | + generate `quantity` invitation codes |
| 39 | + ''' |
| 40 | + placeHoldChar = "L" |
| 41 | + for index in range(quantity): |
| 42 | + tempString = "" |
| 43 | + try: |
| 44 | + yield random_codes(poolOfChars, lengthOfRandom) + placeHoldChar + \ |
| 45 | + pad_zero_to_left(str(index), LengthOfKey) |
| 46 | + except LengthError: |
| 47 | + print "Index exceeds the length of master key." |
| 48 | + |
| 49 | +for invitationCode in invitation_code_generator(200, 16, 4): |
| 50 | + print invitationCode |
0 commit comments