Арифметические выражения в Python не работают с более чем одним значением - PullRequest
0 голосов
/ 18 сентября 2018

Это парсер, который я пытаюсь создать, и он идет хорошо, но почему-то я не могу делать арифметические выражения с более чем одним значением места.Он работает для всего до 9, но не для 10 или 21. Вторая функция предназначена только для интеграции доступа к текстовым файлам.

Например, я могу сделать 9 * 9, но я не могу сделать 12 * 8.

# AditPradipta_Equation_Solving

def only_parsing(equation):
    operators = {0: lambda x, y : int(x) + int(y),
         1: lambda x, y : int(x) - int(y),
         2: lambda x, y : int(x) * int(y),
         3: lambda x, y : int(x) / int(y)}
    operators_list = ["+", "-", "*", "/"]
    equation = equation.strip()
    equation = equation.strip("=")
    print(equation)
    operator_num = 0
    for operator in operators_list:
        if operator_num == 3:
            zero_division_check = equation.find("0")
            if not zero_division_check != True:
                continue
            elif not zero_division_check != False:
                return "You cannot divide by 0."
        operator_find = equation.find(operators_list[operator_num])
        if not operator_find != True:
            first_num = equation[0]
            second_num = equation[-1]
            return operators[operator_num](int(first_num), int(second_num))
        else:
           operator_num = operator_num + 1

def multi_line_parsing(filename, new_file_name):
    file = open(filename, 'r')
    file_lines = file.readlines()
    print(file_lines)
    new_file = []
    for line in file_lines:
        print(line)
        new_file.append(str(only_parsing(line)) + str("\n"))
        print(new_file)
    new_file_string_data = ''.join(new_file)
    print(new_file_string_data)
    file.close()
    write_file = open(new_file_name, 'w+')
    write_file.write(new_file_string_data)
    write_file.close()
    return

file_name = input("Please enter a filename: ")
new_file = input("Please enter another new file name: ")
multi_line_parsing(file_name, new_file)

Пример ожидаемого ввода и вывода и фактического ввода и вывода:

    #Expected input
    12 * 8
    100 * 10

    #Expected Output
    96
    1000

    #Actual Output
    None
    None

Любая помощь приветствуется.

1 Ответ

0 голосов
/ 18 сентября 2018

Комментарий : str.split() ... только хорошо ... отформатирован с пробелами.
Он не будет корректно маркировать "12 * 8"

Для обработки обоих и других возможных форматов замените на re.split(...), например:

    import re
    # Split by blank, require ALWAYS three parts delimited with blank
    v1, v2 = re.split('[\+\-\*\/]', equation)
    op = equation[len(v1)]

Вывод :

12*8 = 96  
12* 8 = 96  
100  *10 = 1000  
division by zero: You cannot divide by 0  
12 / 0 = None  

Вопрос : арифметические выражения ... не работает с более чем одним значением места

Использование str.split() васможет обрабатывать значения любой длины.

Упростите ваш подход, например:

def only_parsing(equation):
    # Use the operators as dict key
    operators = {'+': lambda x, y: int(x) + int(y),
                 '-': lambda x, y: int(x) - int(y),
                 '*': lambda x, y: int(x) * int(y),
                 '/': lambda x, y: int(x) / int(y)}

    # Split by blank, require ALWAYS three parts delimited with blank
    v1, op, v2 = equation.split()
    #print("{}".format((v1, op, v2)))

    # Use try:...except to catch ZeroDivisionError
    try:
        # Call the lambda given by dict key
        return operators[op](v1, v2)

    except ZeroDivisionError as e:
        print("{}: You cannot divide by 0".format(e,))

for exp in ['12 * 8', '100 * 10', '12 / 0']:
    print("{} = {}".format(exp, only_parsing(exp)))

Qutput :

12 * 8 = 96  
100 * 10 = 1000  
division by zero: You cannot divide by 0  
12 / 0 = None  

Протестировано на Python: 3.4.2

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...