Menu
Coddy logo textTech

מבנה בסיסי

שיעור 8 מתוך 29 בקורס פרויקט מחשבון באמצעות Python של Coddy.

השלב הבא הוא להעריך רשימה של ביטויים.

המבנה הבסיסי הוא - [op, num1, num2]

כמה דוגמאות:

  • ['+', 1, 2]  ->  calc('+', 1, 2)
  • ['*', 3, 2]  ->  calc('*', 3, 2)
  • ['/', 5.3, 0]  ->  calc('/', 5.3, 0)
challenge icon

אתגר

קל

צרו פונקציה eval שמקבלת מבנה בסיסי, רשימה כפי שתוארה למעלה, ומחזירה את תוצאת החישוב.

השתמשו בפונקציה calc שיצרתם!

נסו בעצמכם

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 + '"')

כל השיעורים ביחידה פרויקט מחשבון באמצעות Python

תרגלו בעצמכם: קומפיילר Python אונליין