【python小练】0001

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

 

# coding = utf-8
__author__= 'liez'

import random

def make_number(num, length):
    str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    a = []
    i = 0
    while i < num:
        numstr = ''
        for j in range(length):
            numstr += random.choice(str)
        if numstr not in a: #如果没重复
            a.append(numstr)
            i += 1
            print(numstr)

make_number(20,10)

note:

random.choice(seq): Return a random element from the non-empty sequence seq. If seq is empty,

 

这里先生成了20个:

COsSx9umWf
QKMSbDVj0G
ARdycodYAf
f8h0drSHJl
e0T6lF6aO1
ZB06xAlSnf
SmcAqxYHqm
209me2lsCl
NnvmMeMgqd
FqxLZVlzpC
dj7luHI53s
RytNv7yhTH
bg7PDFmGE1
I7r7S1mpWK
agN2PYF3TI
523YX6TdS8
GmffcmyoYX
MmZZ2pHieO
gaHTmOVPDT
6rgb3v2TJP

 

ps:

1.我是用random module的,也看到其他人很多不同的做法。比如用的uuid module,uuid-Universally unique identifier(通用唯一识别码)。

暂时不清楚这些序列生成函数间有什么区别(是不是哪个更安全之类的?)。uuid module docs

2.我用list来放生成的序列号,也看见用set的: A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. 功能更多嘛。set types docs

具体改动:

def make_number(num, length):
    str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    a = set()  //...
    i = 0
    while i < num:
        numstr = ''
        for j in range(length):
            numstr += random.choice(str)
        if numstr not in a: 
            a |= {numstr} //...
            i += 1
            print(numstr)

 

 

练习簿:https://github.com/Yixiaohan/show-me-the-code

posted @ 2016-03-22 20:55  Liez  阅读(407)  评论(0编辑  收藏  举报