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

首頁 > 學院 > 開發設計 > 正文

小學數學運算題出題程序

2019-11-11 03:13:54
字體:
來源:轉載
供稿:網友

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

需求

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

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

原始代碼

#coding: utf-8"""本代碼來自第一感覺,使用函數實現。添加問題類型時,直接修改 main() 的 question_list 語句即可"""import randomdef question_1(): """生成 100 以內退位減法""" 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(): """生成兩位數加法""" num1 = random.randint(10, 99) num2 = random.randint(10, 99) answer = num1 + num2 return ('%d + %d =' % (num1, num2), str(answer))def question_3(): """生成兩位數減兩位數""" 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 美化化輸出結果,方便之后導入 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 = 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 實現 question_generator

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

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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 名山县| 岢岚县| 龙南县| 平凉市| 子洲县| 元阳县| 平武县| 应城市| 定西市| 望奎县| 方城县| 天津市| 秦安县| 特克斯县| 大宁县| 唐海县| 禄劝| 弥渡县| 河南省| 介休市| 麻江县| 包头市| 岚皋县| 博客| 夏津县| 郑州市| 九龙县| 张家川| 鲜城| 佛教| 榕江县| 崇阳县| 河南省| 博客| 龙里县| 清涧县| 东乌| 师宗县| 西城区| 盖州市| 法库县|