{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "#!pip install pyparsing" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# fourFn" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "from pyparsing import (\n", " Literal,\n", " Word,\n", " Group,\n", " Forward,\n", " alphas,\n", " alphanums,\n", " Regex,\n", " ParseException,\n", " CaselessKeyword,\n", " Suppress,\n", " delimitedList,\n", ")\n", "import math\n", "import operator" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "exprStack = []" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "def push_first(toks):\n", " exprStack.append(toks[0])" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "def push_unary_minus(toks):\n", " for t in toks:\n", " if t == \"-\":\n", " exprStack.append(\"unary -\")\n", " else:\n", " break" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "bnf = None" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "def BNF():\n", " \"\"\"\n", " expop :: '^'\n", " multop :: '*' | '/'\n", " addop :: '+' | '-'\n", " integer :: ['+' | '-'] '0'..'9'+\n", " atom :: PI | E | real | fn '(' expr ')' | '(' expr ')'\n", " factor :: atom [ expop factor ]*\n", " term :: factor [ multop factor ]*\n", " expr :: term [ addop term ]*\n", " \"\"\"\n", " global bnf\n", " if not bnf:\n", " # use CaselessKeyword for e and pi, to avoid accidentally matching\n", " # functions that start with 'e' or 'pi' (such as 'exp'); Keyword\n", " # and CaselessKeyword only match whole words\n", " e = CaselessKeyword(\"E\")\n", " pi = CaselessKeyword(\"PI\")\n", " # fnumber = Combine(Word(\"+-\"+nums, nums) +\n", " # Optional(\".\" + Optional(Word(nums))) +\n", " # Optional(e + Word(\"+-\"+nums, nums)))\n", " # or use provided pyparsing_common.number, but convert back to str:\n", " # fnumber = ppc.number().addParseAction(lambda t: str(t[0]))\n", " fnumber = Regex(r\"[+-]?\\d+(?:\\.\\d*)?(?:[eE][+-]?\\d+)?\")\n", " ident = Word(alphas, alphanums + \"_$\")\n", "\n", " plus, minus, mult, div = map(Literal, \"+-*/\")\n", " lpar, rpar = map(Suppress, \"()\")\n", " addop = plus | minus\n", " multop = mult | div\n", " expop = Literal(\"^\")\n", "\n", " expr = Forward()\n", " expr_list = delimitedList(Group(expr))\n", " # add parse action that replaces the function identifier with a (name, number of args) tuple\n", " def insert_fn_argcount_tuple(t):\n", " fn = t.pop(0)\n", " num_args = len(t[0])\n", " t.insert(0, (fn, num_args))\n", "\n", " fn_call = (ident + lpar - Group(expr_list) + rpar).setParseAction(\n", " insert_fn_argcount_tuple\n", " )\n", " atom = (\n", " addop[...]\n", " + (\n", " (fn_call | pi | e | fnumber | ident).setParseAction(push_first)\n", " | Group(lpar + expr + rpar)\n", " )\n", " ).setParseAction(push_unary_minus)\n", "\n", " # by defining exponentiation as \"atom [ ^ factor ]...\" instead of \"atom [ ^ atom ]...\", we get right-to-left\n", " # exponents, instead of left-to-right that is, 2^3^2 = 2^(3^2), not (2^3)^2.\n", " factor = Forward()\n", " factor <<= atom + (expop + factor).setParseAction(push_first)[...]\n", " term = factor + (multop + factor).setParseAction(push_first)[...]\n", " expr <<= term + (addop + term).setParseAction(push_first)[...]\n", " bnf = expr\n", " return bnf" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "# map operator symbols to corresponding arithmetic operations\n", "epsilon = 1e-12\n", "opn = {\n", " \"+\": operator.add,\n", " \"-\": operator.sub,\n", " \"*\": operator.mul,\n", " \"/\": operator.truediv,\n", " \"^\": operator.pow,\n", "}\n", "\n", "fn = {\n", " \"sin\": math.sin,\n", " \"cos\": math.cos,\n", " \"tan\": math.tan,\n", " \"exp\": math.exp,\n", " \"abs\": abs,\n", " \"trunc\": int,\n", " \"round\": round,\n", " \"sgn\": lambda a: -1 if a < -epsilon else 1 if a > epsilon else 0,\n", " # functionsl with multiple arguments\n", " \"multiply\": lambda a, b: a * b,\n", " \"hypot\": math.hypot,\n", " # functions with a variable number of arguments\n", " \"all\": lambda *a: all(a),\n", " \"Circle\": lambda x,y,r: f\"center=({x},{y}),radius={r}\"\n", "}" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "def evaluate_stack(s):\n", " op, num_args = s.pop(), 0\n", " if isinstance(op, tuple):\n", " op, num_args = op\n", " if op == \"unary -\":\n", " return -evaluate_stack(s)\n", " if op in \"+-*/^\":\n", " # note: operands are pushed onto the stack in reverse order\n", " op2 = evaluate_stack(s)\n", " op1 = evaluate_stack(s)\n", " return opn[op](op1, op2)\n", " elif op == \"PI\":\n", " return math.pi # 3.1415926535\n", " elif op == \"E\":\n", " return math.e # 2.718281828\n", " elif op in fn:\n", " # note: args are pushed onto the stack in reverse order\n", " args = reversed([evaluate_stack(s) for _ in range(num_args)])\n", " return fn[op](*args)\n", " elif op[0].isalpha():\n", " raise Exception(\"invalid identifier '%s'\" % op)\n", " else:\n", " # try to evaluate as int first, then as float if int fails\n", " try:\n", " return int(op)\n", " except ValueError:\n", " return float(op)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "def test(s, expected):\n", " exprStack[:] = []\n", " try:\n", " results = BNF().parseString(s, parseAll=True)\n", " val = evaluate_stack(exprStack[:])\n", " except ParseException as pe:\n", " print(s, \"failed parse:\", str(pe))\n", " except Exception as e:\n", " print(s, \"failed eval:\", str(e), exprStack)\n", " else:\n", " if val == expected:\n", " print(s, \"=\", val, results, \"=>\", exprStack)\n", " else:\n", " print(s + \"!!!\", val, \"!=\", expected, results, \"=>\", exprStack)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9 = 9 ['9'] => ['9']\n", "-9 = -9 ['-', '9'] => ['9', 'unary -']\n", "--9 = 9 ['-', '-', '9'] => ['9', 'unary -', 'unary -']\n", "-E = -2.718281828459045 ['-', 'E'] => ['E', 'unary -']\n", "9 + 3 + 6 = 18 ['9', '+', '3', '+', '6'] => ['9', '3', '+', '6', '+']\n", "9 + 3 / 11 = 9.272727272727273 ['9', '+', '3', '/', '11'] => ['9', '3', '11', '/', '+']\n", "(9 + 3) = 12 [['9', '+', '3']] => ['9', '3', '+']\n", "(9+3) / 11 = 1.0909090909090908 [['9', '+', '3'], '/', '11'] => ['9', '3', '+', '11', '/']\n", "9 - 12 - 6 = -9 ['9', '-', '12', '-', '6'] => ['9', '12', '-', '6', '-']\n", "9 - (12 - 6) = 3 ['9', '-', ['12', '-', '6']] => ['9', '12', '6', '-', '-']\n", "2*3.14159 = 6.28318 ['2', '*', '3.14159'] => ['2', '3.14159', '*']\n", "3.1415926535*3.1415926535 / 10 = 0.9869604400525172 ['3.1415926535', '*', '3.1415926535', '/', '10'] => ['3.1415926535', '3.1415926535', '*', '10', '/']\n", "PI * PI / 10 = 0.9869604401089358 ['PI', '*', 'PI', '/', '10'] => ['PI', 'PI', '*', '10', '/']\n", "PI*PI/10 = 0.9869604401089358 ['PI', '*', 'PI', '/', '10'] => ['PI', 'PI', '*', '10', '/']\n", "PI^2 = 9.869604401089358 ['PI', '^', '2'] => ['PI', '2', '^']\n", "round(PI^2) = 10 [('round', 1), [['PI', '^', '2']]] => ['PI', '2', '^', ('round', 1)]\n", "6.02E23 * 8.048 = 4.844896e+24 ['6.02E23', '*', '8.048'] => ['6.02E23', '8.048', '*']\n", "e / 3 = 0.9060939428196817 ['E', '/', '3'] => ['E', '3', '/']\n", "sin(PI/2) = 1.0 [('sin', 1), [['PI', '/', '2']]] => ['PI', '2', '/', ('sin', 1)]\n", "10+sin(PI/4)^2 = 10.5 ['10', '+', ('sin', 1), [['PI', '/', '4']], '^', '2'] => ['10', 'PI', '4', '/', ('sin', 1), '2', '^', '+']\n", "trunc(E) = 2 [('trunc', 1), [['E']]] => ['E', ('trunc', 1)]\n", "trunc(-E) = -2 [('trunc', 1), [['-', 'E']]] => ['E', 'unary -', ('trunc', 1)]\n", "round(E) = 3 [('round', 1), [['E']]] => ['E', ('round', 1)]\n", "round(-E) = -3 [('round', 1), [['-', 'E']]] => ['E', 'unary -', ('round', 1)]\n", "E^PI = 23.140692632779263 ['E', '^', 'PI'] => ['E', 'PI', '^']\n", "exp(0) = 1.0 [('exp', 1), [['0']]] => ['0', ('exp', 1)]\n", "exp(1) = 2.718281828459045 [('exp', 1), [['1']]] => ['1', ('exp', 1)]\n", "2^3^2 = 512 ['2', '^', '3', '^', '2'] => ['2', '3', '2', '^', '^']\n", "(2^3)^2 = 64 [['2', '^', '3'], '^', '2'] => ['2', '3', '^', '2', '^']\n", "2^3+2 = 10 ['2', '^', '3', '+', '2'] => ['2', '3', '^', '2', '+']\n", "2^3+5 = 13 ['2', '^', '3', '+', '5'] => ['2', '3', '^', '5', '+']\n", "2^9 = 512 ['2', '^', '9'] => ['2', '9', '^']\n", "sgn(-2) = -1 [('sgn', 1), [['-', '2']]] => ['2', 'unary -', ('sgn', 1)]\n", "sgn(0) = 0 [('sgn', 1), [['0']]] => ['0', ('sgn', 1)]\n", "sgn(0.1) = 1 [('sgn', 1), [['0.1']]] => ['0.1', ('sgn', 1)]\n", "foo(0.1) failed eval: invalid identifier 'foo' ['0.1', ('foo', 1)]\n", "round(E, 3) = 2.718 [('round', 2), [['E'], ['3']]] => ['E', '3', ('round', 2)]\n", "round(PI^2, 3) = 9.87 [('round', 2), [['PI', '^', '2'], ['3']]] => ['PI', '2', '^', '3', ('round', 2)]\n", "sgn(cos(PI/4)) = 1 [('sgn', 1), [[('cos', 1), [['PI', '/', '4']]]]] => ['PI', '4', '/', ('cos', 1), ('sgn', 1)]\n", "sgn(cos(PI/2)) = 0 [('sgn', 1), [[('cos', 1), [['PI', '/', '2']]]]] => ['PI', '2', '/', ('cos', 1), ('sgn', 1)]\n", "sgn(cos(PI*3/4)) = -1 [('sgn', 1), [[('cos', 1), [['PI', '*', '3', '/', '4']]]]] => ['PI', '3', '*', '4', '/', ('cos', 1), ('sgn', 1)]\n", "+(sgn(cos(PI/4))) = 1 ['+', [('sgn', 1), [[('cos', 1), [['PI', '/', '4']]]]]] => ['PI', '4', '/', ('cos', 1), ('sgn', 1)]\n", "-(sgn(cos(PI/4))) = -1 ['-', [('sgn', 1), [[('cos', 1), [['PI', '/', '4']]]]]] => ['PI', '4', '/', ('cos', 1), ('sgn', 1), 'unary -']\n", "hypot(3, 4) = 5.0 [('hypot', 2), [['3'], ['4']]] => ['3', '4', ('hypot', 2)]\n", "multiply(3, 7) = 21 [('multiply', 2), [['3'], ['7']]] => ['3', '7', ('multiply', 2)]\n", "all(1,1,1) = True [('all', 3), [['1'], ['1'], ['1']]] => ['1', '1', '1', ('all', 3)]\n", "all(1,1,1,1,1,0) = False [('all', 6), [['1'], ['1'], ['1'], ['1'], ['1'], ['0']]] => ['1', '1', '1', '1', '1', '0', ('all', 6)]\n" ] } ], "source": [ "test(\"9\", 9)\n", "test(\"-9\", -9)\n", "test(\"--9\", 9)\n", "test(\"-E\", -math.e)\n", "test(\"9 + 3 + 6\", 9 + 3 + 6)\n", "test(\"9 + 3 / 11\", 9 + 3.0 / 11)\n", "test(\"(9 + 3)\", (9 + 3))\n", "test(\"(9+3) / 11\", (9 + 3.0) / 11)\n", "test(\"9 - 12 - 6\", 9 - 12 - 6)\n", "test(\"9 - (12 - 6)\", 9 - (12 - 6))\n", "test(\"2*3.14159\", 2 * 3.14159)\n", "test(\"3.1415926535*3.1415926535 / 10\", 3.1415926535 * 3.1415926535 / 10)\n", "test(\"PI * PI / 10\", math.pi * math.pi / 10)\n", "test(\"PI*PI/10\", math.pi * math.pi / 10)\n", "test(\"PI^2\", math.pi ** 2)\n", "test(\"round(PI^2)\", round(math.pi ** 2))\n", "test(\"6.02E23 * 8.048\", 6.02e23 * 8.048)\n", "test(\"e / 3\", math.e / 3)\n", "test(\"sin(PI/2)\", math.sin(math.pi / 2))\n", "test(\"10+sin(PI/4)^2\", 10 + math.sin(math.pi / 4) ** 2)\n", "test(\"trunc(E)\", int(math.e))\n", "test(\"trunc(-E)\", int(-math.e))\n", "test(\"round(E)\", round(math.e))\n", "test(\"round(-E)\", round(-math.e))\n", "test(\"E^PI\", math.e ** math.pi)\n", "test(\"exp(0)\", 1)\n", "test(\"exp(1)\", math.e)\n", "test(\"2^3^2\", 2 ** 3 ** 2)\n", "test(\"(2^3)^2\", (2 ** 3) ** 2)\n", "test(\"2^3+2\", 2 ** 3 + 2)\n", "test(\"2^3+5\", 2 ** 3 + 5)\n", "test(\"2^9\", 2 ** 9)\n", "test(\"sgn(-2)\", -1)\n", "test(\"sgn(0)\", 0)\n", "test(\"sgn(0.1)\", 1)\n", "test(\"foo(0.1)\", None)\n", "test(\"round(E, 3)\", round(math.e, 3))\n", "test(\"round(PI^2, 3)\", round(math.pi ** 2, 3))\n", "test(\"sgn(cos(PI/4))\", 1)\n", "test(\"sgn(cos(PI/2))\", 0)\n", "test(\"sgn(cos(PI*3/4))\", -1)\n", "test(\"+(sgn(cos(PI/4)))\", 1)\n", "test(\"-(sgn(cos(PI/4)))\", -1)\n", "test(\"hypot(3, 4)\", 5)\n", "test(\"multiply(3, 7)\", 21)\n", "test(\"all(1,1,1)\", True)\n", "test(\"all(1,1,1,1,1,0)\", False)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Circle(0,0,5) = center=(0,0),radius=5 [('Circle', 3), [['0'], ['0'], ['5']]] => ['0', '0', '5', ('Circle', 3)]\n" ] } ], "source": [ "test(\"Circle(0,0,5)\", \"center=(0,0),radius=5\")" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Circle(0,1,3)!!! center=(0,1),radius=3 != center=(0,0),radius=5 [('Circle', 3), [['0'], ['1'], ['3']]] => ['0', '1', '3', ('Circle', 3)]\n" ] } ], "source": [ "test(\"Circle(0,1,3)\", \"center=(0,0),radius=5\")" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "A=3\n", "N=4" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "N*A/5 failed eval: invalid identifier 'A' ['N', 'A', '*', '5', '/']\n" ] } ], "source": [ "test(\"N*A/5\",12/5)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.5" } }, "nbformat": 4, "nbformat_minor": 4 }