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

memcache_get() giving segmentation fault

memcached libmemcache

I have a following simple memcache code:::::

How to print java.lang.Class object to a file?

class java

I have tried looking for a way to compile a class on the fly and I have got as for as create a compiled Class instance. However, I want to be able to create a .class file that is executable. How wo...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.