{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Quiz 3 (Batch 3)" ] }, { "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 takes, as an argument, a matrix $A$ in the form of list of lists and *returns* its cofactor matrix obtained by removing its first row and column." ] }, { "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 2\\n\")\n", "wfl.write(\"1 0 4\\n\")\n", "wfl.write(\"0 0 1\\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\n", " " ], "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, 2.0], [1.0, 0.0, 4.0], [0.0, 0.0, 1.0]]\n" ] } ], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "def cofactor11(A) :\n", " \"\"\"Given A it returns the (1,1)th cofactor.\"\"\"\n", " B = []\n", " rows = len(A)\n", " if rows <= 1 :\n", " print \"The cofactor is empty.\"\n", " retval = []\n", " else :\n", " cols = len(A[0])\n", " if cols <= 1 :\n", " print \"The cofactor is empty.\"\n", " retval = []\n", " else :\n", " c = []\n", " for i in range(1, rows) :\n", " crow = []\n", " for j in range(1, cols) :\n", " crow.append(A[i][j])\n", " c.append(crow)\n", " retval = c\n", " return retval" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 4 }, { "cell_type": "code", "collapsed": false, "input": [ "print cofactor11(read_matrix(\"test.txt\"))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[[0.0, 4.0], [0.0, 1.0]]\n" ] } ], "prompt_number": 5 } ], "metadata": {} } ] }