天天看點

第5次作業--四則運算

四則運算

GitHub項目位址:   https://github.com/ZJW9633/hello-word/blob/master/ElArith.py

PSP

PSP2.1 Personal Software Process Stages 預估耗時(分鐘) 實際耗時(分鐘)
Planning 計劃  10  23
Estimate 估計這個任務需要多少時間 15   /
Development 開發  40  60
Analysis 需求分析(包括學習新技術) 60
Design Spec 生成設計文檔
Design Review 設計複審(和同僚稽核設計文檔)  20  25
Coding Standard 代碼規範(為目前的開發制定合适的規範) 10
Design 具體設計
Coding 具體編碼  120
Code Review 代碼複審  15
Test 測試(自我測試,修改代碼,送出修改)
Reporting 報告
Test Report 測試報告  45
Size Measurement 計算工作量
Postmortem & Process Improvement Plan 事後總結,并提出過程改進計劃
合計  325  460

項目要求

  • 參與運算的操作數(operands)除了100以内的整數以外,還要支援真分數的四則運算。操作數必須随機生成。
  • 運算符(operators)為 +, −, ×, ÷ 運算符的種類和順序必須随機生成。
  • 要求能處理使用者的輸入,并判斷對錯,打分統計正确率。
  • 使用 參數控制生成題目的個數。

解題思路:

  • 定義一個函數用于随機生成随機長度的算式
  • 把字元串型的算式轉換為逆波蘭式(RPN,也稱字尾表達式)
  • 再把字尾表達式利用棧結構計算出結果
  • 最後再與使用者的輸入做比較

重點難點:

  • 計算結果為負數的情況
  • 分數的表示和計算

難點解決思路:

  • 使用python的fractions庫

代碼說明:

#算式轉換形式      
def toRpn(self, question):
        self.stack = []
        s = ''
        for x in question:
            if x != '+' and x != '-' and x != '×' and x != '÷' and x != '/':
                s += x  #若為數字,直接輸出
            else:  # 若為運算符,進棧
                if not self.stack:  #棧空
                    self.stack.append(x)
                else:
                    if self.this_bigger(x, self.stack[-1]):  #運算級高于棧頂元素
                        self.stack.append(x)  #直接進棧
                    else:
                        while self.stack:
                            if self.this_bigger(x, self.stack[-1]):
                                break
                            s += self.stack.pop()
                        self.stack.append(x)
        while self.stack:
            s += self.stack.pop()
        return s      

代碼測試

C:\Users\Administrator\PycharmProjects\untitled\venv\Scripts\python.exe C:/Users/Administrator/PycharmProjects/untitled/size.py
please input the num of question:10
----------the total of question is:10----------
the 1/10 question is :5×3-2+4-8×8/9=
1
Your answer is wrong !The right answer is :89/9
the 2/10 question is :5+8/9÷1×3×7/9-4=
2
Your answer is wrong !The right answer is :83/27
the 3/10 question is :7÷8-1+8×8/9-4/9×8=
3
Your answer is wrong !The right answer is :247/72
the 4/10 question is :4+6/9+5=
87/9
Your answer is wrong !The right answer is :29/3
the 5/10 question is :2÷8+7÷3×1+8=
1
Your answer is wrong !The right answer is :127/12
the 6/10 question is :0+7/9+2+7÷6÷1=
2
Your answer is wrong !The right answer is :71/18
the 7/10 question is :3/5-8÷3+1×6/7×7×1=
3
Your answer is wrong !The right answer is :59/15
the 8/10 question is :4/6÷6=
4/36
Your answer is wrong !The right answer is :1/9
the 9/10 question is :7+3-6×0÷6=

Your answer is wrong !The right answer is :10
the 10/10 question is :8÷1÷6+7×2÷5/8×7/8=
2
Your answer is wrong !The right answer is :787/480
-------------------------------------
----------you have pass 0 question----------

Process finished with exit code 0      

 效能分析,可用python的profile進行

結果:暫無