{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Quiz 3 (Batch 4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1. Write a *function* which read a matrix from a file and *returns* a list of lists.\n", "1. Write another *function* which, as an argument, takes a matrix $A$ in the form of list of lists, and *returns* a Boolean `True` if the matrix is antisymmetric, and returns a `False` otherwise. Note that antisymmetric means $A^t = -A$." ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Create the file we'll be using to test the following.\n", "wfl = open(\"test.txt\", \"w\")\n", "wfl.write(\"0 1 0\\n\")\n", "wfl.write(\"-1 0 4\\n\")\n", "wfl.write(\"0 -4 0\\n\")\n", "wfl.close()" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "def read_matrix(filename) :\n", " \"\"\"Read a matrix from a file called filename. This returns a list of lists.\"\"\"\n", " fl = open(filename, \"r\")\n", " mat = []\n", " for line in fl :\n", " row = []\n", " words = line.split()\n", " for w in words :\n", " row.append(float(w))\n", " mat.append(row)\n", " fl.close()\n", " return mat" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "code", "collapsed": false, "input": [ "print read_matrix(\"test.txt\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[[0.0, 1.0, 0.0], [-1.0, 0.0, 4.0], [0.0, -4.0, 0.0]]\n" ] } ], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "def is_anti_symmetric(A) :\n", " \"\"\"Checks if a matrix is antisymmetric or not.\"\"\"\n", " # Note an antisymmetric matrix has to be a square matrix.\n", " # We assume that the empty matrix is antisymmetric.\n", " \n", " # Note if A^t[i][j] = -A[i][j], we also have A^t[j][i] = \n", " # - A[j][i].\n", " \n", " rows = len(A)\n", " if rows == 0 :\n", " retval = True\n", " else :\n", " cols = len(A[0])\n", " if rows != cols :\n", " print \"Expected a square matrix.\"\n", " retval = None\n", " else :\n", " retval = True\n", " for i in range(rows) :\n", " for j in range(i+1) :\n", " if A[i][j] != - A[j][i] :\n", " retval = False\n", " return retval" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 4 }, { "cell_type": "code", "collapsed": false, "input": [ "is_anti_symmetric(read_matrix(\"test.txt\"))" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 5, "text": [ "True" ] } ], "prompt_number": 5 } ], "metadata": {} } ] }