当前位置:首页 > Python教程 > python技巧

python自动生成加减法算术题

儿子今年开始上幼小衔接, 老师布置的作业是每天出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:
                breakreturn 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(  )) + nelse:
        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(  )) + nreturn 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 = (  )
        

 

 

原文:https://www.cnblogs.com/techlynn/p/9736351.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐