{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Quiz 3 (Batch 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1. Write a *function* which reads a matrix and *returns* the matrix in the form 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* $(A + A^t)/2$ where $A^t$ denotes the *transpose* of $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 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 symmetric(matrix) :\n", " \"\"\"It computes (A + A^t)/2 of the matrix A.\"\"\"\n", " no_rows = len(matrix)\n", " if no_rows == 0 :\n", " retval = matrix\n", " else :\n", " no_cols = len(matrix[0])\n", " if no_rows != no_cols :\n", " print \"Expected a square matrix.\"\n", " retval = None\n", " else :\n", " sym = []\n", " for i in range(no_rows) :\n", " symrow = []\n", " for j in range(no_rows) :\n", " symentry = (float(matrix[i][j] + matrix[j][i]))/2.0\n", " symrow.append(symentry)\n", " sym.append(symrow)\n", " retval = sym\n", " return retval" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 4 }, { "cell_type": "code", "collapsed": false, "input": [ "print symmetric(read_matrix(\"test.txt\"))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[[0.0, 1.0, 1.0], [1.0, 0.0, 2.0], [1.0, 2.0, 1.0]]\n" ] } ], "prompt_number": 5 } ], "metadata": {} } ] }