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]