国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

小學(xué)數(shù)學(xué)運算題出題程序

2019-11-11 02:59:43
字體:
供稿:網(wǎng)友

需求原始代碼refactoring引入 with 語句處理文件用 dict 代替 list 實現(xiàn) question_generator利用 list 切片將輸出的問題與答案分開改為合起來利用格式化 Excel 文件代替 txt 文件

需求

朋友擔(dān)心小孩暑假玩瘋了,讓我弄點小學(xué)一年級數(shù)學(xué)題給小孩做,要求: 1. 就是簡單的口算式子 2. 可以打印成 A4 紙 3. 有答案

根據(jù)要求,我覺得最簡單的辦法,就是生成一個內(nèi)容用 tab 分隔開的 txt 文件,然后手工復(fù)制到排版好的 Excel 文件里面直接打印即可。

原始代碼

#coding: utf-8"""本代碼來自第一感覺,使用函數(shù)實現(xiàn)。添加問題類型時,直接修改 main() 的 question_list 語句即可"""import randomdef question_1(): """生成 100 以內(nèi)退位減法""" minuend = random.randint(11,98) units = minuend % 10 while units==9 : minuend = random.randint(11,98) units = minuend % 10 subtrahend = random.randint(units+1,9) answer = minuend - subtrahend return ("%d - %d = " % (minuend, subtrahend), str(answer))def question_2(): """生成兩位數(shù)加法""" num1 = random.randint(10, 99) num2 = random.randint(10, 99) answer = num1 + num2 return ('%d + %d =' % (num1, num2), str(answer))def question_3(): """生成兩位數(shù)減兩位數(shù)""" minuend = random.randint(11,99) subtrahend = random.randint(10, minuend) answer = minuend - subtrahend return ("%d - %d = " % (minuend, subtrahend), str(answer))def write_it(questions, answers, output_file): format_items(questions) format_items(answers) f = open(output_file, 'w') f.write("".join(questions)) f.write("/n/n/n") f.write("".join(answers)) f.close()def format_items(items, number_per_line = 4): """用換行、tab 美化化輸出結(jié)果,方便之后導(dǎo)入 excel""" for i,a in enumerate(items): if i % number_per_line == number_per_line - 1: items[i] = a + "/n" else: items[i] = a + "/t"def main(output_file, question_type = 1): """question_type取值:1 到 3 """ questions = [] answers = [] question_generator = [question_1, question_2, question_3] for x in range(80): question, answer = question_list[question_type - 1]() PRint( question) questions.append(question) answers.append(answer) print("now write it") write_it(questions, answers, output_file)if __name__ == '__main__': output_file = "out.txt" main(output_file)

refactoring

引入 with 語句處理文件

以便在發(fā)生異常的時候自動關(guān)閉資源。將

f = open(output_file, 'w')f.write("".join(questions))f.write("/n/n/n")f.write("".join(answers))f.close()

改為

with open(output_file, 'w') as f: f.write("".join(questions)) f.write("/n/n/n") f.write("".join(answers))

用 dict 代替 list 實現(xiàn) question_generator

利用 list 切片,將輸出的問題與答案分開改為合起來

利用格式化 excel 文件代替 txt 文件


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 建德市| 三都| 保山市| 嘉荫县| 开阳县| 新化县| 固阳县| 许昌县| 巩留县| 延寿县| 长汀县| 绥宁县| 城口县| 苍南县| 徐州市| 贺兰县| 青川县| 东兰县| 开江县| 蓬莱市| 衡山县| 通化市| 任丘市| 邵武市| 镇坪县| 休宁县| 电白县| 玉门市| 八宿县| 祁连县| 深水埗区| 新和县| 尼木县| 绥江县| 尤溪县| 宽城| 固原市| 石柱| 巴彦淖尔市| 景洪市| 若羌县|