Continue to do the question:
Generate the activation code
Analyze the problem:
Generally speaking, the company in the activities of the time will have a batch of activation code out, the normal format of the activation codes are xxxxx-xxxxx ... Format, and is randomly generated, I use Python's random module here.
Solve the problem:
#!/usr/bin/env python# -*- coding: utf-8 -*-import randomdef create_key (Key _NUM,KEY_FMT): key = ' temp_list = [] for i in range (KEY_FMT): for i in range (key_num): if i != random.randrange (0,3):      STRING = CHR (Random.randint (65,90)) else: string = random.randint (0,9) key+=str (String) temp_ List.append (Key) key = ' return ('-'). Join (Temp_ List) if __name__ == ' __main__ ': print create_key (5,5)
However, Baidu has a bit of other people's implementation, found that their code is good low Ah, the code of others are relatively streamlined, or write less Ah, the following reference to other people's Code:
He mainly uses three functions:
# First: Determine the number of random combinations to generate # The second: Make sure that each activation code has several sets of # Third: Determine the number of generated activation codes # Activation code similar to ASQE-9XRK-LQWU-QKMT
Specific code:
#!/usr/bin/env python#-*-coding:utf-8-*-import randomimport stringfiled = String.digits+string.lettersdef get_random (): Return '. Join (Random.sample (filed,4)) def concatenate (n): Return '-'. Join ([Get_random () for I in range (n)]) def G Enerate (n): Return [CONCATENATE (4) for I in range (n)]if __name__ = = ' __main__ ': print Generate (200)
The main use of the list deduction, simplifying the code, improve the readability
You need to be aware of writing code later:
1 Thinking about the implementation process before writing
2 Organizing and optimizing the implementation process
3 Try to express complex meanings with thin code
4 Learn more about how others code is implemented
Postscript:
Here is just a simple implementation to generate coupons, but does not take into account the problem of repeatability, in the actual production environment to use is definitely not, how to generate a unique key, this is the next problem to solve. You can refer to this article:
Http://linsir.org/post/Creat-the-unique-activation-code-with-python
Reference article:
http://blog.csdn.net/huangxiongbiao/article/details/45016649
http://www.oschina.net/code/snippet_1866842_45177
This article is from "a struggling small operation" blog, please be sure to keep this source http://yucanghai.blog.51cto.com/5260262/1716436
Python Workbook, a small program every day--0001 questions