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:
                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 = (  )

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM