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

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

小學數學運算題出題程序

2019-11-11 04:28:35
字體:
來源:轉載
供稿:網友

需求原始代碼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 文件


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 东丽区| 正安县| 云龙县| 彭山县| 应城市| 绥滨县| 嘉义市| 洱源县| 凤凰县| 太仆寺旗| 福贡县| 綦江县| 东乡族自治县| 襄汾县| 闽侯县| 辽源市| 余姚市| 巴林右旗| 交口县| 宜宾市| 昂仁县| 尤溪县| 新津县| 拜城县| 德兴市| 华宁县| 平定县| 海丰县| 阿克陶县| 徐闻县| 遵义市| 田阳县| 富平县| 周口市| 湘潭县| 宁乡县| 同江市| 泌阳县| 鲁山县| 册亨县| 墨竹工卡县|