{"nbformat_minor": 2, "cells": [{"execution_count": null, "cell_type": "code", "source": "import numpy as np\nfrom fractions import Fraction as frac\n\ndef Matrix(*a):\n if len(a)==1 and isinstance(a[0], np.ndarray):\n a = a[0]\n return np.array([[frac(x) for x in r] for r in a])\n\ndef Vector(*a):\n if len(a)==1 and isinstance(a[0], np.ndarray):\n a = a[0]\n return np.array([frac(x) for x in a]).reshape(-1,1)", "outputs": [], "metadata": {"collapsed": true}}, {"execution_count": null, "cell_type": "code", "source": "# \u00e5\u00b7\u00ab\u00e8\u00a1\u0093\nfrom IPython.display import Latex, SVG, display\nfrom IPython.core.interactiveshell import InteractiveShell\ndef frac_to_latex(self):\n if self._denominator == 1:\n return str(self._numerator)\n return \"\\\\frac{{{}}}{{{}}}\".format(self._numerator, self._denominator)\nfrac.__str__= frac_to_latex\nfrac._repr_latex_ = lambda x:\"$\"+frac_to_latex(x)+\"$\"\ndef ndarray_to_latex(arr): \n if len(arr.shape)==1: \n arr=arr.reshape(1,-1)\n if len(arr.shape) != 2:\n return None\n str_arr = np.vectorize(str)(arr)\n return r'\\begin{{pmatrix}}{}\\end{{pmatrix}}'.format(r'\\\\ '.join(map('&'.join, str_arr))) \nsh = InteractiveShell.instance()\nsh.display_formatter.formatters['text/latex'].type_printers[np.ndarray]=ndarray_to_latex\n\ndef matrix_dot(A,B):\n if isinstance(A, np.ndarray):\n assert len(A.shape)==2==len(B.shape)\n return np.array([(A * x).sum(axis=1) for x in B.T]).T\n assert callable(A)\n if isinstance(B, np.ndarray):\n return A(B)\n assert callable(B)\n return lambda x:A(B(x))\n\nimport ast\ndef int_to_frac(x):\n if isinstance(x, int):\n return frac(x)\n return x\nclass NumberWrapper(ast.NodeTransformer):\n def visit_BinOp(self, node):\n node = self.generic_visit(node)\n left = node.left\n right = node.right\n if isinstance(node.op, ast.MatMult):\n return ast.Call(func=ast.Name(id='matrix_dot', ctx=ast.Load()),\n args=[left, right], keywords=[])\n elif isinstance(node.op, ast.Div):\n right = ast.Call(func=ast.Name(id='int_to_frac', ctx=ast.Load()),\n args=[right], keywords=[])\n return ast.BinOp(left, node.op, right)\n\n def visit_Num(self, node):\n if isinstance(node.n, float):\n print(\"convert\",repr(node.n), )\n return ast.Call(func=ast.Name(id='frac', ctx=ast.Load()),\n args=[ast.Str(str(node.n))], keywords=[])\n return node\nsh.ast_transformers.append(NumberWrapper())\nsmiley=SVG('<\/linearGradient><\/defs><\/g><\/g><\/g><\/g><\/svg>')\ndef check_answer(result):\n if not result.all():\n print(\"Try again\")\n return result\n return smiley", "outputs": [], "metadata": {"collapsed": true}}], "nbformat": 4, "metadata": {"kernelspec": {"display_name": "Python 3", "name": "python3", "language": "python"}, "language_info": {"mimetype": "text/x-python", "nbconvert_exporter": "python", "version": "3.5.1", "name": "python", "file_extension": ".py", "pygments_lexer": "ipython3", "codemirror_mode": {"version": 3, "name": "ipython"}}}}