[Tutor] Values in matrices

Alan Gauld alan.gauld at freenet.co.uk
Sun Oct 17 16:58:09 CEST 2004

> Lets say you have a N x M matrix initially filled with zeros and
you need to
> place a value, lets say V, in  some row X and column Y where V, X,
and Y  are
> all values determined by user input and X and Y are less than or
equal to N
> and M respectively.

You can write a function (or create a class!):

def insertValueInMatrixAt(v, m, x, y):
    m[x][y] = v

> If this is possible, could this be  done many times for
> different values of V and different values of X and Y

# assume matrix created elsewhere...
while True:
   value = raw_input('Value (Hit enter to stop): ')
   if not value: break
   value = int(value)
   row = int(raw_input('Row: '))
   col = int(raw_input('Column: '))
   if row < N and col < M:
      insertValueInMatrixAt(value, matrix, row, col)

Should do something like what you want?
You could just use the assignment directly of course but I'd actually
be tempted to move the data validation inside the function too...

Alan G.

More information about the Tutor mailing list