import math


def actual_dcg(result, query, author_rankings, n=10):
    """
    Calculate the actual DCG for a query at N.
    The premise of DCG is that highly relevant documents appearing lower
    in a search result list should be penalized as the graded relevance value is reduced
    logarithmically proportional to the position of the result. This function calculates
    what the actual DCG is for a given query.

    :param query: The search query.
    :param result: The result produced by the retrieval system.
    :param author_rankings: A pre-calculated dictionary of authors rankings with relevance labels (available on request).
    :param n: The position through which to calculate the DCG.
    :return dcg: The actual DCG through N for a given query.
    """
    sortd = sorted(result.items(), key=lambda item: item[1]['rank'])[:n]
    labels = []
    for author_id, v in sortd:
        if query.lower() in author_rankings[author_id]:
            label = author_rankings[author_id][query.lower()]
            labels.append(label)
        else:
            labels.append(0)

    dcg = sum([l / math.log((i + 1) + 1) for i, l in enumerate(labels)])

    return dcg