def average_precision_at_k(targets, ranked_predictions, k=None):
    """Computes AP@k given targets and ranked predictions."""
    if k:
        ranked_predictions = ranked_predictions[:k]
    score = 0.0
    hits = 0.0
    for i, pred in enumerate(ranked_predictions):
        if pred in targets and pred not in ranked_predictions[:i]:
            hits += 1.0
            score += hits / (i + 1.0)
    divisor = min(len(targets), k) if k else len(targets)
    return score / divisor