003《Python数据分析、挖掘与可视化(第2版)》/模拟生成志愿选科要求和计划数.py
from random import randint, sample, choice

# 所有选考科目
courses = ('物理', '化学', '生物', '历史', '地理', '思想政治')
# 选考科目之间的关系,|表示“或”,+表示“和”
relations = '|+'
# 计划人数之和
total = 0
with open('各志愿计划人数与选科要求.csv', 'w', encoding='utf8') as fp:
    fp.write('志愿名称,计划人数,选科要求\n')
    # 假设有1000个志愿
    for i in range(1, 1001):
        # 每个志愿至少招生1人,至多招生20人
        rnd = randint(1, 20)
        total = total + rnd
        line = f'志愿{i},{rnd},'
        # 当前志愿的选考科目要求
        my_choices = sample(courses, randint(0,3))
        if not my_choices:
            line = line + '不限'
        else:
            # 随机生成选考科目之间的关系
            line = line + choice(relations).join(my_choices)
        fp.write(line+'\n')
print(total)