[英]Python - Why is my list not being modified outside the scope of this method? How do I modify my code so that it is?
[英]How do I modify my code so that it takes into consideration special operations for integer 1 and 0?
我有一個operator()
,它接受輸入並在字符串中輸出數學計算。 見下文:
def operator():
char = input("Enter your operator / value: ")
if char == "+":
return "(" + operator() + " + " + operator() + ")"
elif char == "-":
return "(" + operator() + " - " + operator() + ")"
elif char == "*":
return "(" + operator() + " * " + operator() + ")"
elif char == "/":
return "(" + operator() + " / " + operator() + ")"
else:
return char
例如,這些是返回語句:
>>> operator()
-
4
+
2
1
'(4 - (2 + 1))'
但是,現在我想考慮這些操作:
0 + x = x
0 * x = 0
1 * x = x
x / 1 = x
所以對於這種情況
>>> operator()
+
0
1
將打印1
而不是(0 + 1)
。 我應該如何修改我的代碼來做到這一點?
您的解決方案要求您在評估操作之前存儲操作數:
def operator():
char = input("Enter your operator / value: ")
if char in ["+", "-", "*", "/"]:
# store the operands
operand_1 = operator()
operand_2 = operator()
# analyze the individual cases
if char == '+':
if operand_1 == '0':
return operand_2
elif operand_2 == '0':
return operand_1
elif char == '*':
if operand_1 == '0' or operand_2 == 0:
return '0'
elif operand_1 == '1':
return operand_2
elif operand_2 == '1':
return operand_1
elif char == '/':
if operand_2 == '1':
return operand_1
# if no special condition is met, return the normal expression
return "(" + operand_1 + " " + char + " " + operand_2 + ")"
else:
return char
這甚至實現了嵌套簡化,因此 2/(1+0) 變為 2
>>> operator()
Enter your operator / value: >? /
Enter your operator / value: >? 2
Enter your operator / value: >? +
Enter your operator / value: >? 1
Enter your operator / value: >? 0
'2'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.