MarMan29
MarMan29

Reputation: 729

Matrix weight algorithm

I'm trying to work out how to write an algorithm to calculate the weights across different lists the most efficient way. I have a dict which contains various ids:

x["Y"]=[id1,id2,id3...]
x["X"]=[id2,id3....]
x["Z"]=[id3]
.
.

I have an associated weight for each of the elements:

w["Y"]=10
w["X"]=10
w["Z"]=5

Given an input, e.g. "Y","Z", I want to get an output of to give me:

(id1,10),(id2,10),(id3,15)

id3 gets 15 because it's in both x["Y"] and x["Z"].

Is there a way way I can do this with vector matrixes?

Upvotes: 0

Views: 133

Answers (2)

Chirag
Chirag

Reputation: 446

You can use the itertools library to group together common terms in a list:

import itertools
import operator

a = {'x': [2,3], 'y': [1,2,3], 'z': [3]}
b = {'x': 10, 'y': 10, 'z': 5}

def matrix_weight(letter1,letter2):
    final_list = []
    for i in a[letter1]:
        final_list.append((i, b[letter1]))
    for i in a[letter2]:
        final_list.append((i, b[letter2]))

    # final_list = [(1,10), (2,10), (3,10), (3,5)]
    it = itertools.groupby(final_list, operator.itemgetter(0))
    for key, subiter in it:
        yield key, sum(item[1] for item in subiter)

print list(matrix_weight('y', 'z'))

Upvotes: 2

Neo X
Neo X

Reputation: 957

I'll use the id in strings as in your example, but integer id works similarly.

def id_weights(x, w, keys):
    result = {}
    for key in keys:
        for id in x[key]:
            if id not in result:
                result[id] = 0
            result[id] += w[key]
    return [(id, result[id]) for id in sorted(result.keys())]

x = {"Y": ["id1","id2","id3"],
     "X": ["id2", "id3"],
     "Z": ["id3"]}
w = {"Y": 10, "X": 10, "Z": 5}

if __name__ == "__main__":
    keys = ["Y", "Z"]
    print id_weights(x, w, keys)

gives

[('id1', 10), ('id2', 10), ('id3', 15)]

Upvotes: 1

Related Questions