简体   繁体   中英

How do I modify my code so that it takes into consideration special operations for integer 1 and 0?

I have a operator() which takes in inputs and outputs the mathematical calculation in a string. See below:

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

These are the return statements for example:

>>> operator()
-
4
+
2
1
'(4 - (2 + 1))'

However, now I want to take into account these operations:

  1. 0 + x = x

  2. 0 * x = 0

  3. 1 * x = x

  4. x / 1 = x

So for the situation where

>>> operator()
+ 
0
1

1 will be printed instead of (0 + 1) . How should I modify my code to do so?

Your solution requires that you store the operands before evaluating the operation:

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

This even achieves nested simplification, so 2/(1+0) becomes 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM