def average_precision(sort_data):
    """ calculate average precision (AP)
    If our returned result is 1, 0, 0, 1, 1, 1
    The precision is 1/1, 0, 0, 2/4, 3/5, 4/6
    AP = (1 + 2/4 + 3/5 + 4/6)/4 = 0.69

    Args:
        sort_data: List of tuple, (score, gold_label); score is in [0, 1], glod_label is in {0, 1}

    Return:
        average precision
    """
    count_gold = 0
    sum_precision = 0

    for i, data in enumerate(sort_data):
        if data[1] == 1:
            count_gold += 1
            sum_precision += 1. * count_gold / (i + 1)

    ap = 1. * sum_precision / count_gold

    return ap