[Tutor] Program matx.py

DL Neil PythonList at DancesWithMice.info
Mon Dec 25 14:52:33 EST 2023


On 12/25/23 09:41, Ethan Rosenberg wrote:
> Help Desk -
> 
> Thank you for the excellent help you give to Python programmers.
> 
> Do I have to be registered to submit a question?

You have already subscribed to the list, ie registered!


> This program is supposed to insert i*j into the cells of a 2x2 matrix.  I
> receive a syntax error.

When writing to the list, please copy-paste both code and the (full) 
'stack trace' of any error messages. That way no-one has to work so hard 
to figure-out where the error occurred.


> #matx.py
> #program to add i*j to cells of 2x2 matrix
> 
> mat = [][]

In this case, it was easy-enough to see this is the error.

> for i in range(0,1):
>      for j in range(0,1):
>          mat[i][j] = i*j
> print(mat)


In Python (as distinct from add-on math/stats libraries such as NumPy) 
the basic collection data-structure is a list. A list is 
one-dimensional, ie it has length (revealed by the len() function) but 
no 'height'.

However, a list can be composed of scalar-elements and/or of collections 
- there is no requirement that every element be of the same type (as 
there may be in other languages).

Accordingly, a two-dimensional approach is to build a list of lists. 
This means that the inner for-loop should build a single row (or column 
- depending how you intend to visualise the problem - think of a larger 
and non-square matrix). Whereas the outer for-loop will build a 
collection of those inner-constructs (the matrix).

Recommendation: eschew short-forms, eg matx, i, j, mat; and use complete 
words to reduce cognitive-load (a decent IDE will save typing!).


The above shows how to solve the problem/implement the solution in 
Python. If that's your challenge, stop reading now!


To check the above solution, try: https://www.pythonpool.com/python-2d-list/

-- 
Regards =dn


More information about the Tutor mailing list