import math


def normalised_payoff(payoff_matrix, turns):
    """
    The per-turn averaged payoff matrix and standard deviations

    Parameters
    ----------
    payoff : list
        A matrix of the form:

        [
            [[a, j], [b, k], [c, l]],
            [[d, m], [e, n], [f, o]],
            [[g, p], [h, q], [i, r]],
        ]

        i.e. one row per player, containing one element per opponent (in
        order of player index) which lists payoffs for each repetition.

    turns : integer
        The number of turns in each round robin.

    Returns
    -------
    list
        A per-turn averaged payoff matrix and its standard deviations.
    """
    repetitions = len(payoff_matrix[0][0])
    averages = []
    stddevs = []
    for res in payoff_matrix:
        averages.append([])
        stddevs.append([])
        for s in res:
            perturn = [1.0 * rep / turns for rep in s]
            avg = sum(perturn) / repetitions
            dev = math.sqrt(
                sum([(avg - pt)**2 for pt in perturn]) / repetitions)
            averages[-1].append(avg)
            stddevs[-1].append(dev)
    return averages, stddevs