techlynn

儿子今年开始上幼小衔接, 老师布置的作业是每天出20道加减法算术题. 一开始都是他妈妈给他出的, 这几天放假, 这个任务就落到了我的身上.

每天都要出20道题, 实在是太麻烦了, 身为一个码农, 当然是代码走起(好吧, 其实是搜索走起).

网上有很多此功能的代码, 基本上都是生成类似于1+2=?的格式, 需要计算的部分都是等号右边的结果. 不过给儿子出的题, 老师要求的是对算术题填空, 类似于?+1=3的格式.

将网上的代码稍加修改, 加上随机生成算术题中填空的代码, 这样以后就轻松啦

# -*- coding: utf-8 -*-  
""" 
@author: DoraVemon
@file: autogen_arith.py 
@time: 2018/10/2 8:45 
"""

import random
from datetime import datetime


def add_test(sum_value, count):
    \'\'\'
    返回指定个数(count)的计算题,以计算某数(sum_value)以内的加法
    :param sum_value: 指定某数以内(的加法)
    :param count: 随机生成多少题
    :return: 返回count个计算题
    \'\'\'

    questions = []
    count_temp = 0  # 计数器

    while True:
        i = random.randrange(0, sum_value)  # 随机生成 第一个加数
        j = random.randrange(1, sum_value + 1)  # 随机生成 和
        l = j - i  # 第二个加数
        if l > 0:
            # str_temp = str(i) + \' + \' + str(l) + \'\' + \' =    \n\'
            # questions += str_temp
            questions.append((i, l, j))
            count_temp += 1
            if count_temp >= count:
                break

    return questions


def resort(quiz):
    rng_index = random.randint(0, 2)
    flag_addsub = random.randint(0, 1)
    if flag_addsub:
        str_temp = (str(quiz[0]) if rng_index != 0 else \'(  )\') + \' + \' \
                   + (str(quiz[1]) if rng_index != 1 else \'(  )\') \
                   + \' = \' \
                   + (str(quiz[2]) if rng_index != 2 else \'(  )\') + \'\n\'
    else:
        str_temp = (str(quiz[2]) if rng_index != 0 else \'(  )\') + \' - \' \
                   + (str(quiz[1]) if rng_index != 1 else \'(  )\') \
                   + \' = \' \
                   + (str(quiz[0]) if rng_index != 2 else \'(  )\') + \'\n\'
    return str_temp


def main():
    sum_value, count = 10, 20  # 随机出20题,10以内的加减法
    text = \'\'
    quizs = add_test(sum_value, count)
    for quiz in quizs:
        text += resort(quiz)
    title = \'%d以内加法算术题\' % sum_value + datetime.now().strftime("_%Y%m%d") + \'.txt\'
    with open(title, "w") as f:
        f.write(text)
    f.close()


if __name__ == \'__main__\':
    main()

 

 出来的题目是这样子的

4 - (  ) = 1
3 + (  ) = 9
6 - 2 = (  )
(  ) - 1 = 0
7 - 7 = (  )
7 - 2 = (  )
4 - (  ) = 3
9 - 4 = (  )
4 + 1 = (  )

 

 

分类:

技术点:

相关文章:

  • 2021-12-31
  • 1970-01-01
  • 2022-12-23
  • 2021-12-16
  • 2021-12-28
  • 2021-06-30
  • 2021-12-12
  • 2022-01-14
猜你喜欢
  • 2022-12-23
  • 2021-08-10
  • 2021-07-01
  • 2021-12-31
  • 2022-12-23
  • 2021-04-16
相关资源
相似解决方案