{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Quiz 3 (Batch 1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1. Write a *function* which reads a matrix from a file and returns a list of lists, like the matrices we saw in the class.\n", "1. Write another *function* which takes a matrix $A$ in the form of list of lists, and returns its square $A^2$." ] }, { "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 0\\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, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]\n" ] } ], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "def matsquare(matrix) :\n", " \"\"\"matrix is a matrix in a list of lists form. It checks if the matrix is a square matrix.\n", " Then it prints out the square.\"\"\"\n", " no_rows = len(matrix)\n", " if no_rows == 0 :\n", " retmat = matrix\n", " else :\n", " no_cols = len(matrix[0])\n", " if no_cols == 0 :\n", " retmat = matrix\n", " elif no_cols != no_rows :\n", " print \"To find square the number of rows should match the numer of\",\n", " print \"columns.\"\n", " retmat = None\n", " else :\n", " sq = []\n", " for i in range(no_rows) :\n", " sqrow = []\n", " for j in range(no_rows) :\n", " ij_th_entry = 0\n", " for k in range(no_rows) :\n", " ij_th_entry += matrix[i][k] * matrix[k][j]\n", " sqrow.append(ij_th_entry)\n", " sq.append(sqrow)\n", " retmat = sq\n", " return retmat" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 4 }, { "cell_type": "code", "collapsed": false, "input": [ "print matsquare(read_matrix(\"test.txt\"))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]\n" ] } ], "prompt_number": 5 } ], "metadata": {} } ] }