Menu
Coddy logo textTech

Operatory pierwszego poziomu

Lekcja 13 z 29 w kursie Projekt kalkulatora w Python w Coddy.

Jak już wcześniej omówiliśmy, w matematyce obowiązuje kolejność działań.

Operatory '*', '/' i '%' są obliczane przed '+' i '-'.

W tym kursie nazywamy operatory '*', '/' i '%' — operatorami pierwszego poziomu.

A operatory '+' i '-' — operatorami drugiego poziomu.

challenge icon

Wyzwanie

Łatwy

Obecnie struct obsługuje tylko operatory poziomu drugiego.

Twoim zadaniem jest dodanie do struct obsługi operatorów poziomu pierwszego.

Upewnij się, że kolejność obliczeń jest zachowana!

Przykłady:

  • struct([3, '*', 2])  ->  ['*', 3, 2]
  • struct([1, '+', 2, 'mul', 3])  ->  ['+', 1, ['mul', 2, 3]]
  • struct([2, 'mod', 3, '-', 4, '/', 5.2])  ->  ['-', ['mod', 2, 3], ['/', 4, 5.2]]

Spróbuj swoich sił

def calc(op, n1, n2=None):
    if not isinstance(n1, int) and not isinstance(n1, float):
        raise Exception('Invalid number "' + str(n1) + '"')

    if n2 is None:
        if op == '+' or op == 'add':
            return n1
        if op == '-' or op == 'sub':
            return -n1

        raise Exception('Invalid operator "' + op + '"')

    if not isinstance(n2, int) and not isinstance(n2, float):
        raise Exception('Invalid number "' + str(n2) + '"')

    if op == '+' or op == 'add':
        return n1 + n2
    if op == '-' or op == 'sub':
        return n1 - n2
    if op == '*' or op == 'mul':
        return n1 * n2
    if op == '/' or op == 'div':
        if n2 == 0:
            raise Exception("Division by zero")
        return n1 / n2
    if op == '%' or op == 'mod':
        if n2 == 0:
            raise Exception("Division by zero")
        return n1 % n2
    if op == '^' or op == 'pow':
        return n1 ** n2

    raise Exception('Invalid operator "' + op + '"')


def eval(lst):
    if not isinstance(lst, list):
        raise Exception('Failed to evaluate "' + str(lst) + '"')
    if len(lst) == 2:
        op = lst[0]
        n = lst[1]
        if not isinstance(n, list):
            return calc(op, n)

        if isinstance(n, list):
            n = eval(n)

        return calc(op, n)
    elif len(lst) == 3:
        op = lst[0]
        n1 = lst[1]
        n2 = lst[2]
        if not isinstance(n1, list) and not isinstance(n2, list):
            return calc(op, n1, n2)
        
        if isinstance(n1, list):
            n1 = eval(n1)
        if isinstance(n2, list):
            n2 = eval(n2)

        return calc(op, n1, n2)
    else:
        raise Exception('Failed to evaluate "' + str(lst) + '"')


OPERATORS = ['+', '-', 'add', 'sub']
def struct(lst):
    i = 0
    while i < len(lst):
        if lst[i] in OPERATORS:
            if len(lst) == 3:
                return [lst[i], lst[i - 1], lst[i + 1]]
            temp = lst[:i - 1]
            temp.append([lst[i], lst[i - 1], lst[i + 1]])
            temp += lst[i + 2:]
            lst = temp
        else:
            i += 1
    return lst

Wszystkie lekcje w sekcji Projekt kalkulatora w Python

Poćwicz samodzielnie: Kompilator Python online