def trim(set, height, level):
    """Trim the given set to the given level and add all nodes of that level.

    Removes all nodes in the given set that are above the given level, and add
    all nodes of the given level. In cases where the set contains a lot of
    duplicate nodes in upper levels, this can reduce the overall size of the
    set.

    This optimiszation is applied in SPHINCS at level 10 in a binary tree of
    height 16.

    Keyword arguments:
    set -- the set of nodes, where each node is represented as a tuple
           consisting of the node's layer and the node's index within this layer
    height -- the height of the binary hash tree
    level -- the level at which to trim the set

    """
    cut = height - level
    if cut > 0:
        # Remove all elements that are at or higher than the given level
        reduced_set = [(i, j) for (i, j) in set if i < level]
        # Add all elements on that level
        reduced_set += [(level, i) for i in range(0, 2**cut)]
        return reduced_set
    else:
        return set