Как мне изменить мой код, чтобы он учитывал специальные операции для целых чисел 1 и 0? - PullRequest
0 голосов
/ 21 февраля 2020

У меня есть 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

Так что для ситуации, когда вместо (0 + 1) будет напечатано

>>> operator()
+ 
0
1

1. Как мне изменить свой код для этого?

1 Ответ

0 голосов
/ 21 февраля 2020

Ваше решение требует сохранения операндов перед оценкой операции:

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