快速生成200个 xxxxx-xxxxx-xxxxx-xxxxx 格式的激活码,统计每个字符出现的次

今天看到一个很有意思的题:

分析:题中有快速和统计

1.使用生成器

2.字典来统计

以下代码仅为抛砖引玉:

import string
import random

class ITer_:
    def __init__(self):
        self.chars = string.ascii_letters + string.digits

    def __iter__(self):
        for _ in range(200):
            codes =[]
            for _ in range(4):
                codes.append("".join(random.choices(self.chars, k=5)))
                # random.shuffle(codes)
            yield "-".join(codes)

result = "".join([x.stri("-") for x in ITer_()])

# 注意 strip 和repalce
count_tmp = {}
for k in result:
    count_tmp[k] = count_tmp.get(k, 0) + 1

这里借用了string和random扩展库,有兴趣的可以看看它们的源码,很有意思的。

猜你喜欢

转载自blog.51cto.com/14730644/2474197