Tuesday, February 11, 2014

Given a matrix, you need to create another matrix such that the value (i,j) is either -1, 0 or 1.

__author__ = 'nitin'

"""Given a matrix, you need to create another matrix such that the value (i,j) is either -1, 0 or 1.
1 - if multiplication of all values in ith row and jth column is greater than 0.
-1 - if multiplication of all values in ith row and jth column is less than 0.
0 - if multiplication of all the values in ith row and jth column is 0.

e.g.
1 2 3 1
1 0 -1 2
-1 1 1 1

o/p
-1 0 -1 1
0 0 0 0
1 0 1 -1 """


matrix=[[1, 2, 3, 1], [1, 0, -1, 2], [-1, 1, 1, 1]]

def column_multiplication(rows,col_elem):
    col_result=1
    while rows>0:
        col_result=col_result * matrix[rows-1][col_elem]
        rows=rows-1
    return col_result

def rows_multiplication(col,row_elem):
    rows_result=1
    while col>0:
        rows_result=rows_result * matrix[row_elem][col-1]
        col=col-1
    return rows_result

def main():
    print "\nGiven Matrix : ", matrix, "\n"
    rows=len(matrix)
    col=len(matrix[0])
    new_matrix=[ [ None for i in range(col) ] for j in range(rows) ]
    for row_elem in range(rows):
        for col_elem in range(col):
            col_result=column_multiplication(rows,col_elem)
            rows_result=rows_multiplication(col,row_elem)
            if col_result * rows_result == 0:
                new_matrix[row_elem][col_elem]= 0
            elif col_result * rows_result > 0:
                new_matrix[row_elem][col_elem]= 1
            elif col_result * rows_result < 0:
                new_matrix[row_elem][col_elem]= -1
    print "Result Matrix : ", new_matrix

if __name__=="__main__":
    main()

No comments:

My Profile

My photo
can be reached at 09916017317