python的加减乘除运算_python实现四则运算
https://gitee.com/szh123/four_arithmetic_implementation.git
1.需求分析:
實現四則運算題目及答案生成,控制生成題目的個數,題目中數值不超過10且有分數存在并用真分數表示。
可以生成10000道題
運算符不超過3個
題目不能出現重復即不能經過有限次交換成為相同題目
可以提供對給出的題目進行查重及答案求解并輸出結果
2.功能設計:
(1)基礎功能:實現四則運算題目和答案的生成,對生成的四則運算題目進行查重,支持對提供的題目進行查重和答案求解并給出正確錯誤及題目重復的結果
(2)擴展功能:
(3)高級功能:
3.設計實現:
類1:生成隨機數
類2:生成整個表達式
類3:表達式轉換成為逆波蘭式
類4:樹
類5:類中存放一個數的分子與分母,同時toString方法輸出真分數形式
類6:計算結果
類7:二叉樹的查重
類8:主函數
4.代碼說明:
生成表達式
def createarithmetic(self):
list = []
f1 = function1.function1()
f2 = function2()
operator_no = random.randint(1,3)
if operator_no == 1:
list.append(f1.createNum())
list.append(f2.createOperator())
list.append(f1.createNum())
elif operator_no == 2:
start = random.randint(0,2)
end = 0
if start == 0:
end == 0
else:
end = start +1
for i in range(1,4):
if i == start:
list.append("(")
list.append(f1.createNum())
if i == end:
list.append(")")
list.append(f2.createOperator())
list.pop()
elif operator_no == 3:
start = random.randint(0, 3)
end = 0
if start == 0:
end == 0
else:
end = start + 1 + random.randint(0,1)
if end >= 4:
end=4
for i in range(1, 5):
if i == start:
list.append("(")
list.append(f1.createNum())
if i == end:
list.append(")")
list.append(f2.createOperator())
list.pop()
else:
list.append(f1.createNum())
list.append(f2.createOperator())
list.append(f1.createNum())
return list
逆波蘭式生成
def toRPN(self,list):
right = []
aStack = []
position = 0
while True:
if self.isOperator(list[position]):
if list ==[] or list[position] == "(" :
aStack.append(list[position])
else:
if list[position] == ")":
while True:
if aStack != [] and aStack[-1] !="(" :
operator = aStack.pop()
right.append(operator)
else :
if aStack !=[]:
aStack.pop()
break
else:
while True:
if aStack != [] and self.priority(list[position],aStack[-1]):
operator = aStack.pop()
if operator != "(":
right.append(operator)
else:
break
aStack.append(list[position])
else:
right.append(list[position])
position = position +1
if position >= len(list):
break
while aStack != []:
operator = aStack.pop()
if operator != "(":
right.append(operator)
return right
5.測試運行:
主界面
選擇功能1:
題目
答案
選擇功能2:
6.PSP
7.小結:
逆波蘭式的生成和計算,二叉樹的查重非常方便
總結
以上是生活随笔為你收集整理的python的加减乘除运算_python实现四则运算的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python分析股票数据_Python数
- 下一篇: 华三交换机路由器图标_弱电箱网口不够用,