-1

I'm new to python and I got a dictionary of 'matrices' which are list of lists and I need to sum the matrices.

It works fine as 2x2 matrice, the problem is my sum_matrice function has fixed append positions and if I grow my matrice like line_numbers = 3 and column_numbers = 3 input it doesn't work.

How can I refactor the sum_matrice function going trough the dictionary list of list elements in a better way?

def create_matrice():
    dic_mat = {}

    for index in range(2):
        matrice = []
        line_numbers = int(input('\nMatrice number of lines: '))
        column_numbers = int(input('Matrice number of columns: '))
        for i in range(line_numbers):
            line = []
            for j in range(column_numbers):
                value = int(input('Value position [' + str(i) + ']' + '[' + str(j) + ']: '))
                line.append(value)
            matrice.append(line)
            dic_mat["matrice{}".format(index)] = matrice
    print('\n')
    sum_matrice(dic_mat)


def sum_matrice(a):
    c = []

    for i in range(0, len(a)):
        temp = None

        for key, value in a.items():
            if not temp:
                temp = a[key][i]
                continue

            c.append([temp[0] + a[key][i][0], temp[1] + a[key][i][1]])

    print_matrice(c)


def print_matrice(b):

    print('The sum of matrices are:')
    for i in b:
        print(i)


if __name__ == '__main__':
    create_matrice()

Inputs:

Matrice number of lines: 2
Matrice number of columns: 2
Value position [0][0]: 1
Value position [0][1]: 1
Value position [1][0]: 1
Value position [1][1]: 1

Matrice number of lines: 2
Matrice number of columns: 2
Value position [0][0]: 3
Value position [0][1]: 3
Value position [1][0]: 3
Value position [1][1]: 3

Result:

My dictionary is: {'matrice0': [[1, 1], [1, 1]], 'matrice1': [[3, 3], [3, 3]]}
The resultant sum matrice is:
[4, 4]
[4, 4]
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • 1
    Can you provide an example of what "doens't work" and what it *should* be doing? – Scott Hunter Apr 09 '21 at 18:26
  • The dictionary design is rather odd. `matrice0`, `matrice1`... should likely be a list, `matice[0]`, `matrice[1]`.... As an aside, I'd remove UI from the matrix function. There was a [question a couple weeks ago with both of these problems](https://stackoverflow.com/a/66935301/6243352)... At the very least, UI makes it hard to provide a [mcve]. Just hardcode in the failing input – ggorlen Apr 09 '21 at 18:28
  • 2
    Please allow me to point out that `numpy` can handle all of this for easily, quickly, transparently, and with easy expandability. This is what it was built for. – Tim Roberts Apr 09 '21 at 18:31

2 Answers2

1

import numpy as np

x = np.matrix(([1, 1], [1, 1]))

y = np.matrix(([3, 3], [3, 3]))

sum_XY = x + y

1

If you want to do this with regular Python lists and not numpy, you can use zip with list comprehensions:

>>> from typing import List
>>> def sum_matrices(matrices: List[List[List[int]]]) -> List[List[int]]:
...     return [[sum(cells) for cells in zip(*rows)] for rows in zip(*matrices)]
...
>>> sum_matrices([[[1, 1], [1, 1]], [[3, 3], [3, 3]]])
[[4, 4], [4, 4]]

(Typing added just for clarity -- I had a lot of trouble reading the original code trying to figure out what level of nesting each variable was at!)

You could get this from your dictionary of matrices by just calling it with the values (there's no need to iterate over the keys -- tbh this dictionary could just be a list if you aren't using the keys for anything else):

>>> d =  {'matrix0': [[1, 1], [1, 1]], 'matrix1': [[3, 3], [3, 3]]}
>>> sum_matrices(d.values())
[[4, 4], [4, 4]]

Since none of the quantities are hardcoded in sum_matrices apart from the 2-dimensionality of the matrices (that's also solveable but I don't think I can do it in one line), you can pass in an arbitrary number of matrices with arbitrary sizes, as long as they're all the same.

>>> def create_matrix() -> List[List[int]]:
...     rows = int(input("Matrix number of lines: "))
...     cols = int(input("Matrix number of columns: "))
...     return [[int(input(f"Value position[{i}][{j}]: ")) for j in range(cols)] for i in range(rows)]
...
>>> dic_mat = {f"matrix{i}": create_matrix() for i in range(int(input("Number of matrices: ")))}
Number of matrices: 3
Matrix number of lines: 3
Matrix number of columns: 3
Value position[0][0]: 1
Value position[0][1]: 1
Value position[0][2]: 1
Value position[1][0]: 1
Value position[1][1]: 1
Value position[1][2]: 1
Value position[2][0]: 1
Value position[2][1]: 1
Value position[2][2]: 1
Matrix number of lines: 3
Matrix number of columns: 3
Value position[0][0]: 1
Value position[0][1]: 1
Value position[0][2]: 1
Value position[1][0]: 1
Value position[1][1]: 1
Value position[1][2]: 1
Value position[2][0]: 1
Value position[2][1]: 1
Value position[2][2]: 1
Matrix number of lines: 3
Matrix number of columns: 3
Value position[0][0]: 1
Value position[0][1]: 1
Value position[0][2]: 1
Value position[1][0]: 1
Value position[1][1]: 1
Value position[1][2]: 1
Value position[2][0]: 1
Value position[2][1]: 1
Value position[2][2]: 1
>>> sum_matrices(dic_mat.values())
[[3, 3, 3], [3, 3, 3], [3, 3, 3]]
Samwise
  • 68,105
  • 3
  • 30
  • 44