def compute_average_precison_for_a_query(recommended_items, actual_items_seen):
    """
    recommended_items: list of n recommended item for a test user
    actual_items_seen: list of actual items that the user has viewed
    return: average precision for a query (user/item)
    """
    num_rel_items = len(actual_items_seen)
    sum_ave_p = 0
    for i in range(0, len(recommended_items)):
        if recommended_items[i] in set(actual_items_seen):
            # item i is relevant
            p_at_i = len(set(recommended_items[:i+1]) & set(actual_items_seen))/(i+1)
            sum_ave_p += p_at_i
    return sum_ave_p/(num_rel_items)