第 0001 题

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

这里的激活码我简单认为是英文字母和阿拉伯数字的组合, 且各部分占比尽量相等。

import random

def add_list(list_, sublist):
    list_.extend(sublist)

def get_code():
    try:
        length = int(input('please enter the length of your code:\n'))
        nums = [str(n) for n in range(10)]
        upper_words = [chr(u) for u in range(65, 91)]
        lower_words = [chr(l) for l in range(97, 123)]
        init_code = nums + upper_words + lower_words
        if length >= 3:
            activate_code = []
            size = length // 3
            add_list(activate_code, random.sample(nums, size))
            add_list(activate_code, random.sample(upper_words, size))
            add_list(activate_code, random.sample(lower_words, size))
            if len(activate_code) < length:
                activate_code.extend(random.sample(init_code, length - len(activate_code)))
            random.shuffle(activate_code)
            final_code = ''.join(activate_code)
            return final_code
        else:
            print('please enter an integer greater than 3!')
    except ValueError:
        print('your input is not integer!')

你可能感兴趣的:(第 0001 题)