import math


def compute_user_similarity(d1, d2, ave_rat1, ave_rat2):
    """ Computes similarity between two users

        Input: d1, d2, (dictionary of user ratings per user) 
            ave_rat1, ave_rat2 average rating per user (float)
        Ouput: user similarity (float)
    """
    num_commun_mov = 0
    sim_numerator = 0.0
    sim_denom_user1 = 0.0
    sim_denom_user2 = 0.0
    for movie in d1:
        if movie in d2:
            num_commun_mov += 1
            a1 = d1[movie] - ave_rat1
            a2 = d2[movie] - ave_rat2
            sim_numerator += a1*a2
            sim_denom_user1 += a1**2
            sim_denom_user2 += a2**2
    if num_commun_mov == 0:
        return 0.0
    denom = math.sqrt(sim_denom_user1 * sim_denom_user2)
    if denom == 0.0:
        return 0.0
    return sim_numerator / denom