efficiently do weighted count the elements in the list

So I have a python dict like:

 1:[ "red","blue","green"]
 2: ["blue","blue","red"]..

and so on.

and then i have another python dict: score_dict = {

 pid: weight
 1: 2
 2: 20
 ...
}

So, what i want is.. in the first dict, count number of times two colors occur together. and so on. But that count be multiplied by their weight.

For example:

I want to find out how many times red an blue occured together in this list:

so for pid 1 red and blue occurs once.

 so this is (1*2) # 2 comes from the score_dict as pid1 has a weight 2

and then for second

there are two blue, red pairs I can form

so this is (1*20) + (1*20)

So total score for blue and red occuring together is 2 + 20 + 20 = 42

Also, how do i extend it to 3 colors?

Like if i have to find out "red" "blue" and " green" occuring together?

Answers


from collections import Counter

dict1 = {1:[ "red","blue","green"], 2: ["blue","blue","red"]}

weight = {1: 2, 2: 20}

score = 0

for k,v in dict1.iteritems():
    score += weight[k] * Counter(v)["red"] * Counter(v)["blue"]

Result:

>>> score
42

The last part of my code could be rewritten as generator comprehension:

score = sum(weight[k] * Counter(v)["red"] * Counter(v)["blue"] for k,v in dict1.iteritems())

Not sure I fully understood but here's an idea:'

from collections import Counter

data = {
    1: ['red','blue','green'],
    2: ['blue','blue','red'],
}

weights = {
    1: 2,
    2: 20,
}

for k, v in data.items():
    score = sum([c * weights[k] for c in Counter(v).values()])
    print "so this is: %s val = %d" % (k, score)

Need Your Help

form submission to an iframe which is in another file

javascript php jquery html iframe

As stated in the title, I'd like to submit a form and the result is shown in an iFrame that is in another file.

PgAdmin Function return type

sql function pgadmin

I am creating a stored procedure in PgAdmin to insert data into a table from different tables. I have tried the following code but I am being asked for a return type. What do I need to add?