import math


def similarity(di, dj):
    """Cos similarity.
    usage:
     >>> a = {0:2, 1:1, 2:1}
     >>> b = {0:1, 2:1}
     >>> print round(similarity(a, b), 5)
     0.86603
    """
    inds = set(di.keys()) & set(dj.keys()) 
    s = len(set(di.keys()) & set(dj.keys())) 
    if s == 0:
        return 0.0

    up = sum([di[k] * dj[k] for k in inds]) 
    m = sum([di[k] ** 2 for k in di]) * sum([dj[k] ** 2 for k in dj]) 
    #alpha = min(s / 6.0, 1.0)
    alpha = 1.0
    return float(up) / math.sqrt(m) * alpha