Reputation: 3443
I have a function that returns a comparison matrix from a given list:
def compare(a, b):
if b > a:
return 1
elif b < a:
return -1
else:
return 0
def matrix(data):
return [[compare(a, b) for b in data] for a in data]
I use this function in this way:
>>> matrix([0, 4, 5, 2, 1, 3])
[[0, 1, 1, 1, 1, 1],
[-1, 0, 1, -1, -1, -1],
[-1, -1, 0, -1, -1, -1],
[-1, 1, 1, 0, -1, 1],
[-1, 1, 1, 1, 0, 1],
[-1, 1, 1, -1, -1, 0]]
I need a function to return data from a given matrix, like the code below, but I don't know how to do.
>>> data_from_matrix([[0, 1, 1, 1, 1, 1],
[-1, 0, 1, -1, -1, -1],
[-1, -1, 0, -1, -1, -1],
[-1, 1, 1, 0, -1, 1],
[-1, 1, 1, 1, 0, 1],
[-1, 1, 1, -1, -1, 0]])
[0, 4, 5, 2, 1, 3]
Upvotes: 1
Views: 135
Reputation: 602425
A simple hack would be to compute the sums over every row of the matrix:
def data_from_matrix(m):
return [(len(m) - 1 - sum(row)) // 2 for row in m]
This assumes that the matrix actually defines a total ordering and does not check the consistency of the matrix. Another assumption is that the set the total ordering is supposed to be defined on is range(len(m))
.
Example:
>>> data_from_matrix([[ 0, 1, 1, 1, 1, 1],
... [-1, 0, 1, -1, -1, -1],
... [-1, -1, 0, -1, -1, -1],
... [-1, 1, 1, 0, -1, 1],
... [-1, 1, 1, 1, 0, 1],
... [-1, 1, 1, -1, -1, 0]])
[0, 4, 5, 2, 1, 3]
Upvotes: 3