Ticket #14498: trac_14998-more-edits-dg.patch

File trac_14998-more-edits-dg.patch, 84.5 KB (added by darij, 6 years ago)

new review patch

  • sage/combinat/abstract_tree.py

    # HG changeset patch
    # User darij grinberg <darijgrinberg@gmail.com>
    # Date 1384130170 28800
    # Node ID d1916f255d1147726cbfea1082543d454c6708f3
    # Parent  10f4f08eea2cf27bf045363c7bf6a4fd00b13377
    trac #14498: Darij's review patch, to be applied ATOP of trac_14498-algorithms_trees-rebased.patch and trac_14498-tree-imps-dg-rebased.patch
    
    diff --git a/sage/combinat/abstract_tree.py b/sage/combinat/abstract_tree.py
    a b incoherent with the data structure. 
    6666from sage.structure.list_clone import ClonableArray
    6767from sage.rings.integer import Integer
    6868from sage.misc.misc_c import prod
    69 ###############################################################################
    70 # # use to load tikz in the preamble (one for *view* and one for *notebook*)
    71 from sage.misc.latex import latex
    72 latex.add_package_to_preamble_if_available("tikz")
    73 latex.add_to_mathjax_avoid_list("tikz")
    74 ###############################################################################
    7569
    7670
    7771# Unfortunately Cython forbids multiple inheritance. Therefore, we do not
    78 # inherits from SageObject to be able to inherits from Element or a subclass
     72# inherit from SageObject to be able to inherit from Element or a subclass
    7973# of it later.
    8074class AbstractTree(object):
    8175    """
    82     Abstract Tree
     76    Abstract Tree.
    8377
    8478    There is no data structure defined here, as this class is meant to be
    8579    extended, not instantiated.
    class AbstractTree(object): 
    9791      <AbstractTree.canonical_labelling>` method
    9892      should return the same value for trees that are considered equal (see the
    9993      "canonical labellings" section in the documentation of the
    100       :class:`AbstractTree <sage.combinat.abstract_tree.AbstractTree>` module).
     94      :class:`AbstractTree <sage.combinat.abstract_tree.AbstractTree>` class).
    10195
    10296    * For a tree ``T`` the call ``T.parent().labelled_trees()`` should return
    10397      a parent for labelled trees of the same kind: for example,
    class AbstractTree(object): 
    118112        The depth-first pre-order traversal iterator.
    119113
    120114        This method iters each node following the depth-first pre-order
    121         traversal algorithm (recursive implementation).
     115        traversal algorithm (recursive implementation). The algorithm
     116        is::
     117
     118            yield the root (in the case of binary trees, if it is not
     119                a node);
     120            then explore each subtree (by the algorithm) from the
     121                leftmost one to the rightmost one.
     122
     123        EXAMPLES:
    122124
    123125        For example, on the following binary tree `b`::
    124126
    class AbstractTree(object): 
    130132            |        / \      |
    131133            |       4   6     |
    132134
    133         the ``depth-first pre-order traversal algorithm`` explores `b` in the
    134         following order of nodes: `3,1,2,7,5,4,6,8`.
    135 
    136         The algorithm is::
    137 
    138             manipulate the root,
    139             then explore each subtree (by the algorithm).
     135        (only the nodes shown), the depth-first pre-order traversal
     136        algorithm explores `b` in the following order of nodes:
     137        `3,1,2,7,5,4,6,8`.
    140138
    141139        Another example::
    142140
    class AbstractTree(object): 
    148146            |  / /        |
    149147            | 4 5         |
    150148
    151         The algorithm explores this tree in the following order:
    152         `1,2,3,4,5,6,7,8,9,10`.
     149        The algorithm explores this labelled tree in the following
     150        order: `1,2,3,4,5,6,7,8,9,10`.
    153151
    154152        TESTS::
    155153
    class AbstractTree(object): 
    164162            [       4   6     ]
    165163            sage: [n.label() for n in b.pre_order_traversal_iter()]
    166164            [3, 1, 2, 7, 5, 4, 6, 8]
     165
    167166            sage: t = OrderedTree([[[[],[]]],[[]],[[],[]]]).canonical_labelling()
    168167            sage: ascii_art([t])
    169168            [     __1____   ]
    class AbstractTree(object): 
    175174            [ 4 5           ]
    176175            sage: [n.label() for n in t.pre_order_traversal_iter()]
    177176            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
     177
     178            sage: [n for n in BinaryTree(None).pre_order_traversal_iter()]
     179            []
     180
     181        The following test checks that things don't go wrong if some among
     182        the descendants of the tree are equal or even identical::
     183
     184            sage: u = BinaryTree(None)
     185            sage: v = BinaryTree([u, u])
     186            sage: w = BinaryTree([v, v])
     187            sage: t = BinaryTree([w, w])
     188            sage: t.node_number()
     189            7
     190            sage: l = [1 for i in t.pre_order_traversal_iter()]
     191            sage: len(l)
     192            7
    178193        """
    179194        if self.is_empty():
    180195            return
    class AbstractTree(object): 
    191206
    192207    def iterative_pre_order_traversal(self, action=None):
    193208        r"""
    194         The depth-first pre-order traversal algorithm (iterative
    195         implementation).
     209        Run the depth-first pre-order traversal algorithm (iterative
     210        implementation) and subject every node encountered
     211        to some procedure ``action``. The algorithm is::
     212
     213            manipulate the root with function `action` (in the case
     214                of a binary tree, only if the root is not a leaf);
     215            then explore each subtree (by the algorithm) from the
     216                leftmost one to the rightmost one.
    196217
    197218        INPUT:
    198219
    199         - ``action`` -- (optional) a function which takes a node in input
    200           and does something during the exploration
     220        - ``action`` -- (optional) a function which takes a node as
     221          input, and does something during the exploration
     222
     223        OUTPUT:
     224
     225        ``None``. (This is *not* an iterator.)
    201226
    202227        .. SEEALSO::
    203228
    class AbstractTree(object): 
    213238            sage: b.iterative_pre_order_traversal(lambda node: l.append(node.label()))
    214239            sage: l
    215240            [3, 1, 2, 7, 5, 4, 6, 8]
     241
    216242            sage: t = OrderedTree([[[[],[]]],[[]],[[],[]]]).canonical_labelling()
    217243            sage: t
    218244            1[2[3[4[], 5[]]], 6[7[]], 8[9[], 10[]]]
    class AbstractTree(object): 
    221247            sage: l
    222248            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    223249            sage: l = []
     250
    224251            sage: BinaryTree().canonical_labelling().\
    225252            ....:     pre_order_traversal(lambda node: l.append(node.label()))
    226253            sage: l
    class AbstractTree(object): 
    229256            ....:     iterative_pre_order_traversal(lambda node: l.append(node.label()))
    230257            sage: l
    231258            [1]
     259
     260        The following test checks that things don't go wrong if some among
     261        the descendants of the tree are equal or even identical::
     262
     263            sage: u = BinaryTree(None)
     264            sage: v = BinaryTree([u, u])
     265            sage: w = BinaryTree([v, v])
     266            sage: t = BinaryTree([w, w])
     267            sage: t.node_number()
     268            7
     269            sage: l = []
     270            sage: t.iterative_pre_order_traversal(lambda node: l.append(1))
     271            sage: len(l)
     272            7
    232273        """
    233274        if self.is_empty():
    234275            return
    class AbstractTree(object): 
    246287
    247288    def pre_order_traversal(self, action=None):
    248289        r"""
    249         The depth-first pre-order traversal algorithm (recursive
    250         implementation).
     290        Run the depth-first pre-order traversal algorithm (recursive
     291        implementation) and subject every node encountered
     292        to some procedure ``action``. The algorithm is::
     293
     294            manipulate the root with function `action` (in the case
     295                of a binary tree, only if the root is not a leaf);
     296            then explore each subtree (by the algorithm) from the
     297                leftmost one to the rightmost one.
    251298
    252299        INPUT:
    253300
    254         - ``action`` -- (optional) a function which takes a node in input
    255           and does something during the exploration
     301        - ``action`` -- (optional) a function which takes a node as
     302          input, and does something during the exploration
    256303
    257         For example on the following binary tree `b`::
     304        OUTPUT:
     305
     306        ``None``. (This is *not* an iterator.)
     307
     308        EXAMPLES:
     309
     310        For example, on the following binary tree `b`::
    258311
    259312            |   ___3____      |
    260313            |  /        \     |
    class AbstractTree(object): 
    264317            |        / \      |
    265318            |       4   6     |
    266319
    267         the ``depth-first pre-order traversal algorithm`` explores `b` in the
    268         following order of nodes `3,1,2,7,5,4,6,8`.
    269 
    270         The algorithm is::
    271 
    272             manipulate the root with function `action`,
    273             then explore each subtrees (by the algorithm)
     320        the depth-first pre-order traversal algorithm explores `b` in the
     321        following order of nodes: `3,1,2,7,5,4,6,8`.
    274322
    275323        Another example::
    276324
    class AbstractTree(object): 
    303351            sage: b.iterative_pre_order_traversal(lambda node: li.append(node.label()))
    304352            sage: l == li
    305353            True
     354
    306355            sage: t = OrderedTree([[[[],[]]],[[]],[[],[]]]).canonical_labelling()
    307356            sage: t
    308357            1[2[3[4[], 5[]]], 6[7[]], 8[9[], 10[]]]
    class AbstractTree(object): 
    314363            sage: t.iterative_pre_order_traversal(lambda node: li.append(node.label()))
    315364            sage: l == li
    316365            True
     366
    317367            sage: l = []
    318368            sage: BinaryTree().canonical_labelling().\
    319369            ....:     pre_order_traversal(lambda node: l.append(node.label()))
    class AbstractTree(object): 
    323373            ....:     pre_order_traversal(lambda node: l.append(node.label()))
    324374            sage: l
    325375            [1]
     376
     377        The following test checks that things don't go wrong if some among
     378        the descendants of the tree are equal or even identical::
     379
     380            sage: u = BinaryTree(None)
     381            sage: v = BinaryTree([u, u])
     382            sage: w = BinaryTree([v, v])
     383            sage: t = BinaryTree([w, w])
     384            sage: t.node_number()
     385            7
     386            sage: l = []
     387            sage: t.pre_order_traversal(lambda node: l.append(1))
     388            sage: len(l)
     389            7
    326390        """
    327391        if action is None:
    328392            action = lambda x: None
    class AbstractTree(object): 
    334398        The depth-first post-order traversal iterator.
    335399
    336400        This method iters each node following the depth-first post-order
    337         traversal algorithm (recursive implementation).
     401        traversal algorithm (recursive implementation). The algorithm
     402        is::
     403
     404            explore each subtree (by the algorithm) from the
     405                leftmost one to the rightmost one;
     406            then yield the root (in the case of binary trees, only if
     407                it is not a node).
     408
     409        EXAMPLES:
    338410
    339411        For example on the following binary tree `b`::
    340412
    class AbstractTree(object): 
    346418            |        / \      |
    347419            |       4   6     |
    348420
    349         the ``depth-first post-order traversal algorithm`` explores `b` in the
    350         following order of nodes `2,1,4,6,5,8,7,3`.
     421        (only the nodes are shown), the depth-first post-order traversal
     422        algorithm explores `b` in the following order of nodes:
     423        `2,1,4,6,5,8,7,3`.
    351424
    352         The algorithm is::
    353 
    354             explore each subtrees (by the algorithm)
    355             then manipulate the root with function `action`
    356 
    357         Another example::
     425        For another example, consider the labelled tree::
    358426
    359427            |     __1____ |
    360428            |    /  /   / |
    class AbstractTree(object): 
    380448            [       4   6     ]
    381449            sage: [node.label() for node in b.post_order_traversal_iter()]
    382450            [2, 1, 4, 6, 5, 8, 7, 3]
     451
    383452            sage: t = OrderedTree([[[[],[]]],[[]],[[],[]]]).canonical_labelling()
    384453            sage: ascii_art([t])
    385454            [     __1____   ]
    class AbstractTree(object): 
    391460            [ 4 5           ]
    392461            sage: [node.label() for node in t.post_order_traversal_iter()]
    393462            [4, 5, 3, 2, 7, 6, 9, 10, 8, 1]
     463
    394464            sage: [node.label() for node in BinaryTree().canonical_labelling().\
    395465            ....:     post_order_traversal_iter()]
    396466            []
    397467            sage: [node.label() for node in OrderedTree([]).\
    398468            ....:     canonical_labelling().post_order_traversal_iter()]
    399469            [1]
     470
     471        The following test checks that things don't go wrong if some among
     472        the descendants of the tree are equal or even identical::
     473
     474            sage: u = BinaryTree(None)
     475            sage: v = BinaryTree([u, u])
     476            sage: w = BinaryTree([v, v])
     477            sage: t = BinaryTree([w, w])
     478            sage: t.node_number()
     479            7
     480            sage: l = [1 for i in t.post_order_traversal_iter()]
     481            sage: len(l)
     482            7
    400483        """
    401484        if self.is_empty():
    402485            return
    class AbstractTree(object): 
    413496
    414497    def post_order_traversal(self, action=None):
    415498        r"""
    416         The depth-first post-order traversal algorithm (recursive
    417         implementation).
     499        Run the depth-first post-order traversal algorithm (recursive
     500        implementation) and subject every node encountered
     501        to some procedure ``action``. The algorithm is::
     502
     503            explore each subtree (by the algorithm) from the
     504                leftmost one to the rightmost one;
     505            then manipulate the root with function `action` (in the
     506                case of a binary tree, only if the root is not a leaf).
    418507
    419508        INPUT:
    420509
    421         - ``action`` -- (optional) a function which takes a node in
    422           input and does something during the exploration
     510        - ``action`` -- (optional) a function which takes a node as
     511          input, and does something during the exploration
     512
     513        OUTPUT:
     514
     515        ``None``. (This is *not* an iterator.)
    423516
    424517        .. SEEALSO::
    425518
    class AbstractTree(object): 
    435528            sage: b.post_order_traversal(lambda node: l.append(node.label()))
    436529            sage: l
    437530            [2, 1, 4, 6, 5, 8, 7, 3]
     531
    438532            sage: t = OrderedTree([[[[],[]]],[[]],[[],[]]]).\
    439533            ....:     canonical_labelling(); t
    440534            1[2[3[4[], 5[]]], 6[7[]], 8[9[], 10[]]]
    class AbstractTree(object): 
    442536            sage: t.post_order_traversal(lambda node: l.append(node.label()))
    443537            sage: l
    444538            [4, 5, 3, 2, 7, 6, 9, 10, 8, 1]
     539
    445540            sage: l = []
    446541            sage: BinaryTree().canonical_labelling().\
    447542            ....:     post_order_traversal(lambda node: l.append(node.label()))
    class AbstractTree(object): 
    451546            ....:     post_order_traversal(lambda node: l.append(node.label()))
    452547            sage: l
    453548            [1]
     549
     550        The following test checks that things don't go wrong if some among
     551        the descendants of the tree are equal or even identical::
     552
     553            sage: u = BinaryTree(None)
     554            sage: v = BinaryTree([u, u])
     555            sage: w = BinaryTree([v, v])
     556            sage: t = BinaryTree([w, w])
     557            sage: t.node_number()
     558            7
     559            sage: l = []
     560            sage: t.post_order_traversal(lambda node: l.append(1))
     561            sage: len(l)
     562            7
    454563        """
    455564        if action is None:
    456565            action = lambda x: None
    class AbstractTree(object): 
    459568
    460569    def iterative_post_order_traversal(self, action=None):
    461570        r"""
    462         The depth-first post-order traversal algorithm (iterative
    463         implementation).
     571        Run the depth-first post-order traversal algorithm (iterative
     572        implementation) and subject every node encountered
     573        to some procedure ``action``. The algorithm is::
     574
     575            explore each subtree (by the algorithm) from the
     576                leftmost one to the rightmost one;
     577            then manipulate the root with function `action` (in the
     578                case of a binary tree, only if the root is not a leaf).
    464579
    465580        INPUT:
    466581
    467         - ``action`` -- (optional) a function which takes a node in input and
    468           does something during the exploration
     582        - ``action`` -- (optional) a function which takes a node as
     583          input, and does something during the exploration
     584
     585        OUTPUT:
     586
     587        ``None``. (This is *not* an iterator.)
    469588
    470589        .. SEEALSO::
    471590
    class AbstractTree(object): 
    479598            3[1[., 2[., .]], 7[5[4[., .], 6[., .]], 8[., .]]]
    480599            sage: b.iterative_post_order_traversal(lambda node: l.append(node.label()))
    481600            sage: l
    482             [8, 6, 4, 5, 7, 2, 1, 3]
     601            [2, 1, 4, 6, 5, 8, 7, 3]
     602
    483603            sage: t = OrderedTree([[[[],[]]],[[]],[[],[]]]).canonical_labelling()
    484604            sage: t
    485605            1[2[3[4[], 5[]]], 6[7[]], 8[9[], 10[]]]
    486606            sage: l = []
    487607            sage: t.iterative_post_order_traversal(lambda node: l.append(node.label()))
    488608            sage: l
    489             [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
     609            [4, 5, 3, 2, 7, 6, 9, 10, 8, 1]
     610
    490611            sage: l = []
    491612            sage: BinaryTree().canonical_labelling().\
    492613            ....:     iterative_post_order_traversal(
    class AbstractTree(object): 
    498619            ....:         lambda node: l.append(node.label()))
    499620            sage: l
    500621            [1]
     622
     623        The following test checks that things don't go wrong if some among
     624        the descendants of the tree are equal or even identical::
     625
     626            sage: u = BinaryTree(None)
     627            sage: v = BinaryTree([u, u])
     628            sage: w = BinaryTree([v, v])
     629            sage: t = BinaryTree([w, w])
     630            sage: t.node_number()
     631            7
     632            sage: l = []
     633            sage: t.iterative_post_order_traversal(lambda node: l.append(1))
     634            sage: len(l)
     635            7
    501636        """
    502637        if self.is_empty():
    503638            return
    504639        if action is None:
    505640            action = lambda x: None
    506641        stack = [self]
    507         mark = []
    508642        while len(stack) > 0:
    509643            node = stack[-1]
    510             if node in mark:
     644            if node != None:
     645                # A "None" on the stack means that the node right before
     646                # it on the stack has already been "exploded" into
     647                # subtrees, and should not be exploded again, but instead
     648                # should be manipulated and removed from the stack.
     649                stack.append(None)
     650                for i in range(len(node)):
     651                    subtree = node[-i - 1]
     652                    if not subtree.is_empty():
     653                        stack.append(subtree)
     654            else:
    511655                stack.pop()
     656                node = stack.pop()
    512657                action(node)
    513             else:
    514                 mark.append(node)
    515                 stack.extend(filter(lambda n: not n.is_empty(), node))
    516658
    517659    def breadth_first_order_traversal(self, action=None):
    518660        r"""
    519         The breadth-first order traversal algorithm.
     661        Run the breadth-first post-order traversal algorithm
     662        and subject every node encountered to some procedure
     663        ``action``. The algorithm is::
     664
     665            queue <- [ root ];
     666            while the queue is not empty:
     667                node <- pop( queue );
     668                manipulate the node;
     669                prepend to the queue the list of all subtrees of
     670                    the node (from the rightmost to the leftmost).
    520671
    521672        INPUT:
    522673
    523         - ``action`` -- (optional) a function which takes a node in input and
    524           does omething during the exploration
     674        - ``action`` -- (optional) a function which takes a node as
     675          input, and does something during the exploration
     676
     677        OUTPUT:
     678
     679        ``None``. (This is *not* an iterator.)
     680
     681        EXAMPLES:
    525682
    526683        For example, on the following binary tree `b`::
    527684
    class AbstractTree(object): 
    533690            |        / \      |
    534691            |       4   6     |
    535692
    536         the ``breadth-first order traversal algorithm`` explores `b` in the
     693        the breadth-first order traversal algorithm explores `b` in the
    537694        following order of nodes: `3,1,7,2,5,8,4,6`.
    538695
    539         The algorithm is::
    540 
    541             queue <- ( root )
    542             while the queue is not empty:
    543                 node <- pop( queue )
    544                 manipulate the node
    545                 append in the queue all subtrees of the node
    546 
    547696        TESTS::
    548697
    549698            sage: b = BinaryTree([[None,[]],[[[],[]],[]]]).canonical_labelling()
    class AbstractTree(object): 
    551700            sage: b.breadth_first_order_traversal(lambda node: l.append(node.label()))
    552701            sage: l
    553702            [3, 1, 7, 2, 5, 8, 4, 6]
     703
    554704            sage: t = OrderedTree([[[[],[]]],[[]],[[],[]]]).canonical_labelling()
    555705            sage: t
    556706            1[2[3[4[], 5[]]], 6[7[]], 8[9[], 10[]]]
    class AbstractTree(object): 
    558708            sage: t.breadth_first_order_traversal(lambda node: l.append(node.label()))
    559709            sage: l
    560710            [1, 2, 6, 8, 3, 7, 9, 10, 4, 5]
     711
    561712            sage: l = []
    562713            sage: BinaryTree().canonical_labelling().\
    563714            ....:     breadth_first_order_traversal(
    class AbstractTree(object): 
    585736
    586737    def subtrees(self):
    587738        """
    588         Return a generator for all subtrees of ``self``.
     739        Return a generator for all nonempty subtrees of ``self``.
    589740
    590         The number of subtrees of a tree is its number of elements.
     741        The number of nonempty subtrees of a tree is its number of
     742        nodes. (The word "nonempty" makes a difference only in the
     743        case of binary trees. For ordered trees, for example, all
     744        trees are nonempty.)
    591745
    592746        EXAMPLES::
    593747
    class AbstractTree(object): 
    596750            sage: list(OrderedTree([[],[[]]]).subtrees())
    597751            [[[], [[]]], [], [[]], []]
    598752
     753            sage: list(OrderedTree([[],[[]]]).canonical_labelling().subtrees())
     754            [1[2[], 3[4[]]], 2[], 3[4[]], 4[]]
     755
    599756            sage: list(BinaryTree([[],[[],[]]]).subtrees())
    600757            [[[., .], [[., .], [., .]]], [., .], [[., .], [., .]], [., .], [., .]]
    601758
     759            sage: v = BinaryTree([[],[]])
     760            sage: list(v.canonical_labelling().subtrees())
     761            [2[1[., .], 3[., .]], 1[., .], 3[., .]]
     762
    602763        TESTS::
    603764
    604765            sage: t = OrderedTree([[], [[], [[], []], [[], []]], [[], []]])
    class AbstractTree(object): 
    619780        OUTPUT:
    620781
    621782        This method returns a list of sequences of integers. Each of these
    622         sequences represents a path from the root node to another one : `(1, 3,
    623         2, 5, 3)` represents the node obtained by chosing the 1st children of
    624         the root node (in the ordering returned by ``iter``), then the 3rd of
    625         its children, then the 2nd of this element, etc.
     783        sequences represents a path from the root node to some node. For
     784        instance, `(1, 3, 2, 5, 0, 3)` represents the node obtained by
     785        choosing the 1st child of the root node (in the ordering returned
     786        by ``iter``), then the 3rd child of its child, then the 2nd child
     787        of the latter, etc. (where the labelling of the children is
     788        zero-based).
    626789
    627790        The root element is represented by the empty tuple ``()``.
    628791
    class AbstractTree(object): 
    655818
    656819    def node_number(self):
    657820        """
    658         The number of nodes of ``self``
     821        The number of nodes of ``self``.
    659822
    660823        EXAMPLES::
    661824
    class AbstractTree(object): 
    670833            sage: OrderedTree([[], [[], [[], []], [[], []]], [[], []]]).node_number()
    671834            13
    672835
    673         EXAMPLE::
     836        EXAMPLES::
    674837
    675838            sage: BinaryTree(None).node_number()
    676839            0
    class AbstractTree(object): 
    688851
    689852    def depth(self):
    690853        """
    691         The depth of ``self``
     854        The depth of ``self``.
    692855
    693856        EXAMPLES::
    694857
    class AbstractTree(object): 
    826989
    827990    def canonical_labelling(self,shift=1):
    828991        """
    829         Returns a labelled version of ``self``
     992        Returns a labelled version of ``self``.
    830993
    831994        The actual canonical labelling is currently unspecified. However, it
    832995        is guaranteed to have labels in `1...n` where `n` is the number of
    class AbstractTree(object): 
    8591022
    8601023    def tree_factorial(self):
    8611024        """
    862         Return the tree-factorial of ``self``
     1025        Return the tree-factorial of ``self``.
    8631026
    8641027        Definition:
    8651028
    class AbstractTree(object): 
    8881051
    8891052    def _latex_(self):
    8901053        r"""
    891         Nice output which can be easily modified
     1054        Generate `\LaTeX` output which can be easily modified.
    8921055
    8931056        TESTS::
    8941057
    class AbstractTree(object): 
    9111074                (a) edge (b) edge (e);
    9121075            \end{tikzpicture}}
    9131076        """
     1077        ###############################################################################
     1078        # # use to load tikz in the preamble (one for *view* and one for *notebook*)
     1079        from sage.misc.latex import latex
     1080        latex.add_package_to_preamble_if_available("tikz")
     1081        latex.add_to_mathjax_avoid_list("tikz")
     1082        ###############################################################################
    9141083        # latex environnement : TikZ
    9151084        begin_env = "\\begin{tikzpicture}[auto]\n"
    9161085        end_env = "\\end{tikzpicture}"
    class AbstractTree(object): 
    12491418
    12501419class AbstractClonableTree(AbstractTree):
    12511420    """
    1252     Abstract Clonable Tree
     1421    Abstract Clonable Tree.
    12531422
    12541423    An abstract class for trees with clone protocol (see
    12551424    :mod:`~sage.structure.list_clone`). It is expected that classes extending
    12561425    this one may also inherit from classes like :class:`ClonableArray` or
    1257     :class:`~sage.structure.list_clone.ClonableList` depending wether one
     1426    :class:`~sage.structure.list_clone.ClonableList` depending whether one
    12581427    wants to build trees where adding a child is allowed.
    12591428
    12601429    .. NOTE:: Due to the limitation of Cython inheritance, one cannot inherit
    12611430       here from :class:`~sage.structure.list_clone.ClonableElement`, because
    1262        it would prevent us to inherit later from
     1431       it would prevent us from later inheriting from from
    12631432       :class:`~sage.structure.list_clone.ClonableArray` or
    12641433       :class:`~sage.structure.list_clone.ClonableList`.
    12651434
    12661435    .. rubric:: How should this class be extended ?
    12671436
    1268     A class extending :class:`AbstractTree
    1269     <sage.combinat.abstract_tree.AbstractTree>` should the following
    1270     assumptions:
     1437    A class extending :class:`AbstractClonableTree
     1438    <sage.combinat.abstract_tree.AbstractClonableTree>` should satisfy the
     1439    following assumptions:
    12711440
    1272     * An instantiable class extending :class:`AbstractTree
    1273       <sage.combinat.abstract_tree.AbstractTree>` should also extend the
    1274       :class:`ClonableElement <sage.structure.list_clone.ClonableElement>`
    1275       class or one of its subclass generally at least :class:`ClonableArray
     1441    * An instantiable class extending :class:`AbstractClonableTree
     1442      <sage.combinat.abstract_tree.AbstractClonableTree>` should also extend
     1443      the :class:`ClonableElement <sage.structure.list_clone.ClonableElement>`
     1444      class or one of its subclasses generally, at least :class:`ClonableArray
    12761445      <sage.structure.list_clone.ClonableArray>`.
    12771446
    1278 
    12791447    * To respect the Clone protocol, the :meth:`AbstractClonableTree.check`
    12801448      method should be overridden by the new class.
     1449
     1450    See also the assumptions in :class:`AbstractTree`.
    12811451    """
    12821452    def check(self):
    12831453        """
    1284         Check that ``self`` is a correct tree
     1454        Check that ``self`` is a correct tree.
    12851455
    12861456        This method does nothing. It is implemented here because many
    1287         extensions of :class:`AbstractTree
    1288         <sage.combinat.abstract_tree.AbstractTree>` also extend
     1457        extensions of :class:`AbstractClonableTree
     1458        <sage.combinat.abstract_tree.AbstractClonableTree>` also extend
    12891459        :class:`sage.structure.list_clone.ClonableElement`, which requires it.
    12901460
    1291         It should be overriden in subclass in order to check that the
    1292         invariant of the kind of tree holds (eg: two children for binary
    1293         trees).
     1461        It should be overridden in subclasses in order to check that the
     1462        characterizing property of the respective kind of tree holds (eg: two
     1463        children for binary trees).
    12941464
    12951465        EXAMPLES::
    12961466
    class AbstractClonableTree(AbstractTree) 
    13321502
    13331503            sage: x = OrderedTree([[],[[]]])
    13341504            sage: with x.clone() as x:
    1335             ...    x[0] = OrderedTree([[]])
     1505            ....:     x[0] = OrderedTree([[]])
    13361506            sage: x
    13371507            [[[]], [[]]]
    13381508
    class AbstractClonableTree(AbstractTree) 
    13401510
    13411511            sage: y = OrderedTree(x)
    13421512            sage: with x.clone() as x:
    1343             ...    x[0,0] = OrderedTree([[]])
     1513            ....:     x[0,0] = OrderedTree([[]])
    13441514            sage: x
    13451515            [[[[]]], [[]]]
    13461516            sage: y
    13471517            [[[]], [[]]]
    13481518            sage: with y.clone() as y:
    1349             ...    y[(0,)] = OrderedTree([])
     1519            ....:     y[(0,)] = OrderedTree([])
    13501520            sage: y
    13511521            [[], [[]]]
    13521522
    class AbstractClonableTree(AbstractTree) 
    13551525            sage: bt = BinaryTree([[],[[],[]]]); bt
    13561526            [[., .], [[., .], [., .]]]
    13571527            sage: with bt.clone() as bt1:
    1358             ...    bt1[0,0] = BinaryTree([[[], []], None])
     1528            ....:     bt1[0,0] = BinaryTree([[[], []], None])
    13591529            sage: bt1
    13601530            [[[[[., .], [., .]], .], .], [[., .], [., .]]]
    13611531
    class AbstractClonableTree(AbstractTree) 
    13631533
    13641534            sage: x = OrderedTree([])
    13651535            sage: with x.clone() as x:
    1366             ...    x[0] = OrderedTree([[]])
     1536            ....:     x[0] = OrderedTree([[]])
    13671537            Traceback (most recent call last):
    1368             ...
     1538            ....:
    13691539            IndexError: list assignment index out of range
    13701540
    1371             sage: x = OrderedTree([]); x = OrderedTree([x,x]);x = OrderedTree([x,x]); x = OrderedTree([x,x])
     1541            sage: x = OrderedTree([]); x = OrderedTree([x,x]); x = OrderedTree([x,x]); x = OrderedTree([x,x])
    13721542            sage: with x.clone() as x:
    1373             ...    x[0,0] = OrderedTree()
     1543            ....:     x[0,0] = OrderedTree()
    13741544            sage: x
    13751545            [[[], [[], []]], [[[], []], [[], []]]]
    13761546        """
    class AbstractClonableTree(AbstractTree) 
    13871557
    13881558            sage: x = OrderedTree([[[], []],[[]]])
    13891559            sage: with x.clone() as x:
    1390             ...    x[0,1] = OrderedTree([[[]]]) # indirect doctest
     1560            ....:     x[0,1] = OrderedTree([[[]]]) # indirect doctest
    13911561            sage: x
    13921562            [[[], [[[]]]], [[]]]
    13931563        """
    class AbstractClonableTree(AbstractTree) 
    14411611
    14421612class AbstractLabelledTree(AbstractTree):
    14431613    """
    1444     Abstract Labelled Tree
     1614    Abstract Labelled Tree.
    14451615
    1446     Typically a class for labelled tree is contructed by inheriting from a
    1447     class for unlabelled trees and :class:`AbstractLabelledTree`
     1616    Typically a class for labelled trees is contructed by inheriting from
     1617    a class for unlabelled trees and :class:`AbstractLabelledTree`.
    14481618
    14491619    .. rubric:: How should this class be extended ?
    14501620
    class AbstractLabelledTree(AbstractTree) 
    14531623    following assumptions:
    14541624
    14551625    * For a labelled tree ``T`` the call ``T.parent().unlabelled_trees()``
    1456       should return a parent for labelled trees of the same kind: for example,
     1626      should return a parent for unlabelled trees of the same kind: for
     1627      example,
    14571628
    14581629      - if ``T`` is a binary labelled tree, ``T.parent()`` is
    14591630        ``LabelledBinaryTrees()`` and ``T.parent().unlabelled_trees()`` is
    class AbstractLabelledTree(AbstractTree) 
    14641635        ``OrderedTrees()``
    14651636
    14661637    * In the same vein, the class of ``T`` should contain an attribute
    1467       ``_Unlabelled`` which should be the class for the corresponding
     1638      ``_UnLabelled`` which should be the class for the corresponding
    14681639      unlabelled trees.
    14691640
     1641    See also the assumptions in :class:`AbstractTree`.
     1642
    14701643    .. SEEALSO:: :class:`AbstractTree`
    14711644    """
    14721645    def __init__(self, parent, children, label = None, check = True):
    class AbstractLabelledClonableTree(Abstr 
    17361909            ...
    17371910            ValueError: object is immutable; please change a copy instead.
    17381911            sage: with t.clone() as t:
    1739             ...    t.set_root_label(3)
     1912            ....:     t.set_root_label(3)
    17401913            sage: t.label()
    17411914            3
    17421915            sage: t
    class AbstractLabelledClonableTree(Abstr 
    17501923            ...
    17511924            ValueError: object is immutable; please change a copy instead.
    17521925            sage: with bt.clone() as bt:
    1753             ...    bt.set_root_label(3)
     1926            ....:     bt.set_root_label(3)
    17541927            sage: bt.label()
    17551928            3
    17561929            sage: bt
    class AbstractLabelledClonableTree(Abstr 
    17591932        TESTS::
    17601933
    17611934            sage: with t.clone() as t:
    1762             ...    t[0] = LabelledOrderedTree(t[0], label = 4)
     1935            ....:     t[0] = LabelledOrderedTree(t[0], label = 4)
    17631936            sage: t
    17641937            3[4[], None[None[], None[]]]
    17651938            sage: with t.clone() as t:
    1766             ...    t[1,0] = LabelledOrderedTree(t[1,0], label = 42)
     1939            ....:     t[1,0] = LabelledOrderedTree(t[1,0], label = 42)
    17671940            sage: t
    17681941            3[4[], None[42[], None[]]]
    1769             """
     1942        """
    17701943        self._require_mutable()
    17711944        self._label = label
    17721945
    class AbstractLabelledClonableTree(Abstr 
    17971970            ...
    17981971            ValueError: object is immutable; please change a copy instead.
    17991972            sage: with t.clone() as t:
    1800             ...    t.set_label((0,), 4)
     1973            ....:     t.set_label((0,), 4)
    18011974            sage: t
    18021975            None[4[], None[None[], None[]]]
    18031976            sage: with t.clone() as t:
    1804             ...    t.set_label((1,0), label = 42)
     1977            ....:     t.set_label((1,0), label = 42)
    18051978            sage: t
    18061979            None[4[], None[42[], None[]]]
    18071980
  • sage/combinat/binary_tree.py

    diff --git a/sage/combinat/binary_tree.py b/sage/combinat/binary_tree.py
    a b  
    11# -*- coding: utf-8 -*-
    22"""
    3 Binary Trees
     3Binary Trees.
    44
    55This module deals with binary trees as mathematical (in particular immutable)
    66objects.
    AUTHORS: 
    1616
    1717REFERENCES:
    1818
    19 .. [LodayRonco] Jean-Louis Loday and María O. Ronco.
     19.. [LodayRonco] Jean-Louis Loday and Maria O. Ronco.
    2020   *Hopf algebra of the planar binary trees*,
    2121   Advances in Mathematics, volume 139, issue 2,
    2222   10 November 1998, pp. 293-309.
    REFERENCES: 
    2626   *The algebra of binary search trees*,
    2727   :arxiv:`math/0401089v2`.
    2828
    29 .. [CP12] Gregory Chatel, Vivane Pons.
     29.. [CP12] Gregory Chatel, Viviane Pons.
    3030   *Counting smaller trees in the Tamari order*,
    3131   :arxiv:`1212.0751v1`.
    3232"""
    class BinaryTree(AbstractClonableTree, C 
    5757
    5858    Binary trees contain nodes and leaves, where each node has two
    5959    children while each leaf has no children. The number of leaves
    60     always equals the number of nodes plus `1`.
     60    of a binary tree always equals the number of nodes plus `1`.
    6161
    6262    INPUT:
    6363
    class BinaryTree(AbstractClonableTree, C 
    6767      leaf or a pair of binary trees. Syntactic sugar allows leaving out
    6868      all but the outermost calls of the ``BinaryTree()`` constructor, so
    6969      that, e. g., ``BinaryTree([BinaryTree(None),BinaryTree(None)])`` can
    70       be simplified to ``BinaryTree([None,None])``. It is also allowed to
     70      be shortened to ``BinaryTree([None,None])``. It is also allowed to
    7171      abbreviate ``[None, None]`` by ``[]``.
    7272
    73     - ``check`` -- (default to ``True``) whether check for binary should be
     73    - ``check`` -- (default: ``True``) whether check for binary should be
    7474      performed or not.
    7575
    7676    EXAMPLES::
    class BinaryTree(AbstractClonableTree, C 
    8989        [[., .], .]
    9090        sage: BinaryTree("[[], .]")
    9191        [[., .], .]
     92        sage: BinaryTree([None, BinaryTree([None, None])])
     93        [., [., .]]
    9294
    9395        sage: BinaryTree([[], None, []])
    9496        Traceback (most recent call last):
    class BinaryTree(AbstractClonableTree, C 
    100102        sage: t1 = BinaryTree([[None, [[],[[], None]]],[[],[]]])
    101103        sage: t2 = BinaryTree([[[],[]],[]])
    102104        sage: with t1.clone() as t1c:
    103         ...       t1c[1,1,1] = t2
     105        ....:     t1c[1,1,1] = t2
    104106        sage: t1 == t1c
    105107        False
    106108    """
    class BinaryTree(AbstractClonableTree, C 
    493495
    494496        if with_leaves:   # We want leaves and nodes.
    495497
    496             # Special treatment for the case when self has only 1 vertex.
     498            # Special treatment for the case when self is empty.
    497499            # In this case, rec(self, 0) would give a false result.
    498500            if not self:
    499501                return DiGraph([[0], lambda i,j: False])
    class BinaryTree(AbstractClonableTree, C 
    539541            return res
    540542
    541543    def canonical_labelling(self,shift=1):
    542         """
     544        r"""
    543545        Return a labelled version of ``self``.
    544546
    545         The canonical labelling of a binary tree is a certain labelling of the
     547        The canonical labelling of a binary tree is a certain labelling of the 
    546548        nodes (not the leaves) of the tree.
    547549        The actual canonical labelling is currently unspecified. However, it
    548550        is guaranteed to have labels in `1...n` where `n` is the number of
    class BinaryTree(AbstractClonableTree, C 
    575577        .. WARNING::
    576578
    577579            Left and right children might get interchanged in
    578             the actual picture.
     580            the actual picture. Moreover, for a labelled binary
     581            tree, the labels shown in the picture are not (in
     582            general) the ones given by the labelling!
     583
     584            Use :meth:`_latex_`, ``view``,
     585            :meth:`_ascii_art_` or ``pretty_print`` for more
     586            faithful representations of the data of the tree.
    579587
    580588        TESTS::
    581589
    class BinaryTree(AbstractClonableTree, C 
    12201228        The depth-first infix-order traversal iterator for the binary
    12211229        tree ``self``.
    12221230
    1223         This method iters each vertex (node and leaf alike) following the
    1224         depth-first infix order traversal algorithm.
     1231        This method iters each vertex (node and leaf alike) of the given
     1232        binary tree following the depth-first infix order traversal
     1233        algorithm.
    12251234
    12261235        The *depth-first infix order traversal algorithm* iterates
    12271236        through a binary tree as follows::
    class BinaryTree(AbstractClonableTree, C 
    12761285            [    1     4       3   5    ]
    12771286            [         / \               ]
    12781287            [        3   5,  ,      ,   ]
     1288
     1289            sage: list(BinaryTree(None).in_order_traversal_iter())
     1290            [.]
    12791291        """
    12801292        if self.is_empty():
    12811293            yield self
    class BinaryTree(AbstractClonableTree, C 
    13481360            sage: def n_action(_):
    13491361            ....:    global nb_node
    13501362            ....:    nb_node += 1
     1363
    13511364            sage: BinaryTree().in_order_traversal(n_action, l_action)
    13521365            sage: nb_leaf, nb_node
    13531366            (1, 0)
     1367
    13541368            sage: nb_leaf, nb_node = 0, 0
    13551369            sage: b = BinaryTree([[],[[],[]]]); b
    13561370            [[., .], [[., .], [., .]]]
    class BinaryTree(AbstractClonableTree, C 
    13661380            sage: b.in_order_traversal(lambda node: l.append( node.label() ))
    13671381            sage: l
    13681382            [1, 2, 3, 4, 5]
     1383
    13691384            sage: leaf = 'a'
    13701385            sage: l = []
    13711386            sage: def l_action(_):
    class BinaryTree(AbstractClonableTree, C 
    13951410        r"""
    13961411        The list of all trees greater or equal to ``self`` in the Tamari
    13971412        order.
    1398         This is the transitive ideal of its successors.
     1413        This is the order filter of the Tamari order generated ``self``.
    13991414
    14001415        The Tamari order on binary trees of size `n` is the partial order
    14011416        on the set of all binary trees of size `n` generated by the
    class BinaryTree(AbstractClonableTree, C 
    14071422        is a quotient of the weak order on the `n`-th symmetric group.
    14081423        See [CP12]_.
    14091424
     1425        EXAMPLES::
     1426
    14101427        For example, the tree::
    14111428
    14121429            |     __o__   |
    class BinaryTree(AbstractClonableTree, C 
    14631480    def tamari_pred(self):
    14641481        r"""
    14651482        Compute the list of predecessors of ``self`` in the Tamari poset.
    1466         This list is computed by all left rotate possible on
     1483
     1484        This list is computed by performing all left rotates possible on
    14671485        its nodes.
    14681486
     1487        EXAMPLES::
     1488
    14691489        For this tree::
    14701490
    14711491            |     __o__   |
    class BinaryTree(AbstractClonableTree, C 
    15101530        r"""
    15111531        The list of all trees smaller or equal to ``self`` in the Tamari
    15121532        order.
    1513         This is the transitive ideal of its predecessors.
     1533        This is the order ideal of the Tamari order generated ``self``.
     1534
     1535        The Tamari order on binary trees of size `n` is the partial order
     1536        on the set of all binary trees of size `n` generated by the
     1537        following requirement:  If a binary tree `T'` is obtained by
     1538        right rotation (see :meth:`right_rotate`) from a binary tree `T`,
     1539        then `T < T'`.
     1540        This not only is a well-defined partial order, but actually is
     1541        a lattice structure on the set of binary trees of size `n`, and
     1542        is a quotient of the weak order on the `n`-th symmetric group.
     1543        See [CP12]_.
     1544
     1545        EXAMPLES::
    15141546
    15151547        The tree::
    15161548
    class BinaryTree(AbstractClonableTree, C 
    15521584    def tamari_succ(self):
    15531585        r"""
    15541586        Compute the list of successors of ``self`` in the Tamari poset.
    1555         There is the list of all trees obtained by a right rotate of
     1587
     1588        This is the list of all trees obtained by a right rotate of
    15561589        one of its nodes.
    15571590
     1591        EXAMPLES::
     1592
    15581593        The list of successors of::
    15591594
    15601595            |     __o__   |
    class BinaryTree(AbstractClonableTree, C 
    16321667            h_{q} (T_1) h_{q} (T_2),
    16331668
    16341669        where `T` is any nonempty binary tree, and `T_1` and `T_2` are
    1635         the two children trees of the root of `T`, and where
     1670        the two child trees of the root of `T`, and where
    16361671        `\binom{a}{b}_q` denotes a `q`-binomial coefficient.
    16371672
    16381673        A variation of the `q`-hook length fraction is the following
    class BinaryTree(AbstractClonableTree, C 
    17921827        tree ``self``.
    17931828
    17941829        Right rotation on binary trees is defined as follows:
    1795         Let `T` be a nonempty binary tree such that the left
    1796         child of the root of `T` is a node. Let `C` be the right
     1830        Let `T` be a binary tree such that the left child of the
     1831        root of `T` is a node. Let `C` be the right
    17971832        child of the root of `T`, and let `A` and `B` be the
    17981833        left and right children of the left child of the root
    17991834        of `T`. (Keep in mind that nodes of trees are identified
    18001835        with the subtrees consisting of their descendants.)
    1801         Then, the right rotation of `T` is the nonempty binary
    1802         tree in which the left child of the root is `A`, whereas
     1836        Then, the right rotation of `T` is the binary tree in
     1837        which the left child of the root is `A`, whereas
    18031838        the right child of the root is a node whose left and right
    18041839        children are `B` and `C`. In pictures::
    18051840
    class BinaryTree(AbstractClonableTree, C 
    18791914        tree ``self``.
    18801915
    18811916        Left rotation on binary trees is defined as follows:
    1882         Let `T` be a nonempty binary tree such that the right
    1883         child of the root of `T` is a node. Let `A` be the left
     1917        Let `T` be a binary tree such that the right child of the
     1918        root of `T` is a node. Let `A` be the left
    18841919        child of the root of `T`, and let `B` and `C` be the
    18851920        left and right children of the right child of the root
    18861921        of `T`. (Keep in mind that nodes of trees are identified
    18871922        with the subtrees consisting of their descendants.)
    1888         Then, the left rotation of `T` is the nonempty binary
    1889         tree in which the right child of the root is `C`, whereas
     1923        Then, the left rotation of `T` is the binary tree in
     1924        which the right child of the root is `C`, whereas
    18901925        the left child of the root is a node whose left and right
    18911926        children are `A` and `B`. In pictures::
    18921927
    class BinaryTree(AbstractClonableTree, C 
    19521987
    19531988        If `T` and `T'` are two binary trees, then `T` over `T'`
    19541989        (written `T / T'`) is defined as the tree obtained by grafting
    1955         `T'` on the rightmost node of `T`. See section 4.5 of [HNT05]_.
     1990        `T'` on the rightmost leaf of `T`. More precisely, `T / T'` is
     1991        defined by identifying the root of the `T'` with the rightmost
     1992        leaf of `T`. See section 4.5 of [HNT05]_.
     1993
     1994        If `T` is empty, then `T / T' = T'`.
    19561995
    19571996        .. TODO::
    19581997
    1959             Fix this doc and figure out which of the different
    1960             (inconsistent?) notations to follow. I don't see the
    1961             "over" operation defined in [LodayRonco]_, although
    1962             [HNT05]_ pretends that it is defined there. In
    1963             [HNT05]_ the definition is somewhat vague about the
    1964             order of the operads. Loday and Ronco seem to define
     1998            I don't see the "over" operation defined in
     1999            [LodayRonco]_, although [HNT05]_ pretends that it
     2000            is defined there. Loday and Ronco seem to define
    19652001            "over" on page 2 of "Order structure on the algebra
    19662002            of permutations and of planar binary trees", but
    19672003            with a different choice of left/right.
    19682004
    1969         This is defined by::
     2005            Same for "under".
     2006
     2007        EXAMPLES:
     2008
     2009        Showing only the nodes of a binary tree, here is an
     2010        example for the over operation:
    19702011
    19712012            |   o       __o__       _o_         |
    19722013            |  / \  /  /     \  =  /   \        |
    class BinaryTree(AbstractClonableTree, C 
    19782019            |                          \     /  |
    19792020            |                           o   o   |
    19802021
    1981         EXAMPLES::
     2022        A Sage example::
    19822023
    19832024            sage: b1 = BinaryTree([[],[[],[]]])
    19842025            sage: b2 = BinaryTree([[None, []],[]])
    class BinaryTree(AbstractClonableTree, C 
    20172058            [     o       o ]
    20182059            [      \     /  ]
    20192060            [       o   o   ]
     2061
     2062        The same in the labelled case:
     2063
     2064            sage: b1 = b1.canonical_labelling()
     2065            sage: b2 = b2.canonical_labelling()
     2066            sage: ascii_art([b1.over(b2)])
     2067            [   _2_         ]
     2068            [  /   \        ]
     2069            [ 1     3       ]
     2070            [        \      ]
     2071            [       __3__   ]
     2072            [      /     \  ]
     2073            [     1       5 ]
     2074            [      \     /  ]
     2075            [       2   4   ]
    20202076        """
    20212077        B = self.parent()._element_constructor_
    20222078        if self.is_empty():
    20232079            return bt
    2024         lab = None
    20252080        if hasattr(self, "label"):
    20262081            lab = self.label()
     2082            return B([self[0], self[1].over(bt)], lab)
    20272083        else:
    2028             return B([self[0], self[1].over(bt)], lab)
     2084            return B([self[0], self[1].over(bt)])
    20292085
    20302086    __div__ = over
    20312087
    class BinaryTree(AbstractClonableTree, C 
    20352091        The ``under`` (`\backslash`) operation defined by Loday-Ronco
    20362092        [LodayRonco]_.
    20372093
     2094        If `T` and `T'` are two binary trees, then `T` under `T'`
     2095        (written `T \ T'`) is defined as the tree obtained by grafting
     2096        `T` on the leftmost leaf of `T'`. More precisely, `T \ T'` is
     2097        defined by identifying the root of `T` with the leftmost
     2098        leaf of `T'`. See section 4.5 of [HNT05]_.
     2099
     2100        If `T'` is empty, then `T \ T' = T`.
     2101
    20382102        EXAMPLES::
    20392103
     2104        Showing only the nodes of a binary tree, here is an
     2105        example for the under operation:
     2106
    20402107            sage: b1 = BinaryTree([[],[]])
    20412108            sage: b2 = BinaryTree([None,[]])
    20422109            sage: ascii_art((b1, b2, b1 \ b2))
    class BinaryTree(AbstractClonableTree, C 
    20742141            [     o         ]
    20752142            [      \        ]
    20762143            [       o       ]
     2144
     2145        The same in the labelled case:
     2146
     2147            sage: b1 = b1.canonical_labelling()
     2148            sage: b2 = b2.canonical_labelling()
     2149            sage: ascii_art([b1.under(b2)])
     2150            [        2_     ]
     2151            [       /  \    ]
     2152            [      1    3   ]
     2153            [     /      \  ]
     2154            [   _2_       4 ]
     2155            [  /   \        ]
     2156            [ 1     5       ]
     2157            [      /        ]
     2158            [     3         ]
     2159            [      \        ]
     2160            [       4       ]
    20772161        """
    20782162        B = self.parent()._element_constructor_
    20792163        if bt.is_empty():
    class BinaryTree(AbstractClonableTree, C 
    20812165        lab = None
    20822166        if hasattr(bt, "label"):
    20832167            lab = bt.label()
     2168            return B([self.under(bt[0]), bt[1]], lab)
    20842169        else:
    2085             return B([self.under(bt[0]), bt[1]], lab)
     2170            return B([self.under(bt[0]), bt[1]])
    20862171
    20872172    _backslash_ = under
    20882173
    class BinaryTree(AbstractClonableTree, C 
    20952180        `\sigma` whose binary search tree (a notion defined in [HNT05]_,
    20962181        Definition 7) is `T` after forgetting the labels. This is an
    20972182        equivalence class of the sylvester congruence (the congruence on
    2098         words which sets two words `uacvbw` and `ucavbw` congruent
     2183        words which holds two words `uacvbw` and `ucavbw` congruent
    20992184        whenever `a`, `b`, `c` are letters satisfying `a \leq b < c`, and
    21002185        extends by transitivity) on the symmetric group.
    21012186
    class BinaryTree(AbstractClonableTree, C 
    21092194        (only the nodes are drawn here).
    21102195
    21112196        The binary search tree of a word is constructed by an RSK-like
    2112         algorithm, in which the word is read from right to left. If a
    2113         left-to-right reading is to be employed instead, the
     2197        insertion algorithm which proceeds as follows: Start with an
     2198        empty labelled binary tree, and read the word from left to right.
     2199        Each time a letter is read from the word, insert this letter in
     2200        the existing tree using binary search tree insertion
     2201        (:meth:`~sage.combinat.binary_tree.LabelledBinaryTree.binary_search_insert`).
     2202        If a left-to-right reading is to be employed instead, the
    21142203        ``left_to_right`` optional keyword variable should be set to
    21152204        ``True``.
    21162205
    class BinaryTree(AbstractClonableTree, C 
    21532242        if self.is_empty():
    21542243            yield []
    21552244            return
    2156         import itertools
     2245        from itertools import product
    21572246        from sage.combinat.words.word import Word as W
    21582247        from sage.combinat.words.shuffle_product import ShuffleProduct_w1w2 \
    21592248            as shuffle
    class BinaryTree(AbstractClonableTree, C 
    21642253            builder = lambda i, p: list(p) + [i]
    21652254
    21662255        shift = self[0].node_number() + 1
    2167         for l, r in itertools.product(
    2168                     self[0].sylvester_class(),
    2169                     self[1].sylvester_class()):
     2256        for l, r in product(self[0].sylvester_class(),
     2257                            self[1].sylvester_class()):
    21702258           for p in shuffle(W(l), W([shift + ri for ri in r])):
    21712259               yield builder(shift, p)
    21722260
    class BinaryTree(AbstractClonableTree, C 
    22712359        r"""
    22722360        Return ``True`` if ``self`` is complete, else return ``False``.
    22732361
    2274         A complete binary tree is a perfect binary tree except possibly in the
    2275         last level.
    2276 
     2362        In a nutshell, a complete binary tree is a perfect binary tree
     2363        except possibly in the last level, with all nodes in the last
     2364        level "flush to the left".
     2365
     2366        In more detail:
    22772367        A complete binary tree (also called binary heap) is a binary tree in
    22782368        which every level, except possibly the last one (the deepest), is
    2279         completely filled. At depth `n` all nodes must be as far left as
     2369        completely filled. At depth `n`, all nodes must be as far left as
    22802370        possible.
    22812371
    22822372        For example::
    class BinaryTrees(UniqueRepresentation,  
    23882478        sage: BinaryTrees(2)
    23892479        Binary trees of size 2
    23902480
    2391     .. NOTE:: this in a factory class whose constructor returns instances of
     2481    .. NOTE:: this is a factory class whose constructor returns instances of
    23922482              subclasses.
    23932483
    2394     .. NOTE:: the fact that OrderedTrees is a class instead of a simple callable
     2484    .. NOTE:: the fact that BinaryTrees is a class instead of a simple callable
    23952485              is an implementation detail. It could be changed in the future
    23962486              and one should not rely on it.
    23972487    """
    class BinaryTrees(UniqueRepresentation,  
    24322522        TEST::
    24332523
    24342524            sage: (BinaryTrees().leaf() is
    2435             ...    sage.combinat.binary_tree.BinaryTrees_all().leaf())
     2525            ....:  sage.combinat.binary_tree.BinaryTrees_all().leaf())
    24362526            True
    24372527        """
    24382528        return self(None)
    class BinaryTrees_all(DisjointUnionEnume 
    25022592
    25032593    def unlabelled_trees(self):
    25042594        """
    2505         Return the set of unlabelled trees associated to ``self``
     2595        Return the set of unlabelled trees associated to ``self``.
    25062596
    25072597        EXAMPLES::
    25082598
    class BinaryTrees_all(DisjointUnionEnume 
    25132603
    25142604    def labelled_trees(self):
    25152605        """
    2516         Return the set of labelled trees associated to ``self``
     2606        Return the set of labelled trees associated to ``self``.
    25172607
    25182608        EXAMPLES::
    25192609
    class BinaryTrees_all(DisjointUnionEnume 
    25392629    Element = BinaryTree
    25402630
    25412631from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
    2542 from combinat import catalan_number
    25432632#################################################################
    25442633# Enumerated set of binary trees of a given size
    25452634#################################################################
    class BinaryTrees_size(BinaryTrees): 
    26092698            sage: BinaryTrees(5).cardinality()
    26102699            42
    26112700        """
     2701        from combinat import catalan_number
    26122702        return catalan_number(self._size)
    26132703
    26142704    def __iter__(self):
    class BinaryTrees_size(BinaryTrees): 
    26372727    @lazy_attribute
    26382728    def _parent_for(self):
    26392729        """
    2640         The parent of the element generated by ``self``
     2730        The parent of the elements generated by ``self``.
    26412731
    26422732        TESTS::
    26432733
    class LabelledBinaryTree(AbstractLabelle 
    26882778    Labelled binary trees.
    26892779
    26902780    A labelled binary tree is a binary tree (see :class:`BinaryTree` for
    2691     the meaning of this) with a label assigned to each node. (The labels
    2692     need not be integers, nor are they required to be distinct. ``None``
    2693     can be used as a label.)
     2781    the meaning of this) with a label assigned to each node and leaf.
     2782    The labels need not be integers, nor are they required to be distinct.
     2783    ``None`` can be used as a label.
     2784
     2785    INPUT:
     2786
     2787    - ``children`` -- ``None`` (default) or a list, tuple or iterable of
     2788      length `2` of labelled binary trees or convertible objects. This
     2789      corresponds to the standard recursive definition of a labelled
     2790      binary tree as given by a pair of:
     2791
     2792      - either a leaf or a pair of labelled binary trees,
     2793      - and a label.
     2794
     2795      (The label is specified in the keyword variable ``label``; see
     2796      below.)
     2797
     2798      Syntactic sugar allows leaving out all but the outermost calls
     2799      of the ``LabelledBinaryTree()`` constructor, so that, e. g.,
     2800      ``LabelledBinaryTree([LabelledBinaryTree(None),LabelledBinaryTree(None)])``
     2801      can be shortened to ``LabelledBinaryTree([None,None])``. However,
     2802      using this shorthand, it is impossible to label any vertex of
     2803      the tree other than the root (because there is no way to pass a
     2804      ``label`` variable without calling ``LabelledBinaryTree``
     2805      explicitly).
     2806
     2807      It is also allowed to abbreviate ``[None, None]`` by ``[]`` if
     2808      one does not want to label the leaves.
     2809
     2810    - ``label`` -- (default: ``None``) the label to be put on the root
     2811      of this tree.
     2812
     2813    - ``check`` -- (default: ``True``) whether checkes should be
     2814      performed or not.
    26942815
    26952816    .. TODO::
    26962817
    2697         Explain how to init these.
    2698 
    2699         Maybe allow ``LabelledBinaryTree()`` syntax for
    2700         ``LabelledBinaryTree(None)`` (in analogy to ``BinaryTree``
    2701         class).
    2702 
    2703     EXAMPLE::
     2818        It is currently not possible to use ``LabelledBinaryTree()``
     2819        as a shorthand for ``LabelledBinaryTree(None)`` (in analogy to
     2820        similar syntax in the ``BinaryTree`` class).
     2821
     2822    EXAMPLES::
     2823
     2824        sage: LabelledBinaryTree(None)
     2825        .
     2826        sage: LabelledBinaryTree(None, label="ae")
     2827        'ae'
     2828        sage: LabelledBinaryTree([])
     2829        None[., .]
     2830        sage: LabelledBinaryTree([], label=3)
     2831        3[., .]
     2832        sage: LabelledBinaryTree([None, None])
     2833        None[., .]
     2834        sage: LabelledBinaryTree([None, None], label=5)
     2835        5[., .]
     2836        sage: LabelledBinaryTree([None, []])
     2837        None[., None[., .]]
     2838        sage: LabelledBinaryTree([None, []], label=4)
     2839        4[., None[., .]]
     2840        sage: LabelledBinaryTree([[], None])
     2841        None[None[., .], .]
     2842        sage: LabelledBinaryTree("[[], .]", label=False)
     2843        False[None[., .], .]
     2844        sage: LabelledBinaryTree([None, LabelledBinaryTree([None, None], label=4)], label=3)
     2845        3[., 4[., .]]
     2846        sage: LabelledBinaryTree([None, BinaryTree([None, None])], label=3)
     2847        3[., None[., .]]
     2848
     2849        sage: LabelledBinaryTree([[], None, []])
     2850        Traceback (most recent call last):
     2851        ...
     2852        ValueError: this is not a binary tree
    27042853
    27052854        sage: LBT = LabelledBinaryTree
    27062855        sage: t1 = LBT([[LBT([], label=2), None], None], label=4); t1
    27072856        4[None[2[., .], .], .]
     2857
     2858    TESTS::
     2859
     2860        sage: t1 = LabelledBinaryTree([[None, [[],[[], None]]],[[],[]]])
     2861        sage: t2 = LabelledBinaryTree([[[],[]],[]])
     2862        sage: with t1.clone() as t1c:
     2863        ....:     t1c[1,1,1] = t2
     2864        sage: t1 == t1c
     2865        False
    27082866    """
    27092867    __metaclass__ = ClasscallMetaclass
    27102868
    class LabelledBinaryTree(AbstractLabelle 
    27122870    def __classcall_private__(cls, *args, **opts):
    27132871        """
    27142872        Ensure that trees created by the sets and directly are the same and
    2715         that they are instances of :class:`LabelledTree`
     2873        that they are instances of :class:`LabelledTree`.
    27162874
    27172875        TESTS::
    27182876
    class LabelledBinaryTree(AbstractLabelle 
    27402898            Labelled binary trees
    27412899            sage: LabelledBinaryTree([], label = 3).parent()
    27422900            Labelled binary trees
    2743          """
     2901        """
    27442902        return LabelledBinaryTrees()
    27452903
    27462904    def _repr_(self):
    class LabelledBinaryTree(AbstractLabelle 
    27682926
    27692927        INPUT:
    27702928
    2771         - ``letter`` -- any object comparable with the label of ``self``
     2929        - ``letter`` -- any object comparable with the labels of ``self``
    27722930
    27732931        OUTPUT:
    27742932
    class LabelledBinaryTree(AbstractLabelle 
    27762934        inserted into it according to the binary search insertion
    27772935        algorithm.
    27782936
    2779         .. NOTE:: ``self`` is supposed to be a binary search tree. No check is
    2780                   performed.
     2937        .. NOTE:: ``self`` is supposed to be a binary search tree.
     2938                  This is not being checked!
    27812939
    27822940        A right strict binary search tree is defined to be a labelled
    27832941        binary tree such that for each node `n` with label `x`,
    27842942        every descendant of the left child of `n` has a label `\leq x`,
    27852943        and every descendant of the right child of `n` has a label
    27862944        `> x`. (Here, only nodes count as descendants, and every node
    2787         counts as its own descendant too.)
    2788 
    2789         .. TODO::
    2790 
    2791             Explain the algorithm.
     2945        counts as its own descendant too.) Leaves are assumed to have
     2946        no labels.
     2947
     2948        Given a right strict binary search tree `t` and a letter `i`,
     2949        the result of inserting `i` into `t` (denoted `Ins(i, t)` in
     2950        the following) is defined recursively as follows:
     2951
     2952        - If `t` is empty, then `Ins(i, t)` is the tree with one node
     2953          only, and this node is labelled with `i`.
     2954
     2955        - Otherwise, let `j` be the label of the root of `t`. If
     2956          `i > j`, then `Ins(i, t)` is obtained by replacing the
     2957          right child of `t` by `Ins(i, r)` in `t`, where `r` denotes
     2958          the right child of `t`. If `i \leq j`, then `Ins(i, t)` is
     2959          obtained by replacing the left child of `t` by `Ins(i, l)`
     2960          in `t`, where `l` denotes the left child of `t`.
     2961
     2962        See, for example, [HNT05]_ for properties of this algorithm.
     2963
     2964        .. WARNING::
     2965
     2966            If `t` is nonempty, then inserting `i` into `t` does not
     2967            change the root label of `t`. Hence, as opposed to
     2968            algorithms like Robinson-Schensted-Knuth, binary
     2969            search tree insertion involves no bumping.
    27922970
    27932971        EXAMPLES::
    27942972
     2973        The example from Fig. 2 of [HNT05]_::
     2974
     2975            sage: LBT = LabelledBinaryTree
     2976            sage: x = LBT(None)
     2977            sage: x
     2978            .
     2979            sage: x = x.binary_search_insert("b"); x
     2980            b[., .]
     2981            sage: x = x.binary_search_insert("d"); x
     2982            b[., d[., .]]
     2983            sage: x = x.binary_search_insert("e"); x
     2984            b[., d[., e[., .]]]
     2985            sage: x = x.binary_search_insert("a"); x
     2986            b[a[., .], d[., e[., .]]]
     2987            sage: x = x.binary_search_insert("b"); x
     2988            b[a[., b[., .]], d[., e[., .]]]
     2989            sage: x = x.binary_search_insert("d"); x
     2990            b[a[., b[., .]], d[d[., .], e[., .]]]
     2991            sage: x = x.binary_search_insert("a"); x
     2992            b[a[a[., .], b[., .]], d[d[., .], e[., .]]]
     2993            sage: x = x.binary_search_insert("c"); x
     2994            b[a[a[., .], b[., .]], d[d[c[., .], .], e[., .]]]
     2995
     2996        Other examples::
     2997
    27952998            sage: LBT = LabelledBinaryTree
    27962999            sage: LBT(None).binary_search_insert(3)
    27973000            3[., .]
    class LabelledBinaryTree(AbstractLabelle 
    28163019                fils = self[1].binary_search_insert(letter)
    28173020                return LT([self[0], fils], label=self.label())
    28183021
     3022    def semistandard_insert(self, letter):
     3023        """
     3024        Return the result of inserting a letter ``letter`` into the
     3025        semistandard tree ``self`` using the bumping algorithm.
     3026
     3027        INPUT:
     3028
     3029        - ``letter`` -- any object comparable with the labels of ``self``
     3030
     3031        OUTPUT:
     3032
     3033        The semistandard tree ``self`` with ``letter`` inserted into it
     3034        according to the bumping algorithm.
     3035
     3036        .. NOTE:: ``self`` is supposed to be a semistandard tree.
     3037                  This is not being checked!
     3038
     3039        A semistandard tree is defined to be a labelled binary tree
     3040        such that for each node `n` with label `x`, every descendant of
     3041        the left child of `n` has a label `> x`, and every descendant
     3042        of the right child of `n` has a label `\geq x`. (Here, only
     3043        nodes count as descendants, and every node counts as its own
     3044        descendant too.) Leaves are assumed to have no labels.
     3045
     3046        Given a semistandard tree `t` and a letter `i`, the result of
     3047        inserting `i` into `t` (denoted `Ins(i, t)` in the following)
     3048        is defined recursively as follows:
     3049
     3050        - If `t` is empty, then `Ins(i, t)` is the tree with one node
     3051          only, and this node is labelled with `i`.
     3052
     3053        - Otherwise, let `j` be the label of the root of `t`. If
     3054          `i \geq j`, then `Ins(i, t)` is obtained by replacing the
     3055          right child of `t` by `Ins(i, r)` in `t`, where `r` denotes
     3056          the right child of `t`. If `i < j`, then `Ins(i, t)` is
     3057          obtained by replacing the label at the root of `t` by `i`,
     3058          and replacing the left child of `t` by `Ins(j, l)`
     3059          in `t`, where `l` denotes the left child of `t`.
     3060
     3061        This algorithm is similar to the Robinson-Schensted-Knuth
     3062        algorithm for semistandard Young tableaux.
     3063
     3064        AUTHORS:
     3065
     3066        - Darij Grinberg (10 Nov 2013).
     3067
     3068        EXAMPLES::
     3069
     3070            sage: LBT = LabelledBinaryTree
     3071            sage: x = LBT(None)
     3072            sage: x
     3073            .
     3074            sage: x = x.semistandard_insert("b"); x
     3075            b[., .]
     3076            sage: x = x.semistandard_insert("d"); x
     3077            b[., d[., .]]
     3078            sage: x = x.semistandard_insert("e"); x
     3079            b[., d[., e[., .]]]
     3080            sage: x = x.semistandard_insert("a"); x
     3081            a[b[., .], d[., e[., .]]]
     3082            sage: x = x.semistandard_insert("b"); x
     3083            a[b[., .], b[d[., .], e[., .]]]
     3084            sage: x = x.semistandard_insert("d"); x
     3085            a[b[., .], b[d[., .], d[e[., .], .]]]
     3086            sage: x = x.semistandard_insert("a"); x
     3087            a[b[., .], a[b[d[., .], .], d[e[., .], .]]]
     3088            sage: x = x.semistandard_insert("c"); x
     3089            a[b[., .], a[b[d[., .], .], c[d[e[., .], .], .]]]
     3090
     3091        Other examples::
     3092
     3093            sage: LBT = LabelledBinaryTree
     3094            sage: LBT(None).semistandard_insert(3)
     3095            3[., .]
     3096            sage: LBT([], label = 1).semistandard_insert(3)
     3097            1[., 3[., .]]
     3098            sage: LBT([], label = 3).semistandard_insert(1)
     3099            1[3[., .], .]
     3100            sage: res = LBT(None)
     3101            sage: for i in [3,1,5,2,4,6]:
     3102            ....:     res = res.semistandard_insert(i)
     3103            sage: res
     3104            1[3[., .], 2[5[., .], 4[., 6[., .]]]]
     3105        """
     3106        LT = self.parent()._element_constructor_
     3107        if not self:
     3108            return LT([], label = letter)
     3109        else:
     3110            root_label = self.label()
     3111            if letter < root_label:
     3112                fils = self[0].semistandard_insert(root_label)
     3113                return LT([fils, self[1]], label=letter)
     3114            else:
     3115                fils = self[1].semistandard_insert(letter)
     3116                return LT([self[0], fils], label=root_label)
     3117
    28193118    def right_rotate(self):
    28203119        r"""
    28213120        Return the result of right rotation applied to the labelled
    28223121        binary tree ``self``.
    28233122
    28243123        Right rotation on labelled binary trees is defined as
    2825         follows: Let `T` be a nonempty labelled binary tree such
    2826         that the left child of the root of `T` is a node. Let
     3124        follows: Let `T` be a labelled binary tree such that the
     3125        left child of the root of `T` is a node. Let
    28273126        `C` be the right child of the root of `T`, and let `A`
    28283127        and `B` be the left and right children of the left child
    28293128        of the root of `T`. (Keep in mind that nodes of trees are
    class LabelledBinaryTree(AbstractLabelle 
    28313130        descendants.) Furthermore, let `y` be the label at the
    28323131        root of `T`, and `x` be the label at the left child of the
    28333132        root of `T`.
    2834         Then, the right rotation of `T` is the nonempty labelled
    2835         binary tree in which the root is labelled `x`, the left
    2836         child of the root is `A`, whereas the right child of the
    2837         root is a node labelled `y` whose left and right children
    2838         are `B` and `C`. In pictures::
     3133        Then, the right rotation of `T` is the labelled binary
     3134        tree in which the root is labelled `x`, the left child of
     3135        the root is `A`, whereas the right child of the root is a
     3136        node labelled `y` whose left and right children are `B`
     3137        and `C`. In pictures::
    28393138
    28403139            |     y                      x     |
    28413140            |    / \                    / \    |
    class LabelledBinaryTree(AbstractLabelle 
    28553154            x[A[., .], y[B[., .], C[., .]]]
    28563155        """
    28573156        B = self.parent()._element_constructor_
    2858         return B([
    2859             self[0][0],
    2860             B([self[0][1], self[1]], self.label())
    2861         ], self[0].label())
     3157        s0 = self[0]
     3158        return B([s0[0], B([s0[1], self[1]], self.label())], s0.label())
    28623159
    28633160    def left_rotate(self):
    28643161        r"""
    class LabelledBinaryTree(AbstractLabelle 
    28663163        binary tree ``self``.
    28673164
    28683165        Left rotation on labelled binary trees is defined as
    2869         follows: Let `T` be a nonempty labelled binary tree such
    2870         that the right child of the root of `T` is a node. Let
     3166        follows: Let `T` be a labelled binary tree such that the
     3167        right child of the root of `T` is a node. Let
    28713168        `A` be the left child of the root of `T`, and let `B`
    28723169        and `C` be the left and right children of the right child
    28733170        of the root of `T`. (Keep in mind that nodes of trees are
    class LabelledBinaryTree(AbstractLabelle 
    28753172        descendants.) Furthermore, let `x` be the label at the
    28763173        root of `T`, and `y` be the label at the right child of the
    28773174        root of `T`.
    2878         Then, the left rotation of `T` is the nonempty labelled
    2879         binary tree in which the root is labelled `y`, the right
    2880         child of the root is `C`, whereas the left child of the
    2881         root is a node labelled `x` whose left and right children
    2882         are `A` and `B`. In pictures::
     3175        Then, the left rotation of `T` is the labelled binary tree
     3176        in which the root is labelled `y`, the right child of the
     3177        root is `C`, whereas the left child of the root is a node
     3178        labelled `x` whose left and right children are `A` and `B`.
     3179        In pictures::
    28833180
    28843181           |     y                    x     |
    28853182           |    / \                  / \    |
    class LabelledBinaryTree(AbstractLabelle 
    28993196            True
    29003197        """
    29013198        B = self.parent()._element_constructor_
    2902         return B([
    2903             B([self[0], self[1][0]], self.label()),
    2904             self[1][1]
    2905         ], self[1].label())
     3199        s1 = self[1]
     3200        return B([B([self[0], s1[0]], self.label()), s1[1]], s1.label())
    29063201
    29073202    def heap_insert(self, l):
    29083203        r"""
    29093204        Return the result of inserting a letter ``l`` into the binary
    29103205        heap (tree) ``self``.
    29113206
    2912         Roughly, a binary heap will be a labelled complete binary tree
    2913         such that for each node the label is greater or equal to the
    2914         label of each of its children.
     3207        A binary heap is a labelled complete binary tree such that for
     3208        each node, the label at the node is greater or equal to the
     3209        label of each of its child nodes. (More precisely, this is
     3210        called a max-heap.)
    29153211
    29163212        For example::
    29173213
    class LabelledBinaryTree(AbstractLabelle 
    29233219
    29243220        is a binary heap.
    29253221
     3222        See :wikipedia:`Binary_heap#Insert` for a description of how to
     3223        insert a letter into a binary heap. The result is another binary
     3224        heap.
     3225
    29263226        INPUT:
    29273227
    2928         - ``letter`` -- any object comparable with the label of ``self``
     3228        - ``letter`` -- any object comparable with the labels of ``self``
    29293229
    29303230        .. NOTE::
    29313231
    class LabelledBinaryTree(AbstractLabelle 
    29793279            # we insert in L
    29803280            return B([L.heap_insert(label_insert), R], label_root)
    29813281        # else ==> dL == dR
    2982         # if R is perfect we have to insert on the most left leaf
     3282        # if R is perfect we have to insert on the leftmost leaf
    29833283        if R.is_perfect():
    29843284            # ## TODO:: can be optimized...
    29853285            return B([L.heap_insert(label_insert), R], label_root)
    class LabelledBinaryTree(AbstractLabelle 
    29923292class LabelledBinaryTrees(LabelledOrderedTrees):
    29933293    """
    29943294    This is a parent stub to serve as a factory class for trees with various
    2995     labels constraints
     3295    labels constraints.
    29963296    """
    29973297    def _repr_(self):
    29983298        """
    class LabelledBinaryTrees(LabelledOrdere 
    30053305
    30063306    def _an_element_(self):
    30073307        """
    3008         Return a labelled binary tree
     3308        Return a labelled binary tree.
    30093309
    30103310        EXAMPLE::
    30113311
    class LabelledBinaryTrees(LabelledOrdere 
    30203320
    30213321    def unlabelled_trees(self):
    30223322        """
    3023         Return the set of unlabelled trees associated to ``self``
     3323        Return the set of unlabelled trees associated to ``self``.
    30243324
    30253325        EXAMPLES::
    30263326
    class LabelledBinaryTrees(LabelledOrdere 
    30443344
    30453345    def labelled_trees(self):
    30463346        """
    3047         Return the set of labelled trees associated to ``self``
     3347        Return the set of labelled trees associated to ``self``.
    30483348
    30493349        EXAMPLES::
    30503350
    class LabelledBinaryTrees(LabelledOrdere 
    30783378#     sage: BTsp_to_bintrees(BT.isotypes(range(5))[0])
    30793379#     [., [., [., [., [., .]]]]]
    30803380#     sage: def spls(size):
    3081 #     ...    return map(BTsp_to_bintrees, BT.isotypes(range(size)).list())
     3381#     ....:     return map(BTsp_to_bintrees, BT.isotypes(range(size)).list())
    30823382#     sage: spls(3)
    30833383#     [[., [., [., .]]], [., [[., .], .]], [[., .], [., .]], [[., [., .]], .], [[[., .], .], .]]
    30843384#     sage: all(spls(i) == BinaryTrees(i).list() for i in range(5))
  • sage/combinat/ordered_tree.py

    diff --git a/sage/combinat/ordered_tree.py b/sage/combinat/ordered_tree.py
    a b class OrderedTree(AbstractClonableTree,  
    200200    @lazy_class_attribute
    201201    def _auto_parent(cls):
    202202        """
    203         The automatic parent of the element of this class
     203        The automatic parent of the elements of this class.
    204204
    205205        When calling the constructor of an element of this class, one needs a
    206206        parent. This class attribute specifies which parent is used.
    class OrderedTrees(UniqueRepresentation, 
    574574        TEST::
    575575
    576576            sage: (OrderedTrees().leaf() is
    577             ...    sage.combinat.ordered_tree.OrderedTrees_all().leaf())
     577            ....:     sage.combinat.ordered_tree.OrderedTrees_all().leaf())
    578578            True
    579579        """
    580580        return self([])
    class OrderedTrees_all(DisjointUnionEnum 
    675675
    676676from sage.misc.lazy_attribute import lazy_attribute
    677677from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
    678 from combinat import catalan_number
    679678from sage.combinat.composition import Compositions
    680679from sage.combinat.cartesian_product import CartesianProduct
    681680#################################################################
    class OrderedTrees_size(OrderedTrees): 
    741740        """
    742741        The cardinality of ``self``
    743742
    744         This is a Catalan number
     743        This is a Catalan number.
    745744
    746745        TESTS::
    747746
    class OrderedTrees_size(OrderedTrees): 
    755754        if self._size == 0:
    756755            return Integer(0)
    757756        else:
     757            from combinat import catalan_number
    758758            return catalan_number(self._size-1)
    759759
    760760    def __iter__(self):
    class OrderedTrees_size(OrderedTrees): 
    833833
    834834class LabelledOrderedTree(AbstractLabelledClonableTree, OrderedTree):
    835835    """
    836     Labelled ordered trees
     836    Labelled ordered trees.
    837837
    838838    A labelled ordered tree is an ordered tree with a label attached at each
    839839    node.
    class LabelledOrderedTree(AbstractLabell 
    878878    @lazy_class_attribute
    879879    def _auto_parent(cls):
    880880        """
    881         The automatic parent of the element of this class
     881        The automatic parent of the elements of this class.
    882882
    883883        When calling the constructor of an element of this class, one needs a
    884884        parent. This class attribute specifies which parent is used.
    class LabelledOrderedTree(AbstractLabell 
    889889            Labelled ordered trees
    890890            sage: LabelledOrderedTree([], label = 3).parent()
    891891            Labelled ordered trees
    892          """
     892        """
    893893        return LabelledOrderedTrees()
    894894
    895895    _UnLabelled = OrderedTree
    from sage.rings.infinity import Infinity 
    899899class LabelledOrderedTrees(UniqueRepresentation, Parent):
    900900    """
    901901    This is a parent stub to serve as a factory class for trees with various
    902     labels constraints
     902    label constraints.
    903903
    904904    EXAMPLES::
    905905
    class LabelledOrderedTrees(UniqueReprese 
    935935
    936936    def cardinality(self):
    937937        """
    938         Return the cardinality of `self`
     938        Return the cardinality of `self`.
    939939
    940940        EXAMPLE::
    941941
  • sage/combinat/tools.py

    diff --git a/sage/combinat/tools.py b/sage/combinat/tools.py
    a b Tools 
    1717#*****************************************************************************
    1818
    1919def transitive_ideal(f, x):
    20     """
    21     Given an initial value x and a successor function f, return a list
    22     containing x and all of its successors. The successor function
    23     should return a list of all the successors of f.
    24    
    25     Note that if x has an infinite number of successors,
    26     transitive_ideal won't return.
    27    
     20    r"""
     21    Return a list of all elements reachable from `x` in the abstract
     22    reduction system whose reduction relation is given by the function
     23    `f`.
     24
     25    In more elementary terms:
     26    If `S` is a set, and `f` is a function sending every element of `S`
     27    to a list of elements of `S`, then we can define a digraph on the
     28    vertex set `S` by drawing an edge from `s` to `t` for every
     29    `s \in S` and every `t \in f(s)`.
     30    If `x \in S`, then an element `y \in S` is said to be reachable
     31    from `x` if there is a path `x \to y` in this graph.
     32    Given `f` and `x`, this method computes the list of all elements of
     33    `S` reachable from `x`.
     34
     35    Note that if there are infinitely many such elements, then this
     36    method will never halt.
     37
    2838    EXAMPLES::
    29    
     39
    3040        sage: f = lambda x: [x-1] if x > 0 else []
    3141        sage: sage.combinat.tools.transitive_ideal(f, 10)
    3242        [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  • sage/combinat/words/shuffle_product.py

    diff --git a/sage/combinat/words/shuffle_product.py b/sage/combinat/words/shuffle_product.py
    a b from sage.combinat.composition import Co 
    2525
    2626class ShuffleProduct_w1w2(CombinatorialClass):
    2727    def __init__(self, w1, w2):
    28         """
     28        r"""
     29        The shuffle product of the two words ``w1`` and ``w2``.
     30
     31        If `u` and `v` are two words, then the *shuffle product* of
     32        `u` and `v` is a certain multiset of words defined as follows:
     33        Let `a` and `b` be the lengths of `u` and `v`, respectively.
     34        For every `a`-element subset `I` of `\{1, 2, \cdots, a+b\}`,
     35        let `w(I)` be the length-`a+b` word such that:
     36
     37        - for every `1 \leq k \leq a`, the `i_k`-th letter of `w(I)`
     38          is the `k`-th letter of `u`, where `i_k` is the
     39          `k`-th smallest element of `I`;
     40
     41        - for every `1 \leq l \leq b`, the `j_l`-th letter of `w(I)`
     42          is the `l`-th letter of `v`, where `j_l` is the
     43          `l`-th smallest element of
     44          `\{1, 2, \cdots, a+b\} \setminus I`.
     45
     46        The shuffle product of `u` and `v` is then the multiset of
     47        all `w(I)` with `I` ranging over the `a`-element subsets of
     48        `\{1, 2, \cdots, a+b\}`.
     49
    2950        EXAMPLES::
    3051
    3152            sage: from sage.combinat.words.shuffle_product import ShuffleProduct_w1w2
    3253            sage: W = Words([1,2,3,4])
    3354            sage: s = ShuffleProduct_w1w2(W([1,2]),W([3,4]))
     55            sage: sorted(list(s))
     56            [word: 1234, word: 1324, word: 1342, word: 3124, word: 3142, word: 3412]
    3457            sage: s == loads(dumps(s))
    3558            True
     59
     60            sage: s = ShuffleProduct_w1w2(W([1,4,3]),W([2]))
     61            sage: sorted(list(s))
     62            [word: 1243, word: 1423, word: 1432, word: 2143]
     63
     64            sage: s = ShuffleProduct_w1w2(W([1,4,3]),W([]))
     65            sage: sorted(list(s))
     66            [word: 143]
    3667        """
    3768        self._w1 = w1
    3869        self._w2 = w2
    class ShuffleProduct_w1w2(CombinatorialC 
    95126        return len(wx) == 0
    96127
    97128    def cardinality(self):
    98         """
    99         Returns the number of words in the shuffle product
    100         of w1 and w2.
     129        r"""
     130        Return the number of words in the shuffle product
     131        of ``w1`` and ``w2``.
    101132
    102         It is given by binomial(len(w1)+len(w2), len(w1)).
     133        It is given by `\binom{l_1+l_2}{l_1}`, where `l_1` is the length of
     134        ``w1`` and where `l_2` is the length of ``w2``.
    103135
    104136        EXAMPLES::
    105137
    class ShuffleProduct_shifted(ShuffleProd 
    224256class ShuffleProduct_overlapping_r(CombinatorialClass):
    225257    def __init__(self, w1, w2, r):
    226258        """
     259        The overlapping shuffle product of the two words ``w1`` and ``w2``
     260        with precisely ``r`` overlaps.
     261
     262        See :class:`ShuffleProduct_overlapping` for a definition.
     263
    227264        EXAMPLES::
    228265
    229266            sage: from sage.combinat.words.shuffle_product import ShuffleProduct_overlapping_r
    230             sage: w, u = map(Words("abcdef"), ["ab", "cd"])
     267            sage: w, u = map(Words(range(20)), [[2, 9], [9, 1]])
    231268            sage: S = ShuffleProduct_overlapping_r(w,u,1)
    232269            sage: S == loads(dumps(S))
    233270            True
    class ShuffleProduct_overlapping_r(Combi 
    246283        EXAMPLES::
    247284
    248285            sage: from sage.combinat.words.shuffle_product import ShuffleProduct_overlapping_r
    249             sage: w, u = map(Words("abcdef"), ["ab", "cd"])
     286            sage: w, u = map(Words(range(20)), [[2, 9], [9, 1]])
    250287            sage: ShuffleProduct_overlapping_r(w,u,1).__repr__()
    251             'Overlapping shuffle product of word: ab and word: cd with 1 overlaps'
     288            'Overlapping shuffle product of word: 29 and word: 91 with 1 overlaps'
    252289        """
    253290        return "Overlapping shuffle product of %s and %s with %s overlaps"%(repr(self._w1), repr(self._w2), self.r)
    254291
    class ShuffleProduct_overlapping_r(Combi 
    321358
    322359class ShuffleProduct_overlapping(CombinatorialClass):
    323360    def __init__(self, w1, w2):
    324         """
     361        r"""
     362        The overlapping shuffle product of the two words ``w1`` and
     363        ``w2``.
     364
     365        If `u` and `v` are two words whose letters belong to an
     366        additive monoid or to another kind of alphabet on which addition
     367        is well-defined, then the *overlapping shuffle product* of
     368        `u` and `v` is a certain multiset of words defined as follows:
     369        Let `a` and `b` be the lengths of `u` and `v`, respectively.
     370        Let `A` be the set `\{(0, 1), (0, 2), \cdots, (0, a)\}`, and
     371        let `B` be the set `\{(1, 1), (1, 2), \cdots, (1, b)\}`.
     372        Notice that the sets `A` and `B` are disjoint. Let `p` be the
     373        map from `A \cup B` to the set of all letters which sends
     374        every `(0, i)` to the `i`-th letter of `u`, and every `(1, j)`
     375        to the `j`-th letter of `v`. For every nonnegative integer `c`
     376        and every surjective map
     377        `f : A \cup B \to \{ 1, 2, \cdots, c \}` for which both
     378        restrictions `f \mid_A` and `f \mid_B` are injective, let
     379        `w(f)` be the length-`c` word such that for every
     380        `1 \leq k \leq c`, the `k`-th letter of `w(f)` equals
     381        `\sum_{j \in f^{-1}(k)} p(j)` (this sum always has either
     382        one or two addends). The overlapping shuffle product of `u`
     383        and `v` is then the multiset of all `w(f)` with `c` ranging
     384        over all nonnegative integers and `f` ranging
     385        over the surjective maps
     386        `f : A \cup B \to \{ 1, 2, \cdots, c \}` for which both
     387        restrictions `f \mid_A` and `f \mid_B` are injective.
     388
     389        If one restricts `c` to a particular fixed nonnegative
     390        integer, then the multiset is instead called the *overlapping
     391        shuffle product with precisely `a + b - c` overlaps*. This is
     392        nonempty only if `\max \{a, b\} \leq c \leq a + b`.
     393
     394        If `c = a + b`, then the overlapping shuffle product with
     395        precisely `a + b - c` overlaps is plainly the shuffle product
     396        (:class:`ShuffleProduct_w1w2`).
     397
    325398        EXAMPLES::
    326399
    327400            sage: from sage.combinat.words.shuffle_product import ShuffleProduct_overlapping
    328             sage: w, u = map(Words("abcdef"), ["ab", "cd"])
     401            sage: w, u = map(Words(range(20)), [[2, 9], [9, 1]])
    329402            sage: S = ShuffleProduct_overlapping(w,u)
     403            sage: sorted([list(i) for i in list(S)])
     404            [[2, 9, 1, 9],
     405             [2, 9, 9, 1],
     406             [2, 9, 9, 1],
     407             [2, 9, 10],
     408             [2, 18, 1],
     409             [9, 1, 2, 9],
     410             [9, 2, 1, 9],
     411             [9, 2, 9, 1],
     412             [9, 2, 10],
     413             [9, 3, 9],
     414             [11, 1, 9],
     415             [11, 9, 1],
     416             [11, 10]]
    330417            sage: S == loads(dumps(S))
    331418            True
    332419        """
    class ShuffleProduct_overlapping(Combina 
    338425        EXAMPLES::
    339426
    340427            sage: from sage.combinat.words.shuffle_product import ShuffleProduct_overlapping
    341             sage: w, u = map(Words("abcdef"), ["ab", "cd"])
     428            sage: w, u = map(Words(range(20)), [[2, 9], [9, 1]])
    342429            sage: ShuffleProduct_overlapping(w,u).__repr__()
    343             'Overlapping shuffle product of word: ab and word: cd'
     430            'Overlapping shuffle product of word: 29 and word: 91'
    344431        """
    345432        return "Overlapping shuffle product of %s and %s"%(repr(self._w1), repr(self._w2))
    346433