This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
permutation.py
8526 lines (6939 loc) · 286 KB
/
permutation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
r"""
Permutations
The Permutations module. Use ``Permutation?`` to get information about
the Permutation class, and ``Permutations?`` to get information about
the combinatorial class of permutations.
.. WARNING::
This file defined :class:`Permutation` which depends upon
:class:`CombinatorialElement` despite it being deprecated (see
:trac:`13742`). This is dangerous. In particular, the
:meth:`Permutation._left_to_right_multiply_on_right` method (which can
be called through multiplication) disables the input checks (see
:meth:`Permutation`). This should not happen. Do not trust the results.
What does this file define ?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The main part of this file consists in the definition of permutation objects,
i.e. the :meth:`Permutation` method and the
:class:`~sage.combinat.permutation.Permutation` class. Global options for
elements of the permutation class can be set through the
:meth:`Permutations.options` object.
Below are listed all methods and classes defined in this file.
**Methods of Permutations objects**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`~sage.combinat.permutation.Permutation.left_action_product` | Returns the product of ``self`` with another permutation, in which the other permutation is applied first.
:meth:`~sage.combinat.permutation.Permutation.right_action_product` | Returns the product of ``self`` with another permutation, in which ``self`` is applied first.
:meth:`~sage.combinat.permutation.Permutation.size` | Returns the size of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.cycle_string` | Returns the disjoint-cycles representation of ``self`` as string.
:meth:`~sage.combinat.permutation.Permutation.next` | Returns the permutation that follows ``self`` in lexicographic order (in the same symmetric group as ``self``).
:meth:`~sage.combinat.permutation.Permutation.prev` | Returns the permutation that comes directly before ``self`` in lexicographic order (in the same symmetric group as ``self``).
:meth:`~sage.combinat.permutation.Permutation.to_tableau_by_shape` | Returns a tableau of shape ``shape`` with the entries in ``self``.
:meth:`~sage.combinat.permutation.Permutation.to_cycles` | Returns the permutation ``self`` as a list of disjoint cycles.
:meth:`~sage.combinat.permutation.Permutation.forget_cycles` | Return ``self`` under the forget cycle map.
:meth:`~sage.combinat.permutation.Permutation.to_permutation_group_element` | Returns a ``PermutationGroupElement`` equal to ``self``.
:meth:`~sage.combinat.permutation.Permutation.signature` | Returns the signature of the permutation ``sef``.
:meth:`~sage.combinat.permutation.Permutation.is_even` | Returns ``True`` if the permutation ``self`` is even, and ``False`` otherwise.
:meth:`~sage.combinat.permutation.Permutation.to_matrix` | Returns a matrix representing the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.rank` | Returns the rank of ``self`` in lexicographic ordering (on the symmetric group containing ``self``).
:meth:`~sage.combinat.permutation.Permutation.to_inversion_vector` | Returns the inversion vector of a permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.inversions` | Returns a list of the inversions of permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.show` | Displays the permutation as a drawing.
:meth:`~sage.combinat.permutation.Permutation.number_of_inversions` | Returns the number of inversions in the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.noninversions` | Returns the ``k``-noninversions in the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.number_of_noninversions` | Returns the number of ``k``-noninversions in the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.length` | Returns the Coxeter length of a permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.inverse` | Returns the inverse of a permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.ishift` | Returns the ``i``-shift of ``self``.
:meth:`~sage.combinat.permutation.Permutation.iswitch` | Returns the ``i``-switch of ``self``.
:meth:`~sage.combinat.permutation.Permutation.runs` | Returns a list of the runs in the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.longest_increasing_subsequence_length` | Returns the length of the longest increasing subsequences of ``self``.
:meth:`~sage.combinat.permutation.Permutation.longest_increasing_subsequences` | Returns the list of the longest increasing subsequences of ``self``.
:meth:`~sage.combinat.permutation.Permutation.cycle_type` | Returns the cycle type of ``self`` as a partition of ``len(self)``.
:meth:`~sage.combinat.permutation.Permutation.foata_bijection` | Returns the image of the permutation ``self`` under the Foata bijection `\phi`.
:meth:`~sage.combinat.permutation.Permutation.destandardize` | Return destandardization of ``self`` with respect to ``weight`` and ``ordered_alphabet``.
:meth:`~sage.combinat.permutation.Permutation.to_lehmer_code` | Returns the Lehmer code of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.to_lehmer_cocode` | Returns the Lehmer cocode of ``self``.
:meth:`~sage.combinat.permutation.Permutation.reduced_word` | Returns the reduced word of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.reduced_words` | Returns a list of the reduced words of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.reduced_word_lexmin` | Returns a lexicographically minimal reduced word of a permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.fixed_points` | Returns a list of the fixed points of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.number_of_fixed_points` | Returns the number of fixed points of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.recoils` | Returns the list of the positions of the recoils of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.number_of_recoils` | Returns the number of recoils of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.recoils_composition` | Returns the composition corresponding to the recoils of ``self``.
:meth:`~sage.combinat.permutation.Permutation.descents` | Returns the list of the descents of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.idescents` | Returns a list of the idescents of ``self``.
:meth:`~sage.combinat.permutation.Permutation.idescents_signature` | Returns the list obtained by mapping each position in ``self`` to `-1` if it is an idescent and `1` if it is not an idescent.
:meth:`~sage.combinat.permutation.Permutation.number_of_descents` | Returns the number of descents of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.number_of_idescents` | Returns the number of idescents of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.descents_composition` | Returns the composition corresponding to the descents of ``self``.
:meth:`~sage.combinat.permutation.Permutation.descent_polynomial` | Returns the descent polynomial of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.major_index` | Returns the major index of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.imajor_index` | Returns the inverse major index of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.to_major_code` | Returns the major code of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.peaks` | Returns a list of the peaks of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.number_of_peaks` | Returns the number of peaks of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.saliances` | Returns a list of the saliances of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.number_of_saliances` | Returns the number of saliances of the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.bruhat_lequal` | Returns ``True`` if self is less or equal to ``p2`` in the Bruhat order.
:meth:`~sage.combinat.permutation.Permutation.weak_excedences` | Returns all the numbers ``self[i]`` such that ``self[i] >= i+1``.
:meth:`~sage.combinat.permutation.Permutation.bruhat_inversions` | Returns the list of inversions of ``self`` such that the application of this inversion to ``self`` decrements its number of inversions.
:meth:`~sage.combinat.permutation.Permutation.bruhat_inversions_iterator` | Returns an iterator over Bruhat inversions of ``self``.
:meth:`~sage.combinat.permutation.Permutation.bruhat_succ` | Returns a list of the permutations covering ``self`` in the Bruhat order.
:meth:`~sage.combinat.permutation.Permutation.bruhat_succ_iterator` | An iterator for the permutations covering ``self`` in the Bruhat order.
:meth:`~sage.combinat.permutation.Permutation.bruhat_pred` | Returns a list of the permutations covered by ``self`` in the Bruhat order.
:meth:`~sage.combinat.permutation.Permutation.bruhat_pred_iterator` | An iterator for the permutations covered by ``self`` in the Bruhat order.
:meth:`~sage.combinat.permutation.Permutation.bruhat_smaller` | Returns the combinatorial class of permutations smaller than or equal to ``self`` in the Bruhat order.
:meth:`~sage.combinat.permutation.Permutation.bruhat_greater` | Returns the combinatorial class of permutations greater than or equal to ``self`` in the Bruhat order.
:meth:`~sage.combinat.permutation.Permutation.permutohedron_lequal` | Returns ``True`` if ``self`` is less or equal to ``p2`` in the permutohedron order.
:meth:`~sage.combinat.permutation.Permutation.permutohedron_succ` | Returns a list of the permutations covering ``self`` in the permutohedron order.
:meth:`~sage.combinat.permutation.Permutation.permutohedron_pred` | Returns a list of the permutations covered by ``self`` in the permutohedron order.
:meth:`~sage.combinat.permutation.Permutation.permutohedron_smaller` | Returns a list of permutations smaller than or equal to ``self`` in the permutohedron order.
:meth:`~sage.combinat.permutation.Permutation.permutohedron_greater` | Returns a list of permutations greater than or equal to ``self`` in the permutohedron order.
:meth:`~sage.combinat.permutation.Permutation.right_permutohedron_interval_iterator` | Returns an iterator over permutations in an interval of the permutohedron order.
:meth:`~sage.combinat.permutation.Permutation.right_permutohedron_interval` | Returns a list of permutations in an interval of the permutohedron order.
:meth:`~sage.combinat.permutation.Permutation.has_pattern` | Tests whether the permutation ``self`` matches the pattern.
:meth:`~sage.combinat.permutation.Permutation.avoids` | Tests whether the permutation ``self`` avoids the pattern.
:meth:`~sage.combinat.permutation.Permutation.pattern_positions` | Returns the list of positions where the pattern ``patt`` appears in ``self``.
:meth:`~sage.combinat.permutation.Permutation.reverse` | Returns the permutation obtained by reversing the 1-line notation of ``self``.
:meth:`~sage.combinat.permutation.Permutation.complement` | Returns the complement of the permutation which is obtained by replacing each value `x` in the 1-line notation of ``self`` with `n - x + 1`.
:meth:`~sage.combinat.permutation.Permutation.permutation_poset` | Returns the permutation poset of ``self``.
:meth:`~sage.combinat.permutation.Permutation.dict` | Returns a dictionary corresponding to the permutation ``self``.
:meth:`~sage.combinat.permutation.Permutation.action` | Returns the action of the permutation ``self`` on a list.
:meth:`~sage.combinat.permutation.Permutation.robinson_schensted` | Returns the pair of standard tableaux obtained by running the Robinson-Schensted Algorithm on ``self``.
:meth:`~sage.combinat.permutation.Permutation.left_tableau` | Returns the left standard tableau after performing the RSK algorithm.
:meth:`~sage.combinat.permutation.Permutation.right_tableau` | Returns the right standard tableau after performing the RSK algorithm.
:meth:`~sage.combinat.permutation.Permutation.increasing_tree` | Returns the increasing tree of ``self``.
:meth:`~sage.combinat.permutation.Permutation.increasing_tree_shape` | Returns the shape of the increasing tree of ``self``.
:meth:`~sage.combinat.permutation.Permutation.binary_search_tree` | Returns the binary search tree of ``self``.
:meth:`~sage.combinat.permutation.Permutation.sylvester_class` | Iterates over the equivalence class of ``self`` under sylvester congruence
:meth:`~sage.combinat.permutation.Permutation.RS_partition` | Returns the shape of the tableaux obtained by the RSK algorithm.
:meth:`~sage.combinat.permutation.Permutation.remove_extra_fixed_points` | Returns the permutation obtained by removing any fixed points at the end of ``self``.
:meth:`~sage.combinat.permutation.Permutation.retract_plain` | Returns the plain retract of ``self`` to a smaller symmetric group `S_m`.
:meth:`~sage.combinat.permutation.Permutation.retract_direct_product` | Returns the direct-product retract of ``self`` to a smaller symmetric group `S_m`.
:meth:`~sage.combinat.permutation.Permutation.retract_okounkov_vershik` | Returns the Okounkov-Vershik retract of ``self`` to a smaller symmetric group `S_m`.
:meth:`~sage.combinat.permutation.Permutation.hyperoctahedral_double_coset_type` | Returns the coset-type of ``self`` as a partition.
:meth:`~sage.combinat.permutation.Permutation.binary_search_tree_shape` | Returns the shape of the binary search tree of ``self`` (a non labelled binary tree).
:meth:`~sage.combinat.permutation.Permutation.shifted_concatenation` | Returns the right (or left) shifted concatenation of ``self`` with a permutation ``other``.
:meth:`~sage.combinat.permutation.Permutation.shifted_shuffle` | Returns the shifted shuffle of ``self`` with a permutation ``other``.
**Other classes defined in this file**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:class:`Permutations` |
:class:`Permutations_nk` |
:class:`Permutations_mset` |
:class:`Permutations_set` |
:class:`Permutations_msetk` |
:class:`Permutations_setk` |
:class:`Arrangements` |
:class:`Arrangements_msetk` |
:class:`Arrangements_setk` |
:class:`StandardPermutations_all` |
:class:`StandardPermutations_n_abstract` |
:class:`StandardPermutations_n` |
:class:`StandardPermutations_descents` |
:class:`StandardPermutations_recoilsfiner` |
:class:`StandardPermutations_recoilsfatter` |
:class:`StandardPermutations_recoils` |
:class:`StandardPermutations_bruhat_smaller` |
:class:`StandardPermutations_bruhat_greater` |
:class:`CyclicPermutations` |
:class:`CyclicPermutationsOfPartition` |
:class:`StandardPermutations_avoiding_12` |
:class:`StandardPermutations_avoiding_21` |
:class:`StandardPermutations_avoiding_132` |
:class:`StandardPermutations_avoiding_123` |
:class:`StandardPermutations_avoiding_321` |
:class:`StandardPermutations_avoiding_231` |
:class:`StandardPermutations_avoiding_312` |
:class:`StandardPermutations_avoiding_213` |
:class:`StandardPermutations_avoiding_generic` |
:class:`PatternAvoider` |
**Functions defined in this file**
.. csv-table::
:class: contentstable
:widths: 30, 70
:delim: |
:meth:`from_major_code` | Returns the permutation corresponding to major code ``mc``.
:meth:`from_permutation_group_element` | Returns a Permutation give a ``PermutationGroupElement`` ``pge``.
:meth:`from_rank` | Returns the permutation with the specified lexicographic rank.
:meth:`from_inversion_vector` | Returns the permutation corresponding to inversion vector ``iv``.
:meth:`from_cycles` | Returns the permutation with given disjoint-cycle representation ``cycles``.
:meth:`from_lehmer_code` | Returns the permutation with Lehmer code ``lehmer``.
:meth:`from_reduced_word` | Returns the permutation corresponding to the reduced word ``rw``.
:meth:`bistochastic_as_sum_of_permutations` | Returns a given bistochastic matrix as a nonnegative linear combination of permutations.
:meth:`bounded_affine_permutation` | Return a partial permutation representing the bounded affine permutation of a matrix.
:meth:`descents_composition_list` | Returns a list of all the permutations in a given descent class (i. e., having a given descents composition).
:meth:`descents_composition_first` | Returns the smallest element of a descent class.
:meth:`descents_composition_last` | Returns the largest element of a descent class.
:meth:`bruhat_lequal` | Returns ``True`` if ``p1`` is less or equal to ``p2`` in the Bruhat order.
:meth:`permutohedron_lequal` | Returns ``True`` if ``p1`` is less or equal to ``p2`` in the permutohedron order.
:meth:`to_standard` | Returns a standard permutation corresponding to the permutation ``self``.
AUTHORS:
- Mike Hansen
- Dan Drake (2008-04-07): allow Permutation() to take lists of tuples
- Sébastien Labbé (2009-03-17): added robinson_schensted_inverse
- Travis Scrimshaw:
* (2012-08-16): ``to_standard()`` no longer modifies input
* (2013-01-19): Removed RSK implementation and moved to
:mod:`~sage.combinat.rsk`.
* (2013-07-13): Removed ``CombinatorialClass`` and moved permutations to the
category framework.
- Darij Grinberg (2013-09-07): added methods; ameliorated :trac:`14885` by
exposing and documenting methods for global-independent
multiplication.
- Travis Scrimshaw (2014-02-05): Made :class:`StandardPermutations_n` a
finite Weyl group to make it more uniform with :class:`SymmetricGroup`.
Added ability to compute the conjugacy classes.
Classes and methods
===================
"""
#*****************************************************************************
# Copyright (C) 2007 Mike Hansen <mhansen@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
from __future__ import print_function, absolute_import
from builtins import zip
from six.moves import range
from six import itervalues
from sage.structure.parent import Parent
from sage.structure.unique_representation import UniqueRepresentation
from sage.categories.infinite_enumerated_sets import InfiniteEnumeratedSets
from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets
from sage.categories.finite_weyl_groups import FiniteWeylGroups
from sage.categories.finite_permutation_groups import FinitePermutationGroups
from sage.structure.list_clone import ClonableArray
from sage.structure.global_options import GlobalOptions
from sage.interfaces.all import gap
from sage.rings.all import ZZ, Integer, PolynomialRing
from sage.arith.all import factorial
from sage.matrix.all import matrix
from sage.combinat.tools import transitive_ideal
from sage.combinat.composition import Composition
from sage.groups.perm_gps.permgroup_named import SymmetricGroup
from sage.groups.perm_gps.permgroup_element import PermutationGroupElement
from sage.misc.prandom import sample
from sage.graphs.digraph import DiGraph
import itertools
from .combinat import CombinatorialElement, catalan_number
from sage.misc.misc import uniq
from sage.misc.cachefunc import cached_method
from .backtrack import GenericBacktracker
from sage.combinat.combinatorial_map import combinatorial_map
from sage.combinat.rsk import RSK, RSK_inverse
from sage.combinat.permutation_cython import (left_action_product,
right_action_product, left_action_same_n, right_action_same_n)
class Permutation(CombinatorialElement):
r"""
A permutation.
Converts ``l`` to a permutation on `\{1, 2, \ldots, n\}`.
INPUT:
- ``l`` -- Can be any one of the following:
- an instance of :class:`Permutation`,
- list of integers, viewed as one-line permutation notation. The
construction checks that you give an acceptable entry. To avoid
the check, use the ``check_input`` option.
- string, expressing the permutation in cycle notation.
- list of tuples of integers, expressing the permutation in cycle
notation.
- a :class:`PermutationGroupElement`
- a pair of two standard tableaux of the same shape. This yields
the permutation obtained from the pair using the inverse of the
Robinson-Schensted algorithm.
- ``check_input`` (boolean) -- whether to check that input is correct. Slows
the function down, but ensures that nothing bad happens. This is set to
``True`` by default.
.. WARNING::
Since :trac:`13742` the input is checked for correctness : it is not
accepted unless it actually is a permutation on `\{1, \ldots, n\}`. It
means that some :meth:`Permutation` objects cannot be created anymore
without setting ``check_input = False``, as there is no certainty that
its functions can handle them, and this should be fixed in a much
better way ASAP (the functions should be rewritten to handle those
cases, and new tests be added).
.. WARNING::
There are two possible conventions for multiplying permutations, and
the one currently enabled in Sage by default is the one which has
`(pq)(i) = q(p(i))` for any permutations `p \in S_n` and `q \in S_n`
and any `1 \leq i \leq n`. (This equation looks less strange when
the action of permutations on numbers is written from the right:
then it takes the form `i^{pq} = (i^p)^q`, which is an associativity
law). There is an alternative convention, which has
`(pq)(i) = p(q(i))` instead. The conventions can be switched at
runtime using
:meth:`sage.combinat.permutation.Permutations.options`.
It is best for code not to rely on this setting being set to a
particular standard, but rather use the methods
:meth:`left_action_product` and :meth:`right_action_product` for
multiplying permutations (these methods don't depend on the setting).
See :trac:`14885` for more details.
.. NOTE::
The ``bruhat*`` methods refer to the *strong* Bruhat order. To use
the *weak* Bruhat order, look under ``permutohedron*``.
EXAMPLES::
sage: Permutation([2,1])
[2, 1]
sage: Permutation([2, 1, 4, 5, 3])
[2, 1, 4, 5, 3]
sage: Permutation('(1,2)')
[2, 1]
sage: Permutation('(1,2)(3,4,5)')
[2, 1, 4, 5, 3]
sage: Permutation( ((1,2),(3,4,5)) )
[2, 1, 4, 5, 3]
sage: Permutation( [(1,2),(3,4,5)] )
[2, 1, 4, 5, 3]
sage: Permutation( ((1,2)) )
[2, 1]
sage: Permutation( (1,2) )
[2, 1]
sage: Permutation( ((1,2),) )
[2, 1]
sage: Permutation( ((1,),) )
[1]
sage: Permutation( (1,) )
[1]
sage: Permutation( () )
[]
sage: Permutation( ((),) )
[]
sage: p = Permutation((1, 2, 5)); p
[2, 5, 3, 4, 1]
sage: type(p)
<class 'sage.combinat.permutation.StandardPermutations_n_with_category.element_class'>
Construction from a string in cycle notation::
sage: p = Permutation( '(4,5)' ); p
[1, 2, 3, 5, 4]
The size of the permutation is the maximum integer appearing; add
a 1-cycle to increase this::
sage: p2 = Permutation( '(4,5)(10)' ); p2
[1, 2, 3, 5, 4, 6, 7, 8, 9, 10]
sage: len(p); len(p2)
5
10
We construct a :class:`Permutation` from a
:class:`PermutationGroupElement`::
sage: g = PermutationGroupElement([2,1,3])
sage: Permutation(g)
[2, 1, 3]
From a pair of tableaux of the same shape. This uses the inverse
of the Robinson-Schensted algorithm::
sage: p = [[1, 4, 7], [2, 5], [3], [6]]
sage: q = [[1, 2, 5], [3, 6], [4], [7]]
sage: P = Tableau(p)
sage: Q = Tableau(q)
sage: Permutation( (p, q) )
[3, 6, 5, 2, 7, 4, 1]
sage: Permutation( [p, q] )
[3, 6, 5, 2, 7, 4, 1]
sage: Permutation( (P, Q) )
[3, 6, 5, 2, 7, 4, 1]
sage: Permutation( [P, Q] )
[3, 6, 5, 2, 7, 4, 1]
TESTS::
sage: Permutation([()])
[]
sage: Permutation('()')
[]
sage: Permutation(())
[]
sage: Permutation( [1] )
[1]
From a pair of empty tableaux ::
sage: Permutation( ([], []) )
[]
sage: Permutation( [[], []] )
[]
.. automethod:: _left_to_right_multiply_on_right
.. automethod:: _left_to_right_multiply_on_left
"""
@staticmethod
def __classcall_private__(cls, l, check_input = True):
"""
Return a permutation in the general permutations parent.
EXAMPLES::
sage: P = Permutation([2,1]); P
[2, 1]
sage: P.parent()
Standard permutations
"""
import sage.combinat.tableau as tableau
if isinstance(l, Permutation):
return l
elif isinstance(l, PermutationGroupElement):
l = l.domain()
#if l is a string, then assume it is in cycle notation
elif isinstance(l, str):
if l == "()" or l == "":
return from_cycles(0, [])
cycles = l.split(")(")
cycles[0] = cycles[0][1:]
cycles[-1] = cycles[-1][:-1]
cycle_list = []
for c in cycles:
cycle_list.append([int(_) for _ in c.split(",")])
return from_cycles(max(max(c) for c in cycle_list), cycle_list)
#if l is a pair of standard tableaux or a pair of lists
elif isinstance(l, (tuple, list)) and len(l) == 2 and \
all(isinstance(x, tableau.Tableau) for x in l):
return RSK_inverse(*l, output='permutation')
elif isinstance(l, (tuple, list)) and len(l) == 2 and \
all(isinstance(x, list) for x in l):
P,Q = [tableau.Tableau(_) for _ in l]
return RSK_inverse(P, Q, 'permutation')
# if it's a tuple or nonempty list of tuples, also assume cycle
# notation
elif isinstance(l, tuple) or \
(isinstance(l, list) and l and
all(isinstance(x, tuple) for x in l)):
if l and (isinstance(l[0], (int,Integer)) or len(l[0]) > 0):
if isinstance(l[0], tuple):
n = max(max(x) for x in l)
return from_cycles(n, [list(x) for x in l])
else:
n = max(l)
return from_cycles(n, [list(l)])
elif len(l) <= 1:
return Permutations()([])
else:
raise ValueError("cannot convert l (= %s) to a Permutation"%l)
# otherwise, it gets processed by CombinatorialElement's __init__.
return Permutations()(l, check_input=check_input)
def __init__(self, parent, l, check_input=True):
"""
Constructor. Checks that INPUT is not a mess, and calls
:class:`CombinatorialElement`. It should not, because
:class:`CombinatorialElement` is deprecated.
INPUT:
- ``l`` -- a list of ``int`` variables
- ``check_input`` (boolean) -- whether to check that input is
correct. Slows the function down, but ensures that nothing bad
happens.
This is set to ``True`` by default.
TESTS::
sage: Permutation([1,2,3])
[1, 2, 3]
sage: Permutation([1,2,2,4])
Traceback (most recent call last):
...
ValueError: An element appears twice in the input. It should not.
sage: Permutation([1,2,4,-1])
Traceback (most recent call last):
...
ValueError: the elements must be strictly positive integers
sage: Permutation([1,2,4,5])
Traceback (most recent call last):
...
ValueError: The permutation has length 4 but its maximal element is
5. Some element may be repeated, or an element is missing, but there
is something wrong with its length.
"""
l = list(l)
if check_input and len(l) > 0:
# Make a copy to sort later
lst = list(l)
# Is input a list of positive integers ?
for i in lst:
try:
i = int(i)
except TypeError:
raise ValueError("the elements must be integer variables")
if i < 1:
raise ValueError("the elements must be strictly positive integers")
lst.sort()
# Is the maximum element of the permutation the length of input,
# or is some integer missing ?
if int(lst[-1]) != len(lst):
raise ValueError("The permutation has length "+str(len(lst))+
" but its maximal element is "+
str(int(lst[-1]))+". Some element "+
"may be repeated, or an element is missing"+
", but there is something wrong with its length.")
# Do the elements appear only once ?
previous = lst[0]-1
for i in lst:
if i == previous:
raise ValueError("An element appears twice in the input. It should not.")
previous = i
CombinatorialElement.__init__(self, parent, l)
def __setstate__(self, state):
r"""
In order to maintain backwards compatibility and be able to unpickle a
old pickle from ``Permutation_class`` we have to override the default
``__setstate__``.
EXAMPLES::
sage: loads('x\x9ck`J.NLO\xd5K\xce\xcfM\xca\xccK,\xd1+H-\xca--I,\xc9\xcc\xcf\xe3\n@\xb0\xe3\x93s\x12\x8b\x8b\xb9\n\x195\x1b'
....: '\x0b\x99j\x0b\x995BY\xe33\x12\x8b3\nY\xfc\x80\xac\x9c\xcc\xe2\x92B\xd6\xd8B6\r\x88iE\x99y\xe9\xc5z\x99y%\xa9\xe9'
....: '\xa9E\\\xb9\x89\xd9\xa9\xf10N!{(\xa3qkP!G\x06\x90a\x04dp\x82\x18\x86@\x06Wji\x92\x1e\x00i\x8d0q')
[3, 2, 1]
sage: loads(dumps( Permutation([3,2,1]) )) # indirect doctest
[3, 2, 1]
"""
if isinstance(state, dict): # for old pickles from Permutation_class
self._set_parent(Permutations())
self.__dict__ = state
else:
self._set_parent(state[0])
self.__dict__ = state[1]
@cached_method
def __hash__(self):
"""
TESTS::
sage: d = {}
sage: p = Permutation([1,2,3])
sage: d[p] = 1
sage: d[p]
1
"""
try:
return hash(tuple(self._list))
except Exception:
return hash(str(self._list))
def __str__(self):
"""
TESTS::
sage: Permutations.options.display='list'
sage: p = Permutation([2,1,3])
sage: str(p)
'[2, 1, 3]'
sage: Permutations.options.display='cycle'
sage: str(p)
'(1,2)'
sage: Permutations.options.display='singleton'
sage: str(p)
'(1,2)(3)'
sage: Permutations.options.display='list'
"""
return repr(self)
def _repr_(self):
"""
TESTS::
sage: p = Permutation([2,1,3])
sage: p
[2, 1, 3]
sage: Permutations.options.display='cycle'
sage: p
(1,2)
sage: Permutations.options.display='singleton'
sage: p
(1,2)(3)
sage: Permutations.options.display='reduced_word'
sage: p
[1]
sage: Permutations.options._reset()
"""
display = self.parent().options.display
if display == 'list':
return repr(self._list)
elif display == 'cycle':
return self.cycle_string()
elif display == 'singleton':
return self.cycle_string(singletons=True)
elif display == 'reduced_word':
return repr(self.reduced_word())
def _latex_(self):
r"""
Return a `\LaTeX` representation of ``self``.
EXAMPLES::
sage: p = Permutation([2,1,3])
sage: latex(p)
[2, 1, 3]
sage: Permutations.options.latex='cycle'
sage: latex(p)
(1 \; 2)
sage: Permutations.options.latex='singleton'
sage: latex(p)
(1 \; 2)(3)
sage: Permutations.options.latex='reduced_word'
sage: latex(p)
s_{1}
sage: latex(Permutation([1,2,3]))
1
sage: Permutations.options.latex_empty_str="e"
sage: latex(Permutation([1,2,3]))
e
sage: Permutations.options.latex='twoline'
sage: latex(p)
\begin{pmatrix} 1 & 2 & 3 \\ 2 & 1 & 3 \end{pmatrix}
sage: Permutations.options._reset()
"""
display = self.parent().options.latex
if display == "reduced_word":
let = self.parent().options.generator_name
redword = self.reduced_word()
if not redword:
return self.parent().options.latex_empty_str
return " ".join("%s_{%s}"%(let, i) for i in redword)
if display == "twoline":
return "\\begin{pmatrix} %s \\\\ %s \\end{pmatrix}"%(
" & ".join("%s"%i for i in range(1, len(self._list)+1)),
" & ".join("%s"%i for i in self._list))
if display == "list":
return repr(self._list)
if display == "cycle":
ret = self.cycle_string()
else: # Must be cycles with singletons
ret = self.cycle_string(singletons=True)
return ret.replace(",", " \\; ")
def _gap_(self, gap):
"""
Return a GAP version of this permutation.
EXAMPLES::
sage: gap(Permutation([1,2,3]))
()
sage: gap(Permutation((1,2,3)))
(1,2,3)
sage: type(_)
<class 'sage.interfaces.gap.GapElement'>
"""
return self.to_permutation_group_element()._gap_(gap)
def size(self):
"""
Return the size of ``self``.
EXAMPLES::
sage: Permutation([3,4,1,2,5]).size()
5
"""
return len(self)
def cycle_string(self, singletons=False):
"""
Returns a string of the permutation in cycle notation.
If ``singletons=True``, it includes 1-cycles in the string.
EXAMPLES::
sage: Permutation([1,2,3]).cycle_string()
'()'
sage: Permutation([2,1,3]).cycle_string()
'(1,2)'
sage: Permutation([2,3,1]).cycle_string()
'(1,2,3)'
sage: Permutation([2,1,3]).cycle_string(singletons=True)
'(1,2)(3)'
"""
cycles = self.to_cycles(singletons=singletons)
if cycles == []:
return "()"
else:
return "".join(["("+",".join([str(l) for l in x])+")" for x in cycles])
def __next__(self):
r"""
Return the permutation that follows ``self`` in lexicographic order on
the symmetric group containing ``self``. If ``self`` is the last
permutation, then ``next`` returns ``False``.
EXAMPLES::
sage: p = Permutation([1, 3, 2])
sage: next(p)
[2, 1, 3]
sage: p = Permutation([4,3,2,1])
sage: next(p)
False
TESTS::
sage: p = Permutation([])
sage: next(p)
False
"""
p = self[:]
n = len(self)
first = -1
#Starting from the end, find the first o such that
#p[o] < p[o+1]
for i in reversed(range(0,n-1)):
if p[i] < p[i+1]:
first = i
break
#If first is still -1, then we are already at the last permutation
if first == -1:
return False
#Starting from the end, find the first j such that p[j] > p[first]
j = n - 1
while p[j] < p[first]:
j -= 1
#Swap positions first and j
(p[j], p[first]) = (p[first], p[j])
#Reverse the list between first and the end
first_half = p[:first+1]
last_half = p[first+1:]
last_half.reverse()
p = first_half + last_half
return Permutations()(p)
next = __next__
def prev(self):
r"""
Return the permutation that comes directly before ``self`` in
lexicographic order on the symmetric group containing ``self``.
If ``self`` is the first permutation, then it returns ``False``.
EXAMPLES::
sage: p = Permutation([1,2,3])
sage: p.prev()
False
sage: p = Permutation([1,3,2])
sage: p.prev()
[1, 2, 3]
TESTS::
sage: p = Permutation([])
sage: p.prev()
False
Check that :trac:`16913` is fixed::
sage: Permutation([1,4,3,2]).prev()
[1, 4, 2, 3]
"""
p = self[:]
n = len(self)
first = -1
#Starting from the end, find the first o such that
#p[o] > p[o+1]
for i in reversed(range(0, n-1)):
if p[i] > p[i+1]:
first = i
break
#If first is still -1, that is we didn't find any descents,
#then we are already at the last permutation
if first == -1:
return False
#Starting from the end, find the first j such that p[j] < p[first]
j = n - 1
while p[j] > p[first]:
j -= 1
#Swap positions first and j
(p[j], p[first]) = (p[first], p[j])
#Reverse the list between first+1 and end
first_half = p[:first+1]
last_half = p[first+1:]
last_half.reverse()
p = first_half + last_half
return Permutations()(p)
def to_tableau_by_shape(self, shape):
"""
Return a tableau of shape ``shape`` with the entries
in ``self``. The tableau is such that the reading word (i. e.,
the word obtained by reading the tableau row by row, starting
from the top row in English notation, with each row being
read from left to right) is ``self``.
EXAMPLES::
sage: Permutation([3,4,1,2,5]).to_tableau_by_shape([3,2])
[[1, 2, 5], [3, 4]]
sage: Permutation([3,4,1,2,5]).to_tableau_by_shape([3,2]).reading_word_permutation()
[3, 4, 1, 2, 5]
"""
import sage.combinat.tableau as tableau
if sum(shape) != len(self):
raise ValueError("the size of the partition must be the size of self")
t = []
w = list(self)
for i in reversed(shape):
t = [ w[:i] ] + t
w = w[i:]
return tableau.Tableau(t)
def to_cycles(self, singletons=True):
"""
Return the permutation ``self`` as a list of disjoint cycles.
The cycles are returned in the order of increasing smallest
elements, and each cycle is returned as a tuple which starts
with its smallest element.
If ``singletons=False`` is given, the list does not contain the
singleton cycles.
EXAMPLES::
sage: Permutation([2,1,3,4]).to_cycles()
[(1, 2), (3,), (4,)]
sage: Permutation([2,1,3,4]).to_cycles(singletons=False)
[(1, 2)]
sage: Permutation([4,1,5,2,6,3]).to_cycles()
[(1, 4, 2), (3, 5, 6)]
The algorithm is of complexity `O(n)` where `n` is the size of the
given permutation.
TESTS::
sage: from sage.combinat.permutation import from_cycles
sage: for n in range(1,6):
....: for p in Permutations(n):
....: if from_cycles(n, p.to_cycles()) != p:
....: print("There is a problem with {}".format(p))
....: break
sage: size = 10000
sage: sample = (Permutations(size).random_element() for i in range(5))
sage: all(from_cycles(size, p.to_cycles()) == p for p in sample)
True
Note: there is an alternative implementation called ``_to_cycle_set``
which could be slightly (10%) faster for some input (typically for
permutations of size in the range [100, 10000]). You can run the
following benchmarks. For small permutations::
sage: for size in range(9): # not tested
....: print(size)
....: lp = Permutations(size).list()
....: timeit('[p.to_cycles(False) for p in lp]')
....: timeit('[p._to_cycles_set(False) for p in lp]')
....: timeit('[p._to_cycles_list(False) for p in lp]')
....: timeit('[p._to_cycles_orig(False) for p in lp]')
and larger ones::
sage: for size in [10, 20, 50, 75, 100, 200, 500, 1000, # not tested
....: 2000, 5000, 10000, 15000, 20000, 30000,
....: 50000, 80000, 100000]:
....: print(size)
....: lp = [Permutations(size).random_element() for i in range(20)]
....: timeit("[p.to_cycles() for p in lp]")
....: timeit("[p._to_cycles_set() for p in lp]")
....: timeit("[p._to_cycles_list() for p in lp]")
"""
cycles = []
l = self[:]
# Go through until we've considered every number between 1 and len(l)
for i in range(len(l)):
if not l[i]:
continue
cycleFirst = i + 1
cycle = [cycleFirst]
l[i], next = False, l[i]
while next != cycleFirst:
cycle.append( next )
l[next - 1], next = False, l[next - 1]
# Add the cycle to the list of cycles
if singletons or len(cycle) > 1:
cycles.append(tuple(cycle))
return cycles
cycle_tuples = to_cycles
def _to_cycles_orig(self, singletons=True):
r"""
Returns the permutation ``self`` as a list of disjoint cycles.
EXAMPLES::
sage: Permutation([2,1,3,4])._to_cycles_orig()
[(1, 2), (3,), (4,)]
sage: Permutation([2,1,3,4])._to_cycles_orig(singletons=False)
[(1, 2)]
"""
p = self[:]
cycles = []
toConsider = -1
#Create the list [1,2,...,len(p)]
l = [ i+1 for i in range(len(p))]
cycle = []
#Go through until we've considered every number between
#1 and len(p)
while len(l) > 0:
#If we are at the end of a cycle
#then we want to add it to the cycles list
if toConsider == -1:
#Add the cycle to the list of cycles
if singletons:
if cycle != []:
cycles.append(tuple(cycle))
else:
if len(cycle) > 1:
cycles.append(tuple(cycle))
#Start with the first element in the list
toConsider = l[0]
l.remove(toConsider)
cycle = [ toConsider ]
cycleFirst = toConsider
#Figure out where the element under consideration
#gets mapped to.
next = p[toConsider - 1]
#If the next element is the first one in the list
#then we've reached the end of the cycle
if next == cycleFirst:
toConsider = -1
else:
cycle.append( next )
l.remove( next )
toConsider = next