簡體   English   中英

如何修改我的代碼,以便它考慮整數 1 和 0 的特殊操作?

[英]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))'

但是,現在我想考慮這些操作:

  1. 0 + x = x

  2. 0 * x = 0

  3. 1 * x = x

  4. 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM