def sort_priority_queue(pq):
    """Sort the priority queue by f-score.  Also puts node that have the
    least number of lower tokens at the front.  This ensures that the
    algorithm looks at states that are closer to the goal first.
    """

    pq = sorted(pq, key=lambda x: x[0])
    min_f = pq[0][0]  # Least f-score
    min_count = len(pq[0][1].lower)  # Least number of lower tokens
    best_i = 0  # Index of best node

    for i, j in enumerate(pq):
        if j[0] != min_f:
            break
        if len(j[1].lower) < min_count:
            min_count = len(j[1].lower)
            best_i = i

    # Swap the first node with the best node
    pq[0], pq[best_i] = pq[best_i], pq[0]
    return pq