Multiplication of matrices

0

Could you give a help with Array in python ?! The exercise is as follows, a matriz_mult(n1, n2) function receives two arrays as a parameter and returns True if the arrays are multiplied in the given order and False otherwise.

The output should be something like:

n1 = [[1, 2, 3], [4, 5, 6]]
n2 = [[2, 3, 4], [5, 6, 7]]
matriz_mult(n1, n2) => False

n1 = [[1], [2], [3]]
n2 = [[1, 2, 3]]
matriz_mult(n1, n2) => True
    
asked by anonymous 01.03.2017 / 20:43

2 answers

3

Mathematically, two matrices are multiplied if the number of columns of the first one is equal to the number of lines of the second one.

Considering that your arrays are in the format:

n1 = [
  [1, 2, 3],
  [4, 5, 6]
]

Since n1 is a 2x3 array, we get the number of columns by doing:

n1_cols = len(n1[0])

And we get the number of lines of n2 by doing:

n2_rows = len(n2)

Just, then check for the values are equal:

def matriz_mult(n1, n2):
    n1_cols = len(n1[0])
    n2_rows = len(n2)
    return (n1_cols == n2_rows)

See working at Repl.it .

    
01.03.2017 / 20:59
1

In fact when you express:

n1 = [[1, 2, 3], [4, 5, 6]]
n2 = [[2, 3, 4], [5, 6, 7]]

You are only "representing" arrays, but in reality you are working with lists. In python, to work with true arrays you could use numpy. To solve what you propose I would do a function like this:

import numpy as np

def mult_array(n1, n2):
    m1 = np.array(n1)
    m2 = np.array(n2)
    try:
        dot(m1,m2)
        success = True
    except:
        success = False        
return success

Then you could call it:

print (mult_array(n1,n2))

That would result False, or

n3 = [[5,6,7,8][1,2,3],[9,8,7]]
print (mult_array(n1,n3)

That would result: True.

    
01.03.2017 / 21:52