[Tutor] creating a matrix of unknown dimensions(dimensions depend on input)

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 30 Apr 2001 18:30:34 -0700 (PDT)


On Mon, 30 Apr 2001, Julieta Rangel wrote:

> Right now I'm trying to come up with a program that given a set of elements 
> (at most 30), the computer will determine whether the set is a group or not. 

> a*a^-1 = e).  To do this I want the computer to offer the user a table set 
> up, so that the user can enter the table.  Here is where the matrix comes 
> into place.  Since I don't know how many elements the set being tested will 
> have, I need to make sure the computer asks the user how many elements the 
> set has, so that the computer can create the matrix, which must be filled 
> out by the user.  All the computer has to do know is to check the table 
> (matrix) for all the properties to determine whether the set is a group or 
> not.  Does this sound too confusing, anyway, at this point I'm maninly 

No, this makes sense; so you're making a program that makes it easy to
enter in the table that tells us how the operator works on a pair of the
group elements.  This sounds reasonable.


> interested on how to create an n x n matrix based on any given input (up to 
> 30elements)
> 
> Again, any kind of help you can offer will be truly appreciated.

There are a couple of ways to go about this.  One way that you might like
is the "dictionary" approach.  It sounds like we're trying to write
something that maps 2-tuples (2 elements) to some element.  Whenever
we're storing a "mapping", we're thinking of a Python dictionary:

###
>>> mytable = {}               ## Initially, an empty dictionary
>>> mytable[0, 0] = 42         ## Filling in an entry
>>> mytable[0, 0]              ## Looking up an entry
42
###

(For those who are curious, we're depending on Python's implicit knowledge
that by saying "0, 0", we actually mean the tuple "(0, 0)".)

This is even nicer than a two-dimensional array, because there isn't any
fixed size to the dictionary; you don't even need to preallocate the
dimensions.  Just start plugging your table values in.


Another operation that dictionaries support is telling us which entries we
filled in.  We do this by asking a dictionary what keys() it has:

###
>>> mytable.keys()
[(0, 0)]
>>> mytable[0, 1] = 3.1415
>>> mytable[1, 0] = 2.718
>>> mytable[1, 1] = 1.61
>>> mytable.keys()
[(0, 1), (0, 0), (1, 0), (1, 1)]
###

Another really useful thing we can ask a dictionary is a list of it's
items():

###
>>> mytable.items()
[((0, 1), 3.1415), ((0, 0), 42), ((1, 0), 2.718), ((1, 1), 1.61)]
###


Dictionaries are a very good data structure; there's some more information
on them here:

http://www.python.org/doc/current/tut/node7.html#SECTION007400000000000000000


Hope this helps!