def only_squares(*matrices):
 if (matrices[0].rows != matrices[(-1)].cols):
  raise RuntimeError('Invalid matrices being multiplied')
 out = []
 start = 0
 for (i, M) in enumerate(matrices):
  if (M.cols == matrices[start].rows):
   out.append(MatMul(*matrices[start:(i + 1)]).doit())
   start = (i + 1)
 return out

def only_squares ( * matrices ) : if ( matrices [ 0 ] . rows != matrices [ ( - 1 ) ] . cols ) : raise RuntimeError ( 'Invalid matrices being multiplied' ) out = [ ] start = 0 for ( i , M ) in enumerate ( matrices ) : if ( M . cols == matrices [ start ] . rows ) : out . append ( MatMul ( * matrices [ start : ( i + 1 ) ] ) . doit ( ) ) start = ( i + 1 ) return out
factor matrices only if they are square .