show_you_my_codes 001

program 001

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

code

# -*- coding: utf-8 -*-
# __author__:Ww2zero

import random
import string

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

    def __init__(self):
        #  字典域 由数字和字母(包括大小写)组成
        self.FIELD = string.digits + string.letters
        self.GENERATE = None

    def createCodes(self, codenumber=10, codesize=10):
        """
            生成codenumber组随机码,每组生成的码的长度为codesize
        """
        def getCode(codesize):
            """
                得到codesize位激活码
            """
            return "".join(random.sample(self.FIELD, codesize))
        self.GENERATE = [getCode(codesize) for i in range(codenumber)]
        return True

    def writeInFile(self, file):
        """
            写入文件 并按顺序排列
        """
        count = 1
        for i in self.GENERATE:
            with open(file, "a") as boom:
                boom.write(str(count).rjust(3) + "  " + i + "\n")
            count += 1


if __name__ == '__main__':
    ac = ActivateCodes()
    ac.createCodes(200, 30)
    ac.writeInFile("accodes.txt")

module

UUID

UUID是128位的全局唯一标识符,通常由32字节的字符串表示。

它可以保证时间和空间的唯一性,也称为GUID,全称为:
UUID —— Universally Unique IDentifier Python 中叫 UUID
GUID —— Globally Unique IDentifier C# 中叫 GUID

它通过MAC地址、时间戳、命名空间、随机数、伪随机数来保证生成ID的唯一性。

UUID常用函数

  • uuid1() 基于时间戳

    • 由MAC地址、当前时间戳、随机数生成。
    • 可以保证全球范围内的唯一性,但MAC的使用同时带来安全性问题,局域网中可以使用IP来代替MAC。
    
    In [8]: uuid.uuid1() # 生成基于计算机主机ID和当前时间的UUID
    Out[8]: UUID('371f06de-fbed-11e6-8d6f-3497f6e040cb')
    
  • uuid3() 基于名字的MD5散列值

    • 通过计算名字和命名空间的MD5散列值得到,保证了同一命名空间中不同名字的唯一性,和不同命名空间的唯一性。
    • 但同一命名空间的同一名字生成相同的uuid。
    
    In [10]: uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')  # 基于命名空间和一个字符的MD5加密的UUID
    Out[10]: UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
    
  • uuid4() 基于随机数

    • 由伪随机数得到,有一定的重复概率,该概率可以计算出来。
    
    In [11]: uuid.uuid4()   # 随机生成一个UUID
    Out[11]: UUID('14eddb20-32d2-411f-a294-30666155c781')
    
  • uuid5() 基于名字的SHA-1散列值

    • 算法与uuid3相同,不同的是使用 Secure Hash Algorithm 1 算法。
    
    In [12]:  uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')  #基于命名空间和一个字符的SHA-1加密的UUID
    Out[12]: UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
    

uuid 命名空间标识符

  • uuid.NAMESPACE_DNS
    • 当指定该命名空间时,参数 name 是一个完全限定的(fully-qualified)域名
  • uuid.NAMESPACE_URL
    • 当指定该命名空间时,参数 name 是一个URL
  • uuid.NAMESPACE_OID
    • 当指定该命名空间时,参数 name 是一个ISO OID
  • uuid.NAMESPACE_X500
    • 当指定该命名空间时,参数 name 是一个DER格式或文本格式的X.500 DN

参考资料

http://www.cnblogs.com/Security-Darren/p/4252868.html
http://blog.163.com/kefan_1987/blog/static/897801312011113011537390/
http://www.cnblogs.com/dkblog/archive/2011/10/10/2205200.html

String

string constants(常量)


>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.hexdigits
'0123456789abcdefABCDEF'
>>> string.letters
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
>>> string.lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.octdigits
'01234567'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>> string.whitespace
'\t\n\x0b\x0c\r

string format(字符串格式化)

# 指定长度的左对齐
>>> '{:<30}'.format('left aligned')
'left aligned                  '
# 指定长度的右对齐
>>> '{:>30}'.format('right aligned')
'                 right aligned'
# 指定长度的中间对齐
>>> '{:^30}'.format('centered')
'           centered           '
# 指定长度,指定符号填充 中间对齐
>>> '{:*^30}'.format('centered')  # use '*' as a fill char
'***********centered***********'
# 主动显示符号
>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
'+3.140000; -3.140000'
# 不主动显示符号
>>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers
' 3.140000; -3.140000'
# 不主动显示符号
>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
'3.140000; -3.140000'
# 按照不同的进制显示数字
>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'
 # 逗号分隔千位
>>> '{:,}'.format(1234567890)
'1,234,567,890'
 
 # 保留指定小数位
>>> points = 19.5
>>> total = 22
>>> 'Correct answers: {:.2%}.'.format(points/total)
'Correct answers: 88.64%'
 # 时间格式化输出
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'

#string 模板输出
>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'

string function (常用函数)

# 获取string 长度
In [2]: len('hello world')
Out[2]: 11
# 转换成大写
In [3]: str.upper('hello world')
Out[3]: 'HELLO WORLD'
# 转化成小写
In [4]: str.lower('HELLO WPRLD')
Out[4]: 'hello wprld'
# 大小写互换
In [5]: str.swapcase('HELLO WORLD')
Out[5]: 'hello world'
In [6]: str.swapcase('hello wprld')
Out[6]: 'HELLO WPRLD'
# 首字母大写,其余小写
In [7]: str.capitalize('hello world')
Out[7]: 'Hello world'
# 首字母大写
In [8]: str.title('hello world')
Out[8]: 'Hello World'
# 获取固定长度,左对齐,右边不够用空格补齐
In [10]: 'Hello world'.ljust(20)
Out[10]: 'Hello world         '
# 获取固定长度,右对齐,左边不够用空格补齐
In [11]: 'Hello world'.rjust(20)
Out[11]: '         Hello world'
# 获取固定长度,中间对齐,两边不够用空格补齐
In [12]: 'Hello world'.center(20)
Out[12]: '    Hello world     '
# 获取固定长度,右对齐,左边不够用0补齐
In [13]: 'Hello world'.zfill(20)
Out[13]: '000000000Hello world'
# 搜索指定字符串,没有返回-1
In [14]: 'Hello world'.find('t')
Out[14]: -1
In [15]: 'Hello world'.find('o')
Out[15]: 4
# 指定起始位置搜索
In [16]: 'Hello world'.find('o',6)
Out[16]: 7
# 指定起始及结束位置搜索
In [19]: 'Hello world'.find('o',6,8)
Out[19]: 7
In [20]: 'Hello world'.find('o',6,7)
Out[20]: -1
# 从右边开始查找
In [17]: 'Hello world'.rfind('o')
Out[17]: 7
# 搜索到多少个指定字符串
In [18]: 'Hello world'.count('o')
Out[18]: 2
# 上面所有方法都可用index代替,不同的是使用index查找不到会抛异常,而find返回-1

# 字符串替换
In [21]: 'Hello world'.replace('world','wwzero')
Out[21]: 'Hello wwzero'
# 指定次数的替换
In [22]: 'Hello world world world'.replace('world','wwzero',2)
Out[22]: 'Hello wwzero wwzero world'
# 去两边空格
In [23]: '    Hello wwzero      '.strip()
Out[23]: 'Hello wwzero'
# 去左空格
In [24]: '    Hello wwzero      '.lstrip()
Out[24]: 'Hello wwzero      '
# 去右空格
In [25]: '    Hello wwzero      '.rstrip()
Out[25]: '    Hello wwzero'
# 去除两边的指定字符  lstrip rstrip 也有类似的方式
In [28]: 'dddHello wwzeroddd'.strip('f')
Out[28]: 'dddHello wwzeroddd'
In [29]: 'dddHello wwzeroddd'.strip('d')
Out[29]: 'Hello wwzero'
# 按指定字符分割字符串为数组
# string.split(s, sep=None, maxsplit=-1)用sep拆分s,返回拆分后的列表,如果sep没有提供或者为None,那么默认的就是空格
In [30]: 'Hello wwzero'.split()
Out[30]: ['Hello', 'wwzero']
In [32]: 'Hello wwzero'.split('e')
Out[32]: ['H', 'llo wwz', 'ro']

In [35]: str.split('hello wwzero')
Out[35]: ['hello', 'wwzero']
# 将数组拼接成字符串
# join(list [,sep])是用sep把list组合成一个字符串返回。
In [36]: string.join(str.split('hello wwzero'))
Out[36]: 'hello wwzero'

# 是否以指定字符串开头
In [39]:  'hello wwzero'.startswith('hello')
Out[39]: True
In [40]:  'hello wwzero'.startswith('he')
Out[40]: True
In [41]:  'hello wwzero'.startswith('Hello')
Out[41]: False
# 是否以指定字符串结尾
In [42]:  'hello wwzero'.endswith('Hello')
Out[42]: False
In [43]:  'hello wwzero'.endswith('o')
Out[43]: True
# 是否全为字母
In [44]:  'hello wwzero'.isalpha()
Out[44]: False
In [46]:  'hellowwzero'.isalpha()
Out[46]: True
# 是否全为数值
In [45]:  'hello wwzero'.isdigit()
Out[45]: False
# 是否全小写
In [47]:  'hellowwzero'.islower()
Out[47]: True
# 是否全大写
In [48]:  'hellowwzero'.isupper()
Out[48]: False

参考资料

https://docs.python.org/2/library/string.html
https://docs.python.org/2/library/stdtypes.html#str.join
http://www.cnblogs.com/rollenholt/archive/2011/11/25/2263722.html

Random

random是用于生成随机数

# random.random()    用于生成一个随机浮点数:range[0.0,1.0)
In [52]: random.random()
Out[52]: 0.31711793445904135

# random.uniform(a,b)    用于生成一个指定范围内的随机浮点数,a,b为上下限,只要a!=b,就会生成介于两者之间的一个浮点数,若a=b,则生成的浮点数就是a
In [54]: random.uniform(10,23)
Out[54]: 11.909177993459068
In [55]: random.uniform(10,23)
Out[55]: 21.549287472540513
# random.randint(a,b)    用于生成一个指定范围内的整数,a为下限,b为上限,生成的随机整数a<=n<=b;若a=b,则n=a;若a>b,报错
In [56]: random.randint(10,44)
Out[56]: 25
In [57]: random.randint(10,44)
Out[57]: 32
# random.randrange([start], stop [,step])    从指定范围内,按指定基数递增的集合中获取一个随机数,基数缺省值为1
In [58]: random.randrange(10,200)
Out[58]: 195
In [59]: random.randrange(10,200,3)
Out[59]: 19
In [60]: random.randrange(10,200,3)
Out[60]: 34
# random.choice(sequence)    从序列中获取一个随机元素,参数sequence表示一个有序类型,并不是一种特定类型,泛指list,tuple,字符串等
In [61]: random.choice(range(12))
Out[61]: 1

In [62]: random.choice('hello wwzero')
Out[62]: 'l'
In [64]: random.choice('hello wwzero')
Out[64]: 'h'
In [66]: random.choice('hello wwzero')
Out[66]: 'r'
In [68]: random.choice(['hello','wwzero'])
Out[68]: 'wwzero'

In [69]: random.choice(['hello','wwzero'])
Out[69]: 'hello'

# random.shuffle(x[,random])    用于将一个列表中的元素打乱
In [71]: l = ['i','hello','wwzero','world']
In [72]: random.shuffle(l)
In [73]: l
Out[73]: ['wwzero', 'world', 'hello', 'i']
# random.sample(sequence,k)    从指定序列中随机获取k个元素作为一个片段返回,sample函数不会修改原有序列
In [75]: import random
    ...: a='123456789'
    ...: b=[1,2,3,4,5,6,7,8,9]
    ...: c=['a','b','c','d','e']
    ...: d= random.sample(a,3)
    ...: e= random.sample(b,3)
    ...: f= random.sample(c,3)  #随机取个元素片段返回[6,4,3]
    ...: print a
    ...: print b
    ...: print c    #a,b,c值
    ...: print d
    ...: print e
    ...: print f
    ...:
    ...:
123456789
[1, 2, 3, 4, 5, 6, 7, 8, 9]
['a', 'b', 'c', 'd', 'e']
['1', '8', '7']
[5, 2, 1]
['a', 'c', 'd']

参考资料

https://docs.python.org/2/library/random.html
posted @ 2017-02-26 16:30  Ww2zero  阅读(531)  评论(0)    收藏  举报