繁体   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