import heapq


def sort_and_trim_beams(beams: list, beam_width: int):
    """
    https://github.com/kensho-technologies/pyctcdecode/blob/v0.1.0/pyctcdecode/decoder.py#L68
    """
    return heapq.nlargest(beam_width, beams, key=lambda x: x.score_lm)