Python每日一题 002

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

在此生成由数字,字母组成的20位字符串

uuid模块

import uuid

def get_id():
    file_object = open('uudi.txt','w+')
    for i in range(200):
        ID = str(uuid.uuid1()) + '\n'
        file_object.write("ID"+str(i+1)+":"+ID)
    file_object.close()

if __name__ == '__main__':
    get_id()

random模块

# coding:utf-8
# python3环境
# 通过多线程来生成200个激活码
import random
import string
import threading

def get_str():
    ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 20))
    return ran_str


class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("开始线程:" + self.name)
        write_id(self.name, 40)
        print ("退出线程:" + self.name)

def write_id(threadName, counter):
    file_object=open('id.txt','a+')
    while counter:
        file_object.write("%s: %s\n" % (threadName+str(counter), get_str()))
        counter -= 1
    file_object.close()

# 创建新线程
thread1 = myThread(1, "Group1-", 1 )
thread2 = myThread(2, "Group2-", 2)
thread3 = myThread(3, "Group3-", 3)
thread4 = myThread(4, "Group4-", 4)
thread5 = myThread(5, "Group5-", 5)

# 开启新线程
thread1.start()
thread2.start()
thread3.start()
thread4.start()
thread5.start()

thread1.join()
thread2.join()
thread3.join()
thread4.join()
thread5.join()

print ("退出主线程")

参考链接

https://docs.python.org/3/library/random.html

https://www.runoob.com/python/func-number-random.html

https://www.runoob.com/python/python-files-io.html

https://docs.python.org/3.6/library/uuid.html

猜你喜欢

转载自www.cnblogs.com/CH42e/p/11954461.html
002