Ticket #9890: trac_9890_review.patch

File trac_9890_review.patch, 32.5 KB (added by chapoton, 7 years ago)
  • sage/combinat/perfect_matching.py

    # HG changeset patch
    # User Frederic Chapoton <chapoton at math.univ-lyon1.fr>
    # Date 1368819378 -7200
    # Node ID e1bd7bedc6784d47392b50195e80b43486ffa634
    # Parent  8708a5383e0f4e1130a037a7389118dd9c74e3fa
    trac #9890 review and remove <>
    
    diff --git a/sage/combinat/perfect_matching.py b/sage/combinat/perfect_matching.py
    a b EXAMPLES: 
    1515
    1616    Create a perfect matching::
    1717
    18         sage: m=PerfectMatching([('a','e'),('b','c'),('d','f')]);m
     18        sage: m = PerfectMatching([('a','e'),('b','c'),('d','f')]);m
    1919        [('a', 'e'), ('b', 'c'), ('d', 'f')]
    2020
    2121    Count its crossings, if the ground set is totally ordered::
    2222
    23         sage: n=PerfectMatching([3,8,1,7,6,5,4,2]); n
     23        sage: n = PerfectMatching([3,8,1,7,6,5,4,2]); n
    2424        [(1, 3), (2, 8), (4, 7), (5, 6)]
    2525        sage: n.number_of_crossings()
    2626        1
    REFERENCES: 
    4242       VII).
    4343
    4444    .. [CM] Benoit Collins, Sho Matsumoto, On some properties of
    45        orthogonal Weingarten functions, arXiv:0903.5143.
     45       orthogonal Weingarten functions, :arxiv:`0903.5143`.
    4646"""
    4747
    48 #***************************************************************************** 
     48#*****************************************************************************
    4949#       Copyright (C) 2010 Valentin Feray <feray@labri.fr>
    5050#
    5151#  Distributed under the terms of the GNU General Public License (GPL)
    from sage.misc.misc_c import prod 
    6868from sage.matrix.constructor import Matrix
    6969from sage.combinat.combinatorial_map import combinatorial_map
    7070
     71
    7172class PerfectMatching(ElementWrapper):
    7273    r"""
    7374    Class of perfect matching.
    class PerfectMatching(ElementWrapper): 
    7576    An instance of the class can be created from a list of pairs or from a
    7677    fixed point-free involution as follows::
    7778
    78         sage: m=PerfectMatching([('a','e'),('b','c'),('d','f')]);m
     79        sage: m = PerfectMatching([('a','e'),('b','c'),('d','f')]);m
    7980        [('a', 'e'), ('b', 'c'), ('d', 'f')]
    80         sage: n=PerfectMatching([3,8,1,7,6,5,4,2]);n
     81        sage: n = PerfectMatching([3,8,1,7,6,5,4,2]);n
    8182        [(1, 3), (2, 8), (4, 7), (5, 6)]
    8283        sage: isinstance(m,PerfectMatching)
    8384        True
    8485
    85     The parent, which is the set of perfect matching of the ground set, is
    86     automaticly created::
     86    The parent, which is the set of perfect matchings of the ground set, is
     87    automatically created::
    8788
    8889        sage: n.parent()
    8990        Set of perfect matchings of {1, 2, 3, 4, 5, 6, 7, 8}
    class PerfectMatching(ElementWrapper): 
    9697
    9798    TESTS::
    9899
    99         sage: m=PerfectMatching([]); m
     100        sage: m = PerfectMatching([]); m
    100101        []
    101102        sage: m.parent()
    102103        Set of perfect matchings of {}
    class PerfectMatching(ElementWrapper): 
    109110    __metaclass__ = ClasscallMetaclass
    110111
    111112    @staticmethod
    112     def __classcall_private__(cls,p):
     113    def __classcall_private__(cls, p):
    113114        r"""
    114115        This function tries to recognize the input (it can be either a list or
    115116        a tuple of pairs, or a fix-point free involution given as a list or as
    class PerfectMatching(ElementWrapper): 
    119120
    120121        EXAMPLES::
    121122
    122             sage: m=PerfectMatching([('a','e'),('b','c'),('d','f')]);m
     123            sage: m = PerfectMatching([('a','e'),('b','c'),('d','f')]);m
    123124            [('a', 'e'), ('b', 'c'), ('d', 'f')]
    124125            sage: isinstance(m,PerfectMatching)
    125126            True
    126             sage: n=PerfectMatching([3, 8, 1, 7, 6, 5, 4, 2]);n
     127            sage: n = PerfectMatching([3, 8, 1, 7, 6, 5, 4, 2]);n
    127128            [(1, 3), (2, 8), (4, 7), (5, 6)]
    128129            sage: n.parent()
    129130            Set of perfect matchings of {1, 2, 3, 4, 5, 6, 7, 8}
    class PerfectMatching(ElementWrapper): 
    144145
    145146        TESTS::
    146147
    147              sage: m=PerfectMatching([('a','e'),('b','c'),('d','f')])
     148             sage: m = PerfectMatching([('a','e'),('b','c'),('d','f')])
    148149             sage: TestSuite(m).run()
    149              sage: m=PerfectMatching([])
     150             sage: m = PerfectMatching([])
    150151             sage: TestSuite(m).run()
    151152             sage: PerfectMatching(6)
    152153             Traceback (most recent call last):
    class PerfectMatching(ElementWrapper): 
    170171        # we have to extract from the argument p the set of objects of the
    171172        # matching and the list of pairs.
    172173        # First case: p is a list (resp tuple) of lists (resp tuple).
    173         if (isinstance(p,list) or isinstance(p,tuple)) and (
    174                 all([isinstance(x,list) or isinstance(x,tuple) for x in p])):
    175             objects=Set(flatten(p))
    176             data=(map(tuple,p))
     174        if (isinstance(p, list) or isinstance(p, tuple)) and (
     175                all([isinstance(x, list) or isinstance(x, tuple) for x in p])):
     176            objects = Set(flatten(p))
     177            data = (map(tuple, p))
    177178            #check if the data are correct
    178             if not all([len(t)==2 for t in data]):
    179                 raise ValueError, ("%s is not a valid perfect matching:\n"
    180                     "all elements of the list must be pairs"%p)
     179            if not all([len(t) == 2 for t in data]):
     180                raise ValueError("%s is not a valid perfect matching:\n"
     181                                 "all elements of the list must be pairs" % p)
    181182            if len(objects) < 2*len(data):
    182                 raise ValueError, ("%s is not a valid perfect matching:\n"
    183                     "there are some repetitions"%p)
     183                raise ValueError("%s is not a valid perfect matching:\n"
     184                                 "there are some repetitions" % p)
    184185        # Second case: p is a permutation or a list of integers, we have to
    185186        # check if it is a fix-point-free involution.
    186         elif ((isinstance(p,list) and
    187             all(map(lambda x: (isinstance(x,Integer) or isinstance(x,int)),p )))
    188             or isinstance(p,Permutation_class)):
    189             p=Permutation(p)
    190             n=len(p)
    191             if not(p.cycle_type()==[2 for i in range(n//2)]):
    192                 raise ValueError, ("The permutation p (= %s) is not a "
    193                         "fixed point free involution"%p)
    194             objects=Set(range(1,n+1))
    195             data=p.to_cycles()
     187        elif ((isinstance(p, list) and
     188               all(map(lambda x: (isinstance(x, Integer) or isinstance(x, int)), p)))
     189              or isinstance(p, Permutation_class)):
     190            p = Permutation(p)
     191            n = len(p)
     192            if not(p.cycle_type() == [2 for i in range(n//2)]):
     193                raise ValueError("The permutation p (= %s) is not a "
     194                                 "fixed point free involution" % p)
     195            objects = Set(range(1, n+1))
     196            data = p.to_cycles()
    196197        # Third case: p is already a perfect matching, we return p directly
    197         elif isinstance(p,PerfectMatching):
     198        elif isinstance(p, PerfectMatching):
    198199            return p
    199200        else:
    200             raise ValueError, "cannot convert p (= %s) to a PerfectMatching"%p
     201            raise ValueError("cannot convert p (= %s) to a PerfectMatching" % p)
    201202        # Finally, we create the parent and the element using the element
    202203        # class of the parent. Note: as this function is private, when we
    203204        # create an object via parent.element_class(...), __init__ is directly
    class PerfectMatching(ElementWrapper): 
    210211
    211212        EXAMPLES::
    212213
    213             sage: m=PerfectMatching([('a','e'),('b','c'),('d','f')]);m
     214            sage: m = PerfectMatching([('a','e'),('b','c'),('d','f')]);m
    214215            [('a', 'e'), ('b', 'c'), ('d', 'f')]
    215             sage: n=PerfectMatching([3,8,1,7,6,5,4,2]);n
     216            sage: n = PerfectMatching([3,8,1,7,6,5,4,2]);n
    216217            [(1, 3), (2, 8), (4, 7), (5, 6)]
    217218        """
    218         return '%s'%self.value
     219        return '%s' % self.value
    219220
    220221    def _latex_(self):
    221222        r"""
    class PerfectMatching(ElementWrapper): 
    243244
    244245        EXAMPLES::
    245246
    246             sage: m=PerfectMatching([('a','e'),('b','c'),('d','f')])
     247            sage: m = PerfectMatching([('a','e'),('b','c'),('d','f')])
    247248            sage: m.__hash__() #random
    248249            1053935254331348997
    249250            sage: hash(m) #indirect doctest #random
    250251
    251             sage: n=PerfectMatching([3,8,1,7,6,5,4,2])
     252            sage: n = PerfectMatching([3,8,1,7,6,5,4,2])
    252253            sage: hash(n) #indirect doctest #random
    253254            8097274995140737937
    254255        """
    255256        return hash(tuple(self.value))
    256257
    257     def __eq__(self,other):
     258    def __eq__(self, other):
    258259        r"""
    259260        Compares two perfect matchings
    260261
    261262        EXAMPLES::
    262263
    263             sage: m=PerfectMatching([('a','e'),('b','c'),('d','f')])
    264             sage: n=PerfectMatching([('c','b'),('d','f'),('e','a')])
    265             sage: n==m
     264            sage: m = PerfectMatching([('a','e'),('b','c'),('d','f')])
     265            sage: n = PerfectMatching([('c','b'),('d','f'),('e','a')])
     266            sage: n == m
    266267            True
    267             sage: n==PerfectMatching([('a','b'),('d','f'),('e','c')])
     268            sage: n == PerfectMatching([('a','b'),('d','f'),('e','c')])
    268269            False
    269270
    270271        """
    class PerfectMatching(ElementWrapper): 
    273274                return False
    274275        except AttributeError:
    275276            return False
    276         return Set(map(Set,self.value))==Set(map(Set,other.value))
     277        return Set(map(Set, self.value)) == Set(map(Set, other.value))
    277278
    278279    def size(self):
    279280        r"""
    class PerfectMatching(ElementWrapper): 
    283284
    284285        EXAMPLES::
    285286
    286             sage: m=PerfectMatching([(-3, 1), (2, 4), (-2, 7)]); m.size()
     287            sage: m = PerfectMatching([(-3, 1), (2, 4), (-2, 7)]); m.size()
    287288            6
    288289        """
    289290        return 2*len(self.value)
    class PerfectMatching(ElementWrapper): 
    294295
    295296        EXAMPLES::
    296297
    297             sage: m=PerfectMatching([(-3, 1), (2, 4), (-2, 7)]); m.partner(4)
     298            sage: m = PerfectMatching([(-3, 1), (2, 4), (-2, 7)]); m.partner(4)
    298299            2
    299             sage: n=PerfectMatching([('c','b'),('d','f'),('e','a')])
     300            sage: n = PerfectMatching([('c','b'),('d','f'),('e','a')])
    300301            sage: n.partner('c')
    301302            'b'
    302303        """
    303304        for i in range(self.size()):
    304             if self.value[i][0]==x:
     305            if self.value[i][0] == x:
    305306                return self.value[i][1]
    306             if self.value[i][1]==x:
     307            if self.value[i][1] == x:
    307308                return self.value[i][0]
    308         raise ValueError,"%s in not an element of the %s"%(x,self)
     309        raise ValueError("%s in not an element of the %s" % (x, self))
    309310
    310311    def conjugate_by_permutation(self, p):
    311312        r"""
    class PerfectMatching(ElementWrapper): 
    314315
    315316        EXAMPLE::
    316317
    317             sage: m=PerfectMatching([(1,4),(2,6),(3,5)])
     318            sage: m = PerfectMatching([(1,4),(2,6),(3,5)])
    318319            sage: m.conjugate_by_permutation(Permutation([4,1,5,6,3,2]))
    319320            [(4, 6), (1, 2), (5, 3)]
    320321
    class PerfectMatching(ElementWrapper): 
    323324            sage: PerfectMatching([]).conjugate_by_permutation(Permutation([]))
    324325            []
    325326        """
    326         return self.parent()(map(lambda t:tuple(map(p,t)),self.value))
     327        return self.parent()(map(lambda t: tuple(map(p, t)), self.value))
    327328
    328     def loops_iterator(self,other=None):
     329    def loops_iterator(self, other=None):
    329330        r"""
    330331        INPUT:
    331332
    class PerfectMatching(ElementWrapper): 
    342343
    343344        EXAMPLES::
    344345
    345             sage: o=PerfectMatching([(1, 7), (2, 4), (3, 8), (5, 6)])
    346             sage: p=PerfectMatching([(1, 6), (2, 7), (3, 4), (5, 8)])
    347             sage: it=o.loops_iterator(p)
     346            sage: o = PerfectMatching([(1, 7), (2, 4), (3, 8), (5, 6)])
     347            sage: p = PerfectMatching([(1, 6), (2, 7), (3, 4), (5, 8)])
     348            sage: it = o.loops_iterator(p)
    348349            sage: it.next()
    349350            [1, 7, 2, 4, 3, 8, 5, 6]
    350351            sage: it.next()
    class PerfectMatching(ElementWrapper): 
    353354            StopIteration
    354355        """
    355356        if other is None:
    356             other=self.parent().an_element()
    357         elif self.parent() <> other.parent():
    358             s="%s is not a matching of the ground set of %s"%(other,self)
    359             raise ValueError,s
    360         remain=flatten(self.value)
    361         while len(remain)>0:
    362             a=remain.pop(0)
    363             b=self.partner(a)
     357            other = self.parent().an_element()
     358        elif self.parent() != other.parent():
     359            s = "%s is not a matching of the ground set of %s" % (other, self)
     360            raise ValueError(s)
     361        remain = flatten(self.value)
     362        while len(remain) > 0:
     363            a = remain.pop(0)
     364            b = self.partner(a)
    364365            remain.remove(b)
    365             loop=[a,b]
    366             c=other.partner(b)
    367             while c<>a:
    368                 b=self.partner(c)
     366            loop = [a, b]
     367            c = other.partner(b)
     368            while c != a:
     369                b = self.partner(c)
    369370                remain.remove(c)
    370371                loop.append(c)
    371372                remain.remove(b)
    372373                loop.append(b)
    373                 c=other.partner(b)
     374                c = other.partner(b)
    374375            yield loop
    375376
    376     def loops(self,other=None):
     377    def loops(self, other=None):
    377378        r"""
    378379        INPUT:
    379380
    class PerfectMatching(ElementWrapper): 
    390391
    391392        EXAMPLES::
    392393
    393             sage: m=PerfectMatching([('a','e'),('b','c'),('d','f')])
    394             sage: n=PerfectMatching([('a','b'),('d','f'),('e','c')])
     394            sage: m = PerfectMatching([('a','e'),('b','c'),('d','f')])
     395            sage: n = PerfectMatching([('a','b'),('d','f'),('e','c')])
    395396            sage: m.loops(n)
    396397            [['a', 'e', 'c', 'b'], ['d', 'f']]
    397             sage: o=PerfectMatching([(1, 7), (2, 4), (3, 8), (5, 6)])
    398             sage: p=PerfectMatching([(1, 6), (2, 7), (3, 4), (5, 8)])
     398
     399            sage: o = PerfectMatching([(1, 7), (2, 4), (3, 8), (5, 6)])
     400            sage: p = PerfectMatching([(1, 6), (2, 7), (3, 4), (5, 8)])
    399401            sage: o.loops(p)
    400402            [[1, 7, 2, 4, 3, 8, 5, 6]]
    401403        """
    class PerfectMatching(ElementWrapper): 
    418420
    419421        EXAMPLES::
    420422
    421             sage: m=PerfectMatching([('a','e'),('b','c'),('d','f')])
    422             sage: n=PerfectMatching([('a','b'),('d','f'),('e','c')])
     423            sage: m = PerfectMatching([('a','e'),('b','c'),('d','f')])
     424            sage: n = PerfectMatching([('a','b'),('d','f'),('e','c')])
    423425            sage: m.loop_type(n)
    424426            [2, 1]
    425427
    426428        TESTS::
    427429
    428             sage: m=PerfectMatching([]); m.loop_type()
     430            sage: m = PerfectMatching([]); m.loop_type()
    429431            []
    430432        """
    431         return Partition(reversed(sorted([len(l)//2
    432             for l in self.loops_iterator(other)])))       
     433        return Partition(reversed(
     434                sorted([len(l)//2 for l in self.loops_iterator(other)])))
    433435
    434     def number_of_loops(self,other=None):
     436    def number_of_loops(self, other=None):
    435437        r"""
    436438        INPUT:
    437439
    class PerfectMatching(ElementWrapper): 
    447449
    448450        EXAMPLES::
    449451
    450             sage: m=PerfectMatching([('a','e'),('b','c'),('d','f')])
    451             sage: n=PerfectMatching([('a','b'),('d','f'),('e','c')])
     452            sage: m = PerfectMatching([('a','e'),('b','c'),('d','f')])
     453            sage: n = PerfectMatching([('a','b'),('d','f'),('e','c')])
    452454            sage: m.number_of_loops(n)
    453455            2
    454456        """
    class PerfectMatching(ElementWrapper): 
    462464        r"""
    463465        INPUT:
    464466
    465             A perfect matching on an *totally ordered* ground set.
     467            A perfect matching on a *totally ordered* ground set.
    466468
    467469        OUTPUT:
    468470
    class PerfectMatching(ElementWrapper): 
    474476
    475477        EXAMPLES::
    476478
    477             sage: n=PerfectMatching([3,8,1,7,6,5,4,2]); n
     479            sage: n = PerfectMatching([3,8,1,7,6,5,4,2]); n
    478480            [(1, 3), (2, 8), (4, 7), (5, 6)]
    479481            sage: it = n.crossings_iterator();
    480482            sage: it.next()
    class PerfectMatching(ElementWrapper): 
    484486            ...
    485487            StopIteration
    486488        """
    487         x=self.value[:]
    488         if len(x)==0:
     489        x = self.value[:]
     490        if len(x) == 0:
    489491            return
    490         (i,j)=x.pop(0)
    491         for (a,b) in x:
     492        (i, j) = x.pop(0)
     493        for (a, b) in x:
    492494            # if (i<a<j<b) or (i<b<j<a) or (j<a<i<b) or (j<b<i<a) or (
    493495            #        a<i<b<j) or (a<j<b<i) or (b<i<a<j) or (b<j<a<i):
    494             labij = sorted([a,b,i,j])
     496            labij = sorted([a, b, i, j])
    495497            posij = sorted([labij.index(i), labij.index(j)])
    496             if posij == [0,2] or posij == [1,3]:
    497                 yield ((i,j),(a,b))
     498            if posij == [0, 2] or posij == [1, 3]:
     499                yield ((i, j), (a, b))
    498500        for cr in PerfectMatchings(flatten(x))(x).crossings_iterator():
    499501            yield cr
    500502
    class PerfectMatching(ElementWrapper): 
    502504        r"""
    503505        INPUT:
    504506
    505             A perfect matching on an *totally ordered* ground set.
     507            A perfect matching on a *totally ordered* ground set.
    506508
    507509        OUTPUT:
    508510
    class PerfectMatching(ElementWrapper): 
    514516
    515517        EXAMPLES::
    516518
    517             sage: n=PerfectMatching([3,8,1,7,6,5,4,2]); n
     519            sage: n = PerfectMatching([3,8,1,7,6,5,4,2]); n
    518520            [(1, 3), (2, 8), (4, 7), (5, 6)]
    519521            sage: n.crossings()
    520522            [((1, 3), (2, 8))]
    521523
    522524        TESTS::
    523525
    524             sage: m=PerfectMatching([]); m.crossings()
     526            sage: m = PerfectMatching([]); m.crossings()
    525527            []
    526528        """
    527529        return list(self.crossings_iterator())
    class PerfectMatching(ElementWrapper): 
    530532        r"""
    531533        INPUT:
    532534
    533             A perfect matching on an *totally ordered* ground set.
     535            A perfect matching on a *totally ordered* ground set.
    534536
    535537        OUTPUT:
    536538
    class PerfectMatching(ElementWrapper): 
    541543
    542544        EXAMPLES::
    543545
    544             sage: n=PerfectMatching([3,8,1,7,6,5,4,2]); n
     546            sage: n = PerfectMatching([3,8,1,7,6,5,4,2]); n
    545547            [(1, 3), (2, 8), (4, 7), (5, 6)]
    546548            sage: n.number_of_crossings()
    547549            1
    class PerfectMatching(ElementWrapper): 
    556558        r"""
    557559        INPUT:
    558560
    559             A perfect matching on an *totally ordered* ground set.
     561            A perfect matching on a *totally ordered* ground set.
    560562
    561563        OUTPUT:
    562564
    class PerfectMatching(ElementWrapper): 
    567569
    568570        EXAMPLES::
    569571
    570             sage: n=PerfectMatching([3,8,1,7,6,5,4,2]); n
     572            sage: n = PerfectMatching([3,8,1,7,6,5,4,2]); n
    571573            [(1, 3), (2, 8), (4, 7), (5, 6)]
    572574            sage: n.is_non_crossing()
    573575            False
    class PerfectMatching(ElementWrapper): 
    586588        r"""
    587589        INPUT:
    588590
    589             A perfect matching on an *totally ordered* ground set.
     591            A perfect matching on a *totally ordered* ground set.
    590592
    591593        OUTPUT:
    592594
    class PerfectMatching(ElementWrapper): 
    598600
    599601        EXAMPLES::
    600602
    601             sage: n=PerfectMatching([(1, 6), (2, 7), (3, 5), (4, 8)])
     603            sage: n = PerfectMatching([(1, 6), (2, 7), (3, 5), (4, 8)])
    602604            sage: it = n.nestings_iterator();
    603605            sage: it.next()
    604606            ((1, 6), (3, 5))
    class PerfectMatching(ElementWrapper): 
    609611            ...
    610612            StopIteration
    611613        """
    612         x=self.value[:]
    613         if len(x)==0:
     614        x = self.value[:]
     615        if len(x) == 0:
    614616            return
    615         (i,j)=x.pop(0)
    616         for (a,b) in x:
     617        (i, j) = x.pop(0)
     618        for (a, b) in x:
    617619            # if (i<a<j<b) or (i<b<j<a) or (j<a<i<b) or (j<b<i<a) or (
    618620            #        a<i<b<j) or (a<j<b<i) or (b<i<a<j) or (b<j<a<i):
    619             labij = sorted([a,b,i,j])
     621            labij = sorted([a, b, i, j])
    620622            posij = sorted([labij.index(i), labij.index(j)])
    621             if posij == [0,3] or posij == [1,2]:
    622                 yield ((i,j),(a,b))
     623            if posij == [0, 3] or posij == [1, 2]:
     624                yield ((i, j), (a, b))
    623625        for nest in PerfectMatchings(flatten(x))(x).nestings_iterator():
    624626            yield nest
    625627
    class PerfectMatching(ElementWrapper): 
    627629        r"""
    628630        INPUT:
    629631
    630             A perfect matching on an *totally ordered* ground set.
     632            A perfect matching on a *totally ordered* ground set.
    631633
    632634        OUTPUT:
    633635
    class PerfectMatching(ElementWrapper): 
    639641
    640642        EXAMPLES::
    641643
    642             sage: m=PerfectMatching([(1, 6), (2, 7), (3, 5), (4, 8)])
     644            sage: m = PerfectMatching([(1, 6), (2, 7), (3, 5), (4, 8)])
    643645            sage: m.nestings()
    644646            [((1, 6), (3, 5)), ((2, 7), (3, 5))]
    645             sage: n=PerfectMatching([3,8,1,7,6,5,4,2]); n
     647
     648            sage: n = PerfectMatching([3,8,1,7,6,5,4,2]); n
    646649            [(1, 3), (2, 8), (4, 7), (5, 6)]
    647650            sage: n.nestings()
    648651            [((2, 8), (4, 7)), ((2, 8), (5, 6)), ((4, 7), (5, 6))]
    649652
    650653        TESTS::
    651654
    652             sage: m=PerfectMatching([]); m.nestings()
     655            sage: m = PerfectMatching([]); m.nestings()
    653656            []
    654657        """
    655658        return list(self.nestings_iterator())
    class PerfectMatching(ElementWrapper): 
    658661        r"""
    659662        INPUT:
    660663
    661             A perfect matching on an *totally ordered* ground set.
     664            A perfect matching on a *totally ordered* ground set.
    662665
    663666        OUTPUT:
    664667
    class PerfectMatching(ElementWrapper): 
    669672
    670673        EXAMPLES::
    671674
    672             sage: n=PerfectMatching([3,8,1,7,6,5,4,2]); n
     675            sage: n = PerfectMatching([3,8,1,7,6,5,4,2]); n
    673676            [(1, 3), (2, 8), (4, 7), (5, 6)]
    674677            sage: n.number_of_nestings()
    675678            3
    class PerfectMatching(ElementWrapper): 
    684687        r"""
    685688        INPUT:
    686689
    687             A perfect matching on an *totally ordered* ground set.
     690            A perfect matching on a *totally ordered* ground set.
    688691
    689692        OUTPUT:
    690693
    class PerfectMatching(ElementWrapper): 
    695698
    696699        EXAMPLES::
    697700
    698             sage: n=PerfectMatching([3,8,1,7,6,5,4,2]); n
     701            sage: n = PerfectMatching([3,8,1,7,6,5,4,2]); n
    699702            [(1, 3), (2, 8), (4, 7), (5, 6)]
    700703            sage: n.is_non_nesting()
    701704            False
    class PerfectMatching(ElementWrapper): 
    710713        else:
    711714            return False
    712715
    713     def Weingarten_function(self,d,other=None):
     716    def Weingarten_function(self, d, other=None):
    714717        r"""
    715718        Returns the Weingarten function of two pairings.
    716719
    717         This function is the value of some integrals over the orhtogonal
     720        This function is the value of some integrals over the orthogonal
    718721        groups `O_N`.  With the convention of [CM]_, the method returns
    719722        `Wg^{O(d)}(other,self)`.
    720723
    class PerfectMatching(ElementWrapper): 
    722725
    723726            sage: var('N')
    724727            N
    725             sage: m=PerfectMatching([(1,3),(2,4)])
    726             sage: n=PerfectMatching([(1,2),(3,4)])
     728            sage: m = PerfectMatching([(1,3),(2,4)])
     729            sage: n = PerfectMatching([(1,2),(3,4)])
    727730            sage: factor(m.Weingarten_function(N,n))
    728731            -1/((N - 1)*(N + 2)*N)
    729732        """
    730733        if other is None:
    731734            other = self.parent().an_element()
    732         W=self.parent().Weingarten_matrix(d)
     735        W = self.parent().Weingarten_matrix(d)
    733736        return W[other.rank()][self.rank()]
    734737
    735738    def to_graph(self):
    class PerfectMatching(ElementWrapper): 
    751754        """
    752755        from sage.graphs.graph import Graph
    753756        G = Graph()
    754         for a,b in self.value:
    755             G.add_edge((a,b))
     757        for a, b in self.value:
     758            G.add_edge((a, b))
    756759        return G
    757760
    758761    @combinatorial_map(name='to permutation')
    class PerfectMatching(ElementWrapper): 
    776779        from sage.combinat.permutation import Permutation
    777780        return Permutation(self.__dict__['value'])
    778781
    779 class PerfectMatchings(UniqueRepresentation,Parent):
     782
     783class PerfectMatchings(UniqueRepresentation, Parent):
    780784    r"""
    781785    Class of perfect matchings of a ground set. At the creation, the set
    782786    can be given as any iterable object. If the argument is an integer `n`, it
    783787    will be transformed into `[1 .. n]`::
    784788
    785         sage: M=PerfectMatchings(6);M
     789        sage: M = PerfectMatchings(6);M
    786790        Set of perfect matchings of {1, 2, 3, 4, 5, 6}
    787791        sage: PerfectMatchings([-1, -3, 1, 2])
    788792        Set of perfect matchings of {1, 2, -3, -1}
    class PerfectMatchings(UniqueRepresentat 
    794798        [[(1, 2), (3, 4)], [(1, 3), (2, 4)], [(1, 4), (2, 3)]]
    795799        sage: PerfectMatchings(8).cardinality()
    796800        105
    797         sage: M=PerfectMatchings(('a', 'e', 'b', 'f', 'c', 'd'))
     801        sage: M = PerfectMatchings(('a', 'e', 'b', 'f', 'c', 'd'))
    798802        sage: M.an_element()
    799803        [('a', 'b'), ('f', 'e'), ('c', 'd')]
    800804        sage: all([PerfectMatchings(i).an_element() in PerfectMatchings(i)
    class PerfectMatchings(UniqueRepresentat 
    824828            {'a', 'c', 'b', 'e'}
    825829        """
    826830        # if the argument is a python int n, we replace it by the list [1 .. n]
    827         if isinstance(objects,int):
    828             objects=range(1,objects+1)
     831        if isinstance(objects, int):
     832            objects = range(1, objects+1)
    829833        # same thing if the argument is a sage integer.
    830         elif isinstance(objects,Integer):
    831             objects=range(1,objects+1)
     834        elif isinstance(objects, Integer):
     835            objects = range(1, objects+1)
    832836        # Finally, if it is iterable, we return the corresponding set.
    833837        # Note that it is important to return a hashable object here (in
    834838        # particular, NOT A LIST), see comment below.
    835         if not hasattr(objects,'__iter__'):
    836             raise ValueError, "do not know how to construct a set of matchings from %s (it must be iterable)"
     839        if not hasattr(objects, '__iter__'):
     840            raise ValueError("do not know how to construct a set of matchings from %s (it must be iterable)")
    837841        return Set(objects)
    838842
    839843    @staticmethod
    class PerfectMatchings(UniqueRepresentat 
    844848
    845849        EXAMPLES::
    846850
    847             sage: M=PerfectMatchings(6);M
     851            sage: M = PerfectMatchings(6);M
    848852            Set of perfect matchings of {1, 2, 3, 4, 5, 6}
    849853            sage: PerfectMatchings([-1, -3, 1, 2])
    850854            Set of perfect matchings of {1, 2, -3, -1}
    class PerfectMatchings(UniqueRepresentat 
    853857        it does not create a new object, but returns the already existing
    854858        one::
    855859
    856             sage: N=PerfectMatchings((2, 3, 5, 4, 1, 6))
     860            sage: N = PerfectMatchings((2, 3, 5, 4, 1, 6))
    857861            sage: N is M
    858862            True
    859863        """
    class PerfectMatchings(UniqueRepresentat 
    862866        # second argument, i.e. the output of _parse_input, must be hashable)
    863867        #    - look for a place in memory and call the __init__ function
    864868        return super(PerfectMatchings, cls).__classcall__(
    865                          cls, cls._parse_input(objects))
     869            cls, cls._parse_input(objects))
    866870
    867     def __init__(self,objects):
     871    def __init__(self, objects):
    868872        r"""
    869873        See :meth:`__classcall__`
    870874
    871875        TEST::
    872876
    873             sage: M=PerfectMatchings(6)
     877            sage: M = PerfectMatchings(6)
    874878            sage: TestSuite(M).run()
    875879        """
    876         self._objects=objects
    877         Parent.__init__(self, category = FiniteEnumeratedSets())
     880        self._objects = objects
     881        Parent.__init__(self, category=FiniteEnumeratedSets())
    878882
    879883    def _repr_(self):
    880884        r"""
    class PerfectMatchings(UniqueRepresentat 
    885889            sage: PerfectMatchings([-1, -3, 1, 2])
    886890            Set of perfect matchings of {1, 2, -3, -1}
    887891        """
    888         return "Set of perfect matchings of %s"%self._objects
     892        return "Set of perfect matchings of %s" % self._objects
    889893
    890894    def __iter__(self):
    891895        r"""
    class PerfectMatchings(UniqueRepresentat 
    901905        elif len(self._objects) == 1:
    902906            pass
    903907        else:
    904             l=list(self._objects)
    905             a=l.pop(0)
     908            l = list(self._objects)
     909            a = l.pop(0)
    906910            for i in range(len(l)):
    907                 obj_rest=l[:]
    908                 b=obj_rest.pop(i)
     911                obj_rest = l[:]
     912                b = obj_rest.pop(i)
    909913                for p in PerfectMatchings(obj_rest):
    910914                    yield self([(a, b)]+p.value)
    911915
    912     def __contains__(self,x):
     916    def __contains__(self, x):
    913917        r"""
    914918        Tests if ``x`` is an element of ``self``.
    915919
    916920        EXAMPLES::
    917921
    918             sage: m=PerfectMatching([(1,2),(4,3)])
     922            sage: m = PerfectMatching([(1,2),(4,3)])
    919923            sage: m in PerfectMatchings(4)
    920924            True
    921925            sage: m in PerfectMatchings((0, 1, 2, 3))
    class PerfectMatchings(UniqueRepresentat 
    935939            ...        ('a', 'b', 'c', 'd'))
    936940            False
    937941        """
    938         if not isinstance(x,PerfectMatching):
     942        if not isinstance(x, PerfectMatching):
    939943            try:
    940                 x=PerfectMatching(x)
     944                x = PerfectMatching(x)
    941945            except ValueError:
    942946                return False
    943         if x.parent() is not self:
    944             return False
    945         return True
     947        return x.parent() is self
    946948
    947949    def cardinality(self):
    948950        r"""
    949         Returns the cardinality of the set of perfect matching ``self``,
    950         that is `1*3*5*...*(2n-1)`, where `2n` is the size of the ground set.
     951        Returns the cardinality of the set of perfect matching ``self``
     952
     953        This is `1*3*5*...*(2n-1)`, where `2n` is the size of the ground set.
    951954
    952955        EXAMPLES::
    953956
    954957            sage: PerfectMatchings(8).cardinality()
    955958            105
    956959        """
    957         n=len(self._objects)
    958         if n%2==1:
     960        n = len(self._objects)
     961        if n % 2 == 1:
    959962            return 0
    960963        else:
    961             return Integer(prod(i for i in range(n) if i%2==1))
     964            return Integer(prod(i for i in range(n) if i % 2 == 1))
    962965
    963966    def random_element(self):
    964967        r"""
    class PerfectMatchings(UniqueRepresentat 
    966969
    967970        EXAMPLES::
    968971
    969             sage: M=PerfectMatchings(('a', 'e', 'b', 'f', 'c', 'd'))
     972            sage: M = PerfectMatchings(('a', 'e', 'b', 'f', 'c', 'd'))
    970973            sage: M.an_element()
    971974            [('a', 'b'), ('f', 'e'), ('c', 'd')]
    972975            sage: all([PerfectMatchings(2*i).an_element() in PerfectMatchings(2*i)
    class PerfectMatchings(UniqueRepresentat 
    978981            sage: p = PerfectMatchings(13).random_element()
    979982            Traceback (most recent call last):
    980983            ...
    981             ValueError: There is no perfect matching on an odd number of elements
     984            ValueError: there is no perfect matching on an odd number of elements
    982985
    983986        """
    984         n=len(self._objects)
     987        n = len(self._objects)
    985988
    986         if n%2==1:
    987             raise ValueError("There is no perfect matching on an odd number of elements")
     989        if n % 2 == 1:
     990            raise ValueError("there is no perfect matching on an odd number of elements")
    988991
    989992        k = n//2
    990993
    991994        from sage.combinat.permutation import Permutations
    992995        p = Permutations(n).random_element()
    993996
    994         return self([(self._objects[p[2*i]-1],self._objects[p[2*i+1]-1]) for i in range(k)])
     997        return self([(self._objects[p[2*i]-1], self._objects[p[2*i+1]-1]) for i in range(k)])
    995998
    996999    an_element = random_element
    9971000
    9981001    @cached_method
    999     def Weingarten_matrix(self,N):
     1002    def Weingarten_matrix(self, N):
    10001003        r"""
    10011004        Returns the Weingarten matrix corresponding to the set of
    1002         PerfectMatchings ``self``. It is a useful theoretical tool to compute
    1003         polynomial integral over the orthogonal group `O_N` (see [CM]_).
     1005        PerfectMatchings ``self``.
     1006
     1007        It is a useful theoretical tool to compute polynomial integral
     1008        over the orthogonal group `O_N` (see [CM]_).
    10041009
    10051010        EXAMPLES::
    10061011
    1007             sage: M=PerfectMatchings(4).Weingarten_matrix(var('N'))
     1012            sage: M = PerfectMatchings(4).Weingarten_matrix(var('N'))
    10081013            sage: N*(N-1)*(N+2)*M.apply_map(factor)
    10091014            [N + 1    -1    -1]
    10101015            [   -1 N + 1    -1]
    10111016            [   -1    -1 N + 1]
    10121017        """
    1013         G=Matrix([ [N**(p1.number_of_loops(p2)) for p1 in self]
    1014             for p2 in self])
     1018        G = Matrix([[N**(p1.number_of_loops(p2)) for p1 in self]
     1019                    for p2 in self])
    10151020        return G**(-1)
    10161021
    1017     Element=PerfectMatching
     1022    Element = PerfectMatching