码迷,mamicode.com
首页 > 编程语言 > 详细

【python小练】0001

时间:2016-03-22 21:54:47      阅读:292      评论:0      收藏:0      [点我收藏+]

标签:

第 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

【python小练】0001

标签:

原文地址:http://www.cnblogs.com/liez/p/5308425.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!