Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

2355

2356

2357

2358

2359

2360

2361

2362

2363

2364

2365

2366

2367

2368

2369

2370

2371

2372

2373

2374

2375

2376

2377

2378

2379

2380

2381

2382

2383

2384

2385

2386

2387

2388

2389

2390

2391

2392

2393

2394

2395

2396

2397

2398

2399

2400

2401

2402

2403

2404

2405

2406

2407

2408

2409

2410

2411

2412

2413

2414

2415

2416

2417

2418

2419

2420

2421

2422

2423

2424

2425

2426

2427

2428

2429

2430

2431

2432

2433

2434

2435

2436

2437

2438

2439

2440

2441

2442

2443

2444

2445

2446

2447

2448

2449

2450

2451

2452

2453

2454

2455

2456

2457

2458

2459

2460

2461

2462

2463

2464

2465

2466

2467

2468

2469

2470

2471

2472

2473

2474

2475

2476

2477

2478

2479

2480

2481

2482

2483

2484

2485

2486

2487

2488

2489

2490

2491

2492

2493

2494

2495

2496

2497

2498

2499

2500

2501

2502

2503

2504

2505

2506

2507

2508

2509

2510

2511

2512

2513

2514

2515

2516

2517

2518

2519

2520

2521

2522

2523

2524

2525

2526

2527

2528

2529

2530

2531

2532

2533

2534

2535

2536

2537

2538

2539

2540

2541

2542

2543

2544

2545

2546

2547

2548

2549

2550

2551

2552

2553

2554

2555

2556

2557

2558

2559

2560

2561

2562

2563

2564

2565

2566

2567

2568

2569

2570

2571

2572

2573

2574

2575

2576

2577

2578

2579

2580

2581

2582

2583

2584

2585

2586

2587

2588

2589

2590

2591

2592

2593

2594

2595

2596

2597

2598

2599

2600

2601

2602

2603

2604

2605

2606

2607

2608

2609

2610

2611

2612

2613

2614

2615

2616

2617

2618

2619

2620

2621

2622

2623

2624

2625

2626

2627

2628

2629

2630

2631

2632

2633

2634

2635

2636

2637

2638

2639

2640

2641

2642

2643

2644

2645

2646

2647

2648

2649

2650

2651

2652

2653

2654

2655

2656

2657

2658

2659

2660

2661

2662

2663

2664

2665

2666

2667

2668

2669

2670

2671

2672

2673

2674

2675

2676

2677

2678

2679

2680

2681

2682

2683

2684

2685

2686

2687

2688

2689

2690

2691

2692

2693

2694

2695

2696

2697

2698

2699

2700

2701

2702

2703

2704

2705

2706

2707

2708

2709

2710

2711

2712

2713

2714

2715

2716

2717

2718

2719

2720

2721

2722

2723

2724

2725

2726

2727

2728

2729

2730

2731

2732

2733

2734

2735

2736

2737

2738

2739

2740

2741

2742

2743

2744

2745

2746

2747

2748

2749

2750

2751

2752

2753

2754

2755

2756

2757

2758

2759

2760

2761

2762

2763

2764

2765

2766

2767

2768

2769

2770

2771

2772

2773

2774

2775

2776

2777

2778

2779

2780

2781

2782

2783

2784

2785

2786

2787

2788

2789

2790

2791

2792

2793

2794

2795

2796

2797

2798

2799

2800

2801

2802

2803

2804

2805

2806

2807

2808

2809

2810

2811

2812

2813

2814

2815

2816

2817

2818

2819

2820

2821

2822

2823

2824

2825

2826

2827

2828

2829

2830

2831

2832

2833

2834

2835

from __future__ import print_function, division 

 

import random 

from collections import defaultdict 

 

from sympy.core import Basic 

from sympy.core.compatibility import is_sequence, reduce, range, as_int 

from sympy.utilities.iterables import (flatten, has_variety, minlex, 

has_dups, runs) 

from sympy.polys.polytools import lcm 

from sympy.matrices import zeros 

from mpmath.libmp.libintmath import ifac 

 

 

def _af_rmul(a, b): 

""" 

Return the product b*a; input and output are array forms. The ith value 

is a[b[i]]. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import _af_rmul, Permutation 

>>> Permutation.print_cyclic = False 

 

>>> a, b = [1, 0, 2], [0, 2, 1] 

>>> _af_rmul(a, b) 

[1, 2, 0] 

>>> [a[b[i]] for i in range(3)] 

[1, 2, 0] 

 

This handles the operands in reverse order compared to the ``*`` operator: 

 

>>> a = Permutation(a) 

>>> b = Permutation(b) 

>>> list(a*b) 

[2, 0, 1] 

>>> [b(a(i)) for i in range(3)] 

[2, 0, 1] 

 

See Also 

======== 

rmul, _af_rmuln 

""" 

return [a[i] for i in b] 

 

 

def _af_rmuln(*abc): 

""" 

Given [a, b, c, ...] return the product of ...*c*b*a using array forms. 

The ith value is a[b[c[i]]]. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import _af_rmul, Permutation 

>>> Permutation.print_cyclic = False 

 

>>> a, b = [1, 0, 2], [0, 2, 1] 

>>> _af_rmul(a, b) 

[1, 2, 0] 

>>> [a[b[i]] for i in range(3)] 

[1, 2, 0] 

 

This handles the operands in reverse order compared to the ``*`` operator: 

 

>>> a = Permutation(a); b = Permutation(b) 

>>> list(a*b) 

[2, 0, 1] 

>>> [b(a(i)) for i in range(3)] 

[2, 0, 1] 

 

See Also 

======== 

rmul, _af_rmul 

""" 

a = abc 

m = len(a) 

if m == 3: 

p0, p1, p2 = a 

return [p0[p1[i]] for i in p2] 

if m == 4: 

p0, p1, p2, p3 = a 

return [p0[p1[p2[i]]] for i in p3] 

if m == 5: 

p0, p1, p2, p3, p4 = a 

return [p0[p1[p2[p3[i]]]] for i in p4] 

if m == 6: 

p0, p1, p2, p3, p4, p5 = a 

return [p0[p1[p2[p3[p4[i]]]]] for i in p5] 

if m == 7: 

p0, p1, p2, p3, p4, p5, p6 = a 

return [p0[p1[p2[p3[p4[p5[i]]]]]] for i in p6] 

if m == 8: 

p0, p1, p2, p3, p4, p5, p6, p7 = a 

return [p0[p1[p2[p3[p4[p5[p6[i]]]]]]] for i in p7] 

if m == 1: 

return a[0][:] 

if m == 2: 

a, b = a 

return [a[i] for i in b] 

if m == 0: 

raise ValueError("String must not be empty") 

p0 = _af_rmuln(*a[:m//2]) 

p1 = _af_rmuln(*a[m//2:]) 

return [p0[i] for i in p1] 

 

 

def _af_parity(pi): 

""" 

Computes the parity of a permutation in array form. 

 

The parity of a permutation reflects the parity of the 

number of inversions in the permutation, i.e., the 

number of pairs of x and y such that x > y but p[x] < p[y]. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import _af_parity 

>>> _af_parity([0, 1, 2, 3]) 

0 

>>> _af_parity([3, 2, 0, 1]) 

1 

 

See Also 

======== 

 

Permutation 

""" 

n = len(pi) 

a = [0] * n 

c = 0 

for j in range(n): 

if a[j] == 0: 

c += 1 

a[j] = 1 

i = j 

while pi[i] != j: 

i = pi[i] 

a[i] = 1 

return (n - c) % 2 

 

 

def _af_invert(a): 

""" 

Finds the inverse, ~A, of a permutation, A, given in array form. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import _af_invert, _af_rmul 

>>> A = [1, 2, 0, 3] 

>>> _af_invert(A) 

[2, 0, 1, 3] 

>>> _af_rmul(_, A) 

[0, 1, 2, 3] 

 

See Also 

======== 

 

Permutation, __invert__ 

""" 

inv_form = [0] * len(a) 

for i, ai in enumerate(a): 

inv_form[ai] = i 

return inv_form 

 

def _af_pow(a, n): 

""" 

Routine for finding powers of a permutation. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation, _af_pow 

>>> Permutation.print_cyclic = False 

>>> p = Permutation([2, 0, 3, 1]) 

>>> p.order() 

4 

>>> _af_pow(p._array_form, 4) 

[0, 1, 2, 3] 

""" 

if n == 0: 

return list(range(len(a))) 

if n < 0: 

return _af_pow(_af_invert(a), -n) 

if n == 1: 

return a[:] 

elif n == 2: 

b = [a[i] for i in a] 

elif n == 3: 

b = [a[a[i]] for i in a] 

elif n == 4: 

b = [a[a[a[i]]] for i in a] 

else: 

# use binary multiplication 

b = list(range(len(a))) 

while 1: 

if n & 1: 

b = [b[i] for i in a] 

n -= 1 

if not n: 

break 

if n % 4 == 0: 

a = [a[a[a[i]]] for i in a] 

n = n // 4 

elif n % 2 == 0: 

a = [a[i] for i in a] 

n = n // 2 

return b 

 

def _af_commutes_with(a, b): 

""" 

Checks if the two permutations with array forms 

given by ``a`` and ``b`` commute. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import _af_commutes_with 

>>> _af_commutes_with([1, 2, 0], [0, 2, 1]) 

False 

 

See Also 

======== 

 

Permutation, commutes_with 

""" 

return not any(a[b[i]] != b[a[i]] for i in range(len(a) - 1)) 

 

 

class Cycle(dict): 

""" 

Wrapper around dict which provides the functionality of a disjoint cycle. 

 

A cycle shows the rule to use to move subsets of elements to obtain 

a permutation. The Cycle class is more flexible than Permutation in 

that 1) all elements need not be present in order to investigate how 

multiple cycles act in sequence and 2) it can contain singletons: 

 

>>> from sympy.combinatorics.permutations import Perm, Cycle 

 

A Cycle will automatically parse a cycle given as a tuple on the rhs: 

 

>>> Cycle(1, 2)(2, 3) 

(1 3 2) 

 

The identity cycle, Cycle(), can be used to start a product: 

 

>>> Cycle()(1, 2)(2, 3) 

(1 3 2) 

 

The array form of a Cycle can be obtained by calling the list 

method (or passing it to the list function) and all elements from 

0 will be shown: 

 

>>> a = Cycle(1, 2) 

>>> a.list() 

[0, 2, 1] 

>>> list(a) 

[0, 2, 1] 

 

If a larger (or smaller) range is desired use the list method and 

provide the desired size -- but the Cycle cannot be truncated to 

a size smaller than the largest element that is out of place: 

 

>>> b = Cycle(2, 4)(1, 2)(3, 1, 4)(1, 3) 

>>> b.list() 

[0, 2, 1, 3, 4] 

>>> b.list(b.size + 1) 

[0, 2, 1, 3, 4, 5] 

>>> b.list(-1) 

[0, 2, 1] 

 

Singletons are not shown when printing with one exception: the largest 

element is always shown -- as a singleton if necessary: 

 

>>> Cycle(1, 4, 10)(4, 5) 

(1 5 4 10) 

>>> Cycle(1, 2)(4)(5)(10) 

(1 2)(10) 

 

The array form can be used to instantiate a Permutation so other 

properties of the permutation can be investigated: 

 

>>> Perm(Cycle(1, 2)(3, 4).list()).transpositions() 

[(1, 2), (3, 4)] 

 

Notes 

===== 

 

The underlying structure of the Cycle is a dictionary and although 

the __iter__ method has been redefined to give the array form of the 

cycle, the underlying dictionary items are still available with the 

such methods as items(): 

 

>>> list(Cycle(1, 2).items()) 

[(1, 2), (2, 1)] 

 

See Also 

======== 

 

Permutation 

""" 

def __missing__(self, arg): 

"""Enter arg into dictionary and return arg.""" 

arg = as_int(arg) 

self[arg] = arg 

return arg 

 

def __iter__(self): 

for i in self.list(): 

yield i 

 

def __call__(self, *other): 

"""Return product of cycles processed from R to L. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Cycle as C 

>>> from sympy.combinatorics.permutations import Permutation as Perm 

>>> C(1, 2)(2, 3) 

(1 3 2) 

 

An instance of a Cycle will automatically parse list-like 

objects and Permutations that are on the right. It is more 

flexible than the Permutation in that all elements need not 

be present: 

 

>>> a = C(1, 2) 

>>> a(2, 3) 

(1 3 2) 

>>> a(2, 3)(4, 5) 

(1 3 2)(4 5) 

 

""" 

rv = Cycle(*other) 

for k, v in zip(list(self.keys()), [rv[self[k]] for k in self.keys()]): 

rv[k] = v 

return rv 

 

def list(self, size=None): 

"""Return the cycles as an explicit list starting from 0 up 

to the greater of the largest value in the cycles and size. 

 

Truncation of trailing unmoved items will occur when size 

is less than the maximum element in the cycle; if this is 

desired, setting ``size=-1`` will guarantee such trimming. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Cycle 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.print_cyclic = False 

>>> p = Cycle(2, 3)(4, 5) 

>>> p.list() 

[0, 1, 3, 2, 5, 4] 

>>> p.list(10) 

[0, 1, 3, 2, 5, 4, 6, 7, 8, 9] 

 

Passing a length too small will trim trailing, unchanged elements 

in the permutation: 

 

>>> Cycle(2, 4)(1, 2, 4).list(-1) 

[0, 2, 1] 

""" 

if not self and size is None: 

raise ValueError('must give size for empty Cycle') 

if size is not None: 

big = max([i for i in self.keys() if self[i] != i] + [0]) 

size = max(size, big + 1) 

else: 

size = self.size 

return [self[i] for i in range(size)] 

 

def __repr__(self): 

"""We want it to print as a Cycle, not as a dict. 

 

Examples 

======== 

 

>>> from sympy.combinatorics import Cycle 

>>> Cycle(1, 2) 

(1 2) 

>>> print(_) 

(1 2) 

>>> list(Cycle(1, 2).items()) 

[(1, 2), (2, 1)] 

""" 

if not self: 

return 'Cycle()' 

cycles = Permutation(self).cyclic_form 

s = ''.join(str(tuple(c)) for c in cycles) 

big = self.size - 1 

if not any(i == big for c in cycles for i in c): 

s += '(%s)' % big 

return 'Cycle%s' % s 

 

def __str__(self): 

"""We want it to be printed in a Cycle notation with no 

comma in-between. 

 

Examples 

======== 

 

>>> from sympy.combinatorics import Cycle 

>>> Cycle(1, 2) 

(1 2) 

>>> Cycle(1, 2, 4)(5, 6) 

(1 2 4)(5 6) 

""" 

if not self: 

return '()' 

cycles = Permutation(self).cyclic_form 

s = ''.join(str(tuple(c)) for c in cycles) 

big = self.size - 1 

if not any(i == big for c in cycles for i in c): 

s += '(%s)' % big 

s = s.replace(',', '') 

return s 

 

def __init__(self, *args): 

"""Load up a Cycle instance with the values for the cycle. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Cycle 

>>> Cycle(1, 2, 6) 

(1 2 6) 

""" 

 

if not args: 

return 

if len(args) == 1: 

if isinstance(args[0], Permutation): 

for c in args[0].cyclic_form: 

self.update(self(*c)) 

return 

elif isinstance(args[0], Cycle): 

for k, v in args[0].items(): 

self[k] = v 

return 

args = [as_int(a) for a in args] 

if any(i < 0 for i in args): 

raise ValueError('negative integers are not allowed in a cycle.') 

if has_dups(args): 

raise ValueError('All elements must be unique in a cycle.') 

for i in range(-len(args), 0): 

self[args[i]] = args[i + 1] 

 

@property 

def size(self): 

if not self: 

return 0 

return max(self.keys()) + 1 

 

def copy(self): 

return Cycle(self) 

 

class Permutation(Basic): 

""" 

A permutation, alternatively known as an 'arrangement number' or 'ordering' 

is an arrangement of the elements of an ordered list into a one-to-one 

mapping with itself. The permutation of a given arrangement is given by 

indicating the positions of the elements after re-arrangement [2]_. For 

example, if one started with elements [x, y, a, b] (in that order) and 

they were reordered as [x, y, b, a] then the permutation would be 

[0, 1, 3, 2]. Notice that (in SymPy) the first element is always referred 

to as 0 and the permutation uses the indices of the elements in the 

original ordering, not the elements (a, b, etc...) themselves. 

 

>>> from sympy.combinatorics import Permutation 

>>> Permutation.print_cyclic = False 

 

Permutations Notation 

===================== 

 

Permutations are commonly represented in disjoint cycle or array forms. 

 

Array Notation and 2-line Form 

------------------------------------ 

 

In the 2-line form, the elements and their final positions are shown 

as a matrix with 2 rows: 

 

[0 1 2 ... n-1] 

[p(0) p(1) p(2) ... p(n-1)] 

 

Since the first line is always range(n), where n is the size of p, 

it is sufficient to represent the permutation by the second line, 

referred to as the "array form" of the permutation. This is entered 

in brackets as the argument to the Permutation class: 

 

>>> p = Permutation([0, 2, 1]); p 

Permutation([0, 2, 1]) 

 

Given i in range(p.size), the permutation maps i to i^p 

 

>>> [i^p for i in range(p.size)] 

[0, 2, 1] 

 

The composite of two permutations p*q means first apply p, then q, so 

i^(p*q) = (i^p)^q which is i^p^q according to Python precedence rules: 

 

>>> q = Permutation([2, 1, 0]) 

>>> [i^p^q for i in range(3)] 

[2, 0, 1] 

>>> [i^(p*q) for i in range(3)] 

[2, 0, 1] 

 

One can use also the notation p(i) = i^p, but then the composition 

rule is (p*q)(i) = q(p(i)), not p(q(i)): 

 

>>> [(p*q)(i) for i in range(p.size)] 

[2, 0, 1] 

>>> [q(p(i)) for i in range(p.size)] 

[2, 0, 1] 

>>> [p(q(i)) for i in range(p.size)] 

[1, 2, 0] 

 

Disjoint Cycle Notation 

----------------------- 

 

In disjoint cycle notation, only the elements that have shifted are 

indicated. In the above case, the 2 and 1 switched places. This can 

be entered in two ways: 

 

>>> Permutation(1, 2) == Permutation([[1, 2]]) == p 

True 

 

Only the relative ordering of elements in a cycle matter: 

 

>>> Permutation(1,2,3) == Permutation(2,3,1) == Permutation(3,1,2) 

True 

 

The disjoint cycle notation is convenient when representing permutations 

that have several cycles in them: 

 

>>> Permutation(1, 2)(3, 5) == Permutation([[1, 2], [3, 5]]) 

True 

 

It also provides some economy in entry when computing products of 

permutations that are written in disjoint cycle notation: 

 

>>> Permutation(1, 2)(1, 3)(2, 3) 

Permutation([0, 3, 2, 1]) 

>>> _ == Permutation([[1, 2]])*Permutation([[1, 3]])*Permutation([[2, 3]]) 

True 

 

Entering a singleton in a permutation is a way to indicate the size of the 

permutation. The ``size`` keyword can also be used. 

 

Array-form entry: 

 

>>> Permutation([[1, 2], [9]]) 

Permutation([0, 2, 1], size=10) 

>>> Permutation([[1, 2]], size=10) 

Permutation([0, 2, 1], size=10) 

 

Cyclic-form entry: 

 

>>> Permutation(1, 2, size=10) 

Permutation([0, 2, 1], size=10) 

>>> Permutation(9)(1, 2) 

Permutation([0, 2, 1], size=10) 

 

Caution: no singleton containing an element larger than the largest 

in any previous cycle can be entered. This is an important difference 

in how Permutation and Cycle handle the __call__ syntax. A singleton 

argument at the start of a Permutation performs instantiation of the 

Permutation and is permitted: 

 

>>> Permutation(5) 

Permutation([], size=6) 

 

A singleton entered after instantiation is a call to the permutation 

-- a function call -- and if the argument is out of range it will 

trigger an error. For this reason, it is better to start the cycle 

with the singleton: 

 

The following fails because there is is no element 3: 

 

>>> Permutation(1, 2)(3) 

Traceback (most recent call last): 

... 

IndexError: list index out of range 

 

This is ok: only the call to an out of range singleton is prohibited; 

otherwise the permutation autosizes: 

 

>>> Permutation(3)(1, 2) 

Permutation([0, 2, 1, 3]) 

>>> Permutation(1, 2)(3, 4) == Permutation(3, 4)(1, 2) 

True 

 

 

Equality testing 

---------------- 

 

The array forms must be the same in order for permutations to be equal: 

 

>>> Permutation([1, 0, 2, 3]) == Permutation([1, 0]) 

False 

 

 

Identity Permutation 

-------------------- 

 

The identity permutation is a permutation in which no element is out of 

place. It can be entered in a variety of ways. All the following create 

an identity permutation of size 4: 

 

>>> I = Permutation([0, 1, 2, 3]) 

>>> all(p == I for p in [ 

... Permutation(3), 

... Permutation(range(4)), 

... Permutation([], size=4), 

... Permutation(size=4)]) 

True 

 

Watch out for entering the range *inside* a set of brackets (which is 

cycle notation): 

 

>>> I == Permutation([range(4)]) 

False 

 

 

Permutation Printing 

==================== 

 

There are a few things to note about how Permutations are printed. 

 

1) If you prefer one form (array or cycle) over another, you can set that 

with the print_cyclic flag. 

 

>>> Permutation(1, 2)(4, 5)(3, 4) 

Permutation([0, 2, 1, 4, 5, 3]) 

>>> p = _ 

 

>>> Permutation.print_cyclic = True 

>>> p 

(1 2)(3 4 5) 

>>> Permutation.print_cyclic = False 

 

2) Regardless of the setting, a list of elements in the array for cyclic 

form can be obtained and either of those can be copied and supplied as 

the argument to Permutation: 

 

>>> p.array_form 

[0, 2, 1, 4, 5, 3] 

>>> p.cyclic_form 

[[1, 2], [3, 4, 5]] 

>>> Permutation(_) == p 

True 

 

3) Printing is economical in that as little as possible is printed while 

retaining all information about the size of the permutation: 

 

>>> Permutation([1, 0, 2, 3]) 

Permutation([1, 0, 2, 3]) 

>>> Permutation([1, 0, 2, 3], size=20) 

Permutation([1, 0], size=20) 

>>> Permutation([1, 0, 2, 4, 3, 5, 6], size=20) 

Permutation([1, 0, 2, 4, 3], size=20) 

 

>>> p = Permutation([1, 0, 2, 3]) 

>>> Permutation.print_cyclic = True 

>>> p 

(3)(0 1) 

>>> Permutation.print_cyclic = False 

 

The 2 was not printed but it is still there as can be seen with the 

array_form and size methods: 

 

>>> p.array_form 

[1, 0, 2, 3] 

>>> p.size 

4 

 

Short introduction to other methods 

=================================== 

 

The permutation can act as a bijective function, telling what element is 

located at a given position 

 

>>> q = Permutation([5, 2, 3, 4, 1, 0]) 

>>> q.array_form[1] # the hard way 

2 

>>> q(1) # the easy way 

2 

>>> {i: q(i) for i in range(q.size)} # showing the bijection 

{0: 5, 1: 2, 2: 3, 3: 4, 4: 1, 5: 0} 

 

The full cyclic form (including singletons) can be obtained: 

 

>>> p.full_cyclic_form 

[[0, 1], [2], [3]] 

 

Any permutation can be factored into transpositions of pairs of elements: 

 

>>> Permutation([[1, 2], [3, 4, 5]]).transpositions() 

[(1, 2), (3, 5), (3, 4)] 

>>> Permutation.rmul(*[Permutation([ti], size=6) for ti in _]).cyclic_form 

[[1, 2], [3, 4, 5]] 

 

The number of permutations on a set of n elements is given by n! and is 

called the cardinality. 

 

>>> p.size 

4 

>>> p.cardinality 

24 

 

A given permutation has a rank among all the possible permutations of the 

same elements, but what that rank is depends on how the permutations are 

enumerated. (There are a number of different methods of doing so.) The 

lexicographic rank is given by the rank method and this rank is used to 

increment a permutation with addition/subtraction: 

 

>>> p.rank() 

6 

>>> p + 1 

Permutation([1, 0, 3, 2]) 

>>> p.next_lex() 

Permutation([1, 0, 3, 2]) 

>>> _.rank() 

7 

>>> p.unrank_lex(p.size, rank=7) 

Permutation([1, 0, 3, 2]) 

 

The product of two permutations p and q is defined as their composition as 

functions, (p*q)(i) = q(p(i)) [6]_. 

 

>>> p = Permutation([1, 0, 2, 3]) 

>>> q = Permutation([2, 3, 1, 0]) 

>>> list(q*p) 

[2, 3, 0, 1] 

>>> list(p*q) 

[3, 2, 1, 0] 

>>> [q(p(i)) for i in range(p.size)] 

[3, 2, 1, 0] 

 

The permutation can be 'applied' to any list-like object, not only 

Permutations: 

 

>>> p(['zero', 'one', 'four', 'two']) 

['one', 'zero', 'four', 'two'] 

>>> p('zo42') 

['o', 'z', '4', '2'] 

 

If you have a list of arbitrary elements, the corresponding permutation 

can be found with the from_sequence method: 

 

>>> Permutation.from_sequence('SymPy') 

Permutation([1, 3, 2, 0, 4]) 

 

See Also 

======== 

 

Cycle 

 

References 

========== 

 

.. [1] Skiena, S. 'Permutations.' 1.1 in Implementing Discrete Mathematics 

Combinatorics and Graph Theory with Mathematica. Reading, MA: 

Addison-Wesley, pp. 3-16, 1990. 

 

.. [2] Knuth, D. E. The Art of Computer Programming, Vol. 4: Combinatorial 

Algorithms, 1st ed. Reading, MA: Addison-Wesley, 2011. 

 

.. [3] Wendy Myrvold and Frank Ruskey. 2001. Ranking and unranking 

permutations in linear time. Inf. Process. Lett. 79, 6 (September 2001), 

281-284. DOI=10.1016/S0020-0190(01)00141-7 

 

.. [4] D. L. Kreher, D. R. Stinson 'Combinatorial Algorithms' 

CRC Press, 1999 

 

.. [5] Graham, R. L.; Knuth, D. E.; and Patashnik, O. 

Concrete Mathematics: A Foundation for Computer Science, 2nd ed. 

Reading, MA: Addison-Wesley, 1994. 

 

.. [6] http://en.wikipedia.org/wiki/Permutation#Product_and_inverse 

 

.. [7] http://en.wikipedia.org/wiki/Lehmer_code 

 

""" 

 

is_Permutation = True 

 

_array_form = None 

_cyclic_form = None 

_cycle_structure = None 

_size = None 

_rank = None 

 

def __new__(cls, *args, **kwargs): 

""" 

Constructor for the Permutation object from a list or a 

list of lists in which all elements of the permutation may 

appear only once. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.print_cyclic = False 

 

Permutations entered in array-form are left unaltered: 

 

>>> Permutation([0, 2, 1]) 

Permutation([0, 2, 1]) 

 

Permutations entered in cyclic form are converted to array form; 

singletons need not be entered, but can be entered to indicate the 

largest element: 

 

>>> Permutation([[4, 5, 6], [0, 1]]) 

Permutation([1, 0, 2, 3, 5, 6, 4]) 

>>> Permutation([[4, 5, 6], [0, 1], [19]]) 

Permutation([1, 0, 2, 3, 5, 6, 4], size=20) 

 

All manipulation of permutations assumes that the smallest element 

is 0 (in keeping with 0-based indexing in Python) so if the 0 is 

missing when entering a permutation in array form, an error will be 

raised: 

 

>>> Permutation([2, 1]) 

Traceback (most recent call last): 

... 

ValueError: Integers 0 through 2 must be present. 

 

If a permutation is entered in cyclic form, it can be entered without 

singletons and the ``size`` specified so those values can be filled 

in, otherwise the array form will only extend to the maximum value 

in the cycles: 

 

>>> Permutation([[1, 4], [3, 5, 2]], size=10) 

Permutation([0, 4, 3, 5, 1, 2], size=10) 

>>> _.array_form 

[0, 4, 3, 5, 1, 2, 6, 7, 8, 9] 

""" 

size = kwargs.pop('size', None) 

if size is not None: 

size = int(size) 

 

#a) () 

#b) (1) = identity 

#c) (1, 2) = cycle 

#d) ([1, 2, 3]) = array form 

#e) ([[1, 2]]) = cyclic form 

#f) (Cycle) = conversion to permutation 

#g) (Permutation) = adjust size or return copy 

ok = True 

if not args: # a 

return _af_new(list(range(size or 0))) 

elif len(args) > 1: # c 

return _af_new(Cycle(*args).list(size)) 

if len(args) == 1: 

a = args[0] 

if isinstance(a, Perm): # g 

if size is None or size == a.size: 

return a 

return Perm(a.array_form, size=size) 

if isinstance(a, Cycle): # f 

return _af_new(a.list(size)) 

if not is_sequence(a): # b 

return _af_new(list(range(a + 1))) 

if has_variety(is_sequence(ai) for ai in a): 

ok = False 

else: 

ok = False 

if not ok: 

raise ValueError("Permutation argument must be a list of ints, " 

"a list of lists, Permutation or Cycle.") 

 

 

# safe to assume args are valid; this also makes a copy 

# of the args 

args = list(args[0]) 

 

is_cycle = args and is_sequence(args[0]) 

if is_cycle: # e 

args = [[int(i) for i in c] for c in args] 

else: # d 

args = [int(i) for i in args] 

 

# if there are n elements present, 0, 1, ..., n-1 should be present 

# unless a cycle notation has been provided. A 0 will be added 

# for convenience in case one wants to enter permutations where 

# counting starts from 1. 

 

temp = flatten(args) 

if has_dups(temp): 

if is_cycle: 

raise ValueError('there were repeated elements; to resolve ' 

'cycles use Cycle%s.' % ''.join([str(tuple(c)) for c in args])) 

else: 

raise ValueError('there were repeated elements.') 

temp = set(temp) 

 

if not is_cycle and \ 

any(i not in temp for i in range(len(temp))): 

raise ValueError("Integers 0 through %s must be present." % 

max(temp)) 

 

if is_cycle: 

# it's not necessarily canonical so we won't store 

# it -- use the array form instead 

c = Cycle() 

for ci in args: 

c = c(*ci) 

aform = c.list() 

else: 

aform = list(args) 

if size and size > len(aform): 

# don't allow for truncation of permutation which 

# might split a cycle and lead to an invalid aform 

# but do allow the permutation size to be increased 

aform.extend(list(range(len(aform), size))) 

size = len(aform) 

obj = Basic.__new__(cls, aform) 

obj._array_form = aform 

obj._size = size 

return obj 

 

@staticmethod 

def _af_new(perm): 

"""A method to produce a Permutation object from a list; 

the list is bound to the _array_form attribute, so it must 

not be modified; this method is meant for internal use only; 

the list ``a`` is supposed to be generated as a temporary value 

in a method, so p = Perm._af_new(a) is the only object 

to hold a reference to ``a``:: 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Perm 

>>> Perm.print_cyclic = False 

>>> a = [2,1,3,0] 

>>> p = Perm._af_new(a) 

>>> p 

Permutation([2, 1, 3, 0]) 

 

""" 

p = Basic.__new__(Perm, perm) 

p._array_form = perm 

p._size = len(perm) 

return p 

 

def _hashable_content(self): 

# the array_form (a list) is the Permutation arg, so we need to 

# return a tuple, instead 

return tuple(self.array_form) 

 

@property 

def array_form(self): 

""" 

Return a copy of the attribute _array_form 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.print_cyclic = False 

>>> p = Permutation([[2, 0], [3, 1]]) 

>>> p.array_form 

[2, 3, 0, 1] 

>>> Permutation([[2, 0, 3, 1]]).array_form 

[3, 2, 0, 1] 

>>> Permutation([2, 0, 3, 1]).array_form 

[2, 0, 3, 1] 

>>> Permutation([[1, 2], [4, 5]]).array_form 

[0, 2, 1, 3, 5, 4] 

""" 

return self._array_form[:] 

 

def __repr__(self): 

from sympy.combinatorics.permutations import Permutation, Cycle 

if Permutation.print_cyclic: 

if not self.size: 

return 'Permutation()' 

# before taking Cycle notation, see if the last element is 

# a singleton and move it to the head of the string 

s = Cycle(self)(self.size - 1).__repr__()[len('Cycle'):] 

last = s.rfind('(') 

if not last == 0 and ',' not in s[last:]: 

s = s[last:] + s[:last] 

return 'Permutation%s' %s 

else: 

s = self.support() 

if not s: 

if self.size < 5: 

return 'Permutation(%s)' % str(self.array_form) 

return 'Permutation([], size=%s)' % self.size 

trim = str(self.array_form[:s[-1] + 1]) + ', size=%s' % self.size 

use = full = str(self.array_form) 

if len(trim) < len(full): 

use = trim 

return 'Permutation%s' % use 

 

def list(self, size=None): 

"""Return the permutation as an explicit list, possibly 

trimming unmoved elements if size is less than the maximum 

element in the permutation; if this is desired, setting 

``size=-1`` will guarantee such trimming. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.print_cyclic = False 

>>> p = Permutation(2, 3)(4, 5) 

>>> p.list() 

[0, 1, 3, 2, 5, 4] 

>>> p.list(10) 

[0, 1, 3, 2, 5, 4, 6, 7, 8, 9] 

 

Passing a length too small will trim trailing, unchanged elements 

in the permutation: 

 

>>> Permutation(2, 4)(1, 2, 4).list(-1) 

[0, 2, 1] 

>>> Permutation(3).list(-1) 

[] 

""" 

if not self and size is None: 

raise ValueError('must give size for empty Cycle') 

rv = self.array_form 

if size is not None: 

if size > self.size: 

rv.extend(list(range(self.size, size))) 

else: 

# find first value from rhs where rv[i] != i 

i = self.size - 1 

while rv: 

if rv[-1] != i: 

break 

rv.pop() 

i -= 1 

return rv 

 

@property 

def cyclic_form(self): 

""" 

This is used to convert to the cyclic notation 

from the canonical notation. Singletons are omitted. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.print_cyclic = False 

>>> p = Permutation([0, 3, 1, 2]) 

>>> p.cyclic_form 

[[1, 3, 2]] 

>>> Permutation([1, 0, 2, 4, 3, 5]).cyclic_form 

[[0, 1], [3, 4]] 

 

See Also 

======== 

 

array_form, full_cyclic_form 

""" 

if self._cyclic_form is not None: 

return list(self._cyclic_form) 

array_form = self.array_form 

unchecked = [True] * len(array_form) 

cyclic_form = [] 

for i in range(len(array_form)): 

if unchecked[i]: 

cycle = [] 

cycle.append(i) 

unchecked[i] = False 

j = i 

while unchecked[array_form[j]]: 

j = array_form[j] 

cycle.append(j) 

unchecked[j] = False 

if len(cycle) > 1: 

cyclic_form.append(cycle) 

assert cycle == list(minlex(cycle, is_set=True)) 

cyclic_form.sort() 

self._cyclic_form = cyclic_form[:] 

return cyclic_form 

 

@property 

def full_cyclic_form(self): 

"""Return permutation in cyclic form including singletons. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation([0, 2, 1]).full_cyclic_form 

[[0], [1, 2]] 

""" 

need = set(range(self.size)) - set(flatten(self.cyclic_form)) 

rv = self.cyclic_form 

rv.extend([[i] for i in need]) 

rv.sort() 

return rv 

 

@property 

def size(self): 

""" 

Returns the number of elements in the permutation. 

 

Examples 

======== 

 

>>> from sympy.combinatorics import Permutation 

>>> Permutation([[3, 2], [0, 1]]).size 

4 

 

See Also 

======== 

 

cardinality, length, order, rank 

""" 

return self._size 

 

def support(self): 

"""Return the elements in permutation, P, for which P[i] != i. 

 

Examples 

======== 

 

>>> from sympy.combinatorics import Permutation 

>>> p = Permutation([[3, 2], [0, 1], [4]]) 

>>> p.array_form 

[1, 0, 3, 2, 4] 

>>> p.support() 

[0, 1, 2, 3] 

""" 

a = self.array_form 

return [i for i, e in enumerate(a) if a[i] != i] 

 

def __add__(self, other): 

"""Return permutation that is other higher in rank than self. 

 

The rank is the lexicographical rank, with the identity permutation 

having rank of 0. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.print_cyclic = False 

>>> I = Permutation([0, 1, 2, 3]) 

>>> a = Permutation([2, 1, 3, 0]) 

>>> I + a.rank() == a 

True 

 

See Also 

======== 

 

__sub__, inversion_vector 

 

""" 

rank = (self.rank() + other) % self.cardinality 

rv = Perm.unrank_lex(self.size, rank) 

rv._rank = rank 

return rv 

 

def __sub__(self, other): 

"""Return the permutation that is other lower in rank than self. 

 

See Also 

======== 

 

__add__ 

""" 

return self.__add__(-other) 

 

@staticmethod 

def rmul(*args): 

""" 

Return product of Permutations [a, b, c, ...] as the Permutation whose 

ith value is a(b(c(i))). 

 

a, b, c, ... can be Permutation objects or tuples. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import _af_rmul, Permutation 

>>> Permutation.print_cyclic = False 

 

>>> a, b = [1, 0, 2], [0, 2, 1] 

>>> a = Permutation(a); b = Permutation(b) 

>>> list(Permutation.rmul(a, b)) 

[1, 2, 0] 

>>> [a(b(i)) for i in range(3)] 

[1, 2, 0] 

 

This handles the operands in reverse order compared to the ``*`` operator: 

 

>>> a = Permutation(a); b = Permutation(b) 

>>> list(a*b) 

[2, 0, 1] 

>>> [b(a(i)) for i in range(3)] 

[2, 0, 1] 

 

Notes 

===== 

 

All items in the sequence will be parsed by Permutation as 

necessary as long as the first item is a Permutation: 

 

>>> Permutation.rmul(a, [0, 2, 1]) == Permutation.rmul(a, b) 

True 

 

The reverse order of arguments will raise a TypeError. 

 

""" 

rv = args[0] 

for i in range(1, len(args)): 

rv = args[i]*rv 

return rv 

 

@staticmethod 

def rmul_with_af(*args): 

""" 

same as rmul, but the elements of args are Permutation objects 

which have _array_form 

""" 

a = [x._array_form for x in args] 

rv = _af_new(_af_rmuln(*a)) 

return rv 

 

def mul_inv(self, other): 

""" 

other*~self, self and other have _array_form 

""" 

a = _af_invert(self._array_form) 

b = other._array_form 

return _af_new(_af_rmul(a, b)) 

 

def __rmul__(self, other): 

"""This is needed to coerse other to Permutation in rmul.""" 

return Perm(other)*self 

 

def __mul__(self, other): 

""" 

Return the product a*b as a Permutation; the ith value is b(a(i)). 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import _af_rmul, Permutation 

>>> Permutation.print_cyclic = False 

 

>>> a, b = [1, 0, 2], [0, 2, 1] 

>>> a = Permutation(a); b = Permutation(b) 

>>> list(a*b) 

[2, 0, 1] 

>>> [b(a(i)) for i in range(3)] 

[2, 0, 1] 

 

This handles operands in reverse order compared to _af_rmul and rmul: 

 

>>> al = list(a); bl = list(b) 

>>> _af_rmul(al, bl) 

[1, 2, 0] 

>>> [al[bl[i]] for i in range(3)] 

[1, 2, 0] 

 

It is acceptable for the arrays to have different lengths; the shorter 

one will be padded to match the longer one: 

 

>>> b*Permutation([1, 0]) 

Permutation([1, 2, 0]) 

>>> Permutation([1, 0])*b 

Permutation([2, 0, 1]) 

 

It is also acceptable to allow coercion to handle conversion of a 

single list to the left of a Permutation: 

 

>>> [0, 1]*a # no change: 2-element identity 

Permutation([1, 0, 2]) 

>>> [[0, 1]]*a # exchange first two elements 

Permutation([0, 1, 2]) 

 

You cannot use more than 1 cycle notation in a product of cycles 

since coercion can only handle one argument to the left. To handle 

multiple cycles it is convenient to use Cycle instead of Permutation: 

 

>>> [[1, 2]]*[[2, 3]]*Permutation([]) # doctest: +SKIP 

>>> from sympy.combinatorics.permutations import Cycle 

>>> Cycle(1, 2)(2, 3) 

(1 3 2) 

 

""" 

a = self.array_form 

# __rmul__ makes sure the other is a Permutation 

b = other.array_form 

if not b: 

perm = a 

else: 

b.extend(list(range(len(b), len(a)))) 

perm = [b[i] for i in a] + b[len(a):] 

return _af_new(perm) 

 

def commutes_with(self, other): 

""" 

Checks if the elements are commuting. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> a = Permutation([1, 4, 3, 0, 2, 5]) 

>>> b = Permutation([0, 1, 2, 3, 4, 5]) 

>>> a.commutes_with(b) 

True 

>>> b = Permutation([2, 3, 5, 4, 1, 0]) 

>>> a.commutes_with(b) 

False 

""" 

a = self.array_form 

b = other.array_form 

return _af_commutes_with(a, b) 

 

def __pow__(self, n): 

""" 

Routine for finding powers of a permutation. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.print_cyclic = False 

>>> p = Permutation([2,0,3,1]) 

>>> p.order() 

4 

>>> p**4 

Permutation([0, 1, 2, 3]) 

""" 

if type(n) == Perm: 

raise NotImplementedError( 

'p**p is not defined; do you mean p^p (conjugate)?') 

n = int(n) 

return _af_new(_af_pow(self.array_form, n)) 

 

def __rxor__(self, i): 

"""Return self(i) when ``i`` is an int. 

 

Examples 

======== 

 

>>> from sympy.combinatorics import Permutation 

>>> p = Permutation(1, 2, 9) 

>>> 2^p == p(2) == 9 

True 

""" 

if int(i) == i: 

return self(i) 

else: 

raise NotImplementedError( 

"i^p = p(i) when i is an integer, not %s." % i) 

 

def __xor__(self, h): 

"""Return the conjugate permutation ``~h*self*h` `. 

 

If ``a`` and ``b`` are conjugates, ``a = h*b*~h`` and 

``b = ~h*a*h`` and both have the same cycle structure. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.print_cyclic = True 

>>> p = Permutation(1, 2, 9) 

>>> q = Permutation(6, 9, 8) 

>>> p*q != q*p 

True 

 

Calculate and check properties of the conjugate: 

 

>>> c = p^q 

>>> c == ~q*p*q and p == q*c*~q 

True 

 

The expression q^p^r is equivalent to q^(p*r): 

 

>>> r = Permutation(9)(4, 6, 8) 

>>> q^p^r == q^(p*r) 

True 

 

If the term to the left of the conjugate operator, i, is an integer 

then this is interpreted as selecting the ith element from the 

permutation to the right: 

 

>>> all(i^p == p(i) for i in range(p.size)) 

True 

 

Note that the * operator as higher precedence than the ^ operator: 

 

>>> q^r*p^r == q^(r*p)^r == Permutation(9)(1, 6, 4) 

True 

 

Notes 

===== 

 

In Python the precedence rule is p^q^r = (p^q)^r which differs 

in general from p^(q^r) 

 

>>> q^p^r 

(9)(1 4 8) 

>>> q^(p^r) 

(9)(1 8 6) 

 

For a given r and p, both of the following are conjugates of p: 

~r*p*r and r*p*~r. But these are not necessarily the same: 

 

>>> ~r*p*r == r*p*~r 

True 

 

>>> p = Permutation(1, 2, 9)(5, 6) 

>>> ~r*p*r == r*p*~r 

False 

 

The conjugate ~r*p*r was chosen so that ``p^q^r`` would be equivalent 

to ``p^(q*r)`` rather than ``p^(r*q)``. To obtain r*p*~r, pass ~r to 

this method: 

 

>>> p^~r == r*p*~r 

True 

""" 

 

if self.size != h.size: 

raise ValueError("The permutations must be of equal size.") 

a = [None]*self.size 

h = h._array_form 

p = self._array_form 

for i in range(self.size): 

a[h[i]] = h[p[i]] 

return _af_new(a) 

 

def transpositions(self): 

""" 

Return the permutation decomposed into a list of transpositions. 

 

It is always possible to express a permutation as the product of 

transpositions, see [1] 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([[1, 2, 3], [0, 4, 5, 6, 7]]) 

>>> t = p.transpositions() 

>>> t 

[(0, 7), (0, 6), (0, 5), (0, 4), (1, 3), (1, 2)] 

>>> print(''.join(str(c) for c in t)) 

(0, 7)(0, 6)(0, 5)(0, 4)(1, 3)(1, 2) 

>>> Permutation.rmul(*[Permutation([ti], size=p.size) for ti in t]) == p 

True 

 

References 

========== 

 

1. http://en.wikipedia.org/wiki/Transposition_%28mathematics%29#Properties 

 

""" 

a = self.cyclic_form 

res = [] 

for x in a: 

nx = len(x) 

if nx == 2: 

res.append(tuple(x)) 

elif nx > 2: 

first = x[0] 

for y in x[nx - 1:0:-1]: 

res.append((first, y)) 

return res 

 

@classmethod 

def from_sequence(self, i, key=None): 

"""Return the permutation needed to obtain ``i`` from the sorted 

elements of ``i``. If custom sorting is desired, a key can be given. 

 

Examples 

======== 

 

>>> from sympy.combinatorics import Permutation 

>>> Permutation.print_cyclic = True 

 

>>> Permutation.from_sequence('SymPy') 

(4)(0 1 3) 

>>> _(sorted("SymPy")) 

['S', 'y', 'm', 'P', 'y'] 

>>> Permutation.from_sequence('SymPy', key=lambda x: x.lower()) 

(4)(0 2)(1 3) 

""" 

ic = list(zip(i, list(range(len(i))))) 

if key: 

ic.sort(key=lambda x: key(x[0])) 

else: 

ic.sort() 

return ~Permutation([i[1] for i in ic]) 

 

def __invert__(self): 

""" 

Return the inverse of the permutation. 

 

A permutation multiplied by its inverse is the identity permutation. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([[2,0], [3,1]]) 

>>> ~p 

Permutation([2, 3, 0, 1]) 

>>> _ == p**-1 

True 

>>> p*~p == ~p*p == Permutation([0, 1, 2, 3]) 

True 

""" 

return _af_new(_af_invert(self._array_form)) 

 

def __iter__(self): 

"""Yield elements from array form. 

 

Examples 

======== 

 

>>> from sympy.combinatorics import Permutation 

>>> list(Permutation(range(3))) 

[0, 1, 2] 

""" 

for i in self.array_form: 

yield i 

 

def __call__(self, *i): 

""" 

Allows applying a permutation instance as a bijective function. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([[2, 0], [3, 1]]) 

>>> p.array_form 

[2, 3, 0, 1] 

>>> [p(i) for i in range(4)] 

[2, 3, 0, 1] 

 

If an array is given then the permutation selects the items 

from the array (i.e. the permutation is applied to the array): 

 

>>> from sympy.abc import x 

>>> p([x, 1, 0, x**2]) 

[0, x**2, x, 1] 

""" 

# list indices can be Integer or int; leave this 

# as it is (don't test or convert it) because this 

# gets called a lot and should be fast 

if len(i) == 1: 

i = i[0] 

try: 

# P(1) 

return self._array_form[i] 

except TypeError: 

try: 

# P([a, b, c]) 

return [i[j] for j in self._array_form] 

except Exception: 

raise TypeError('unrecognized argument') 

else: 

# P(1, 2, 3) 

return self*Permutation(Cycle(*i), size=self.size) 

 

def atoms(self): 

""" 

Returns all the elements of a permutation 

 

Examples 

======== 

 

>>> from sympy.combinatorics import Permutation 

>>> Permutation([0, 1, 2, 3, 4, 5]).atoms() 

set([0, 1, 2, 3, 4, 5]) 

>>> Permutation([[0, 1], [2, 3], [4, 5]]).atoms() 

set([0, 1, 2, 3, 4, 5]) 

""" 

return set(self.array_form) 

 

def next_lex(self): 

""" 

Returns the next permutation in lexicographical order. 

If self is the last permutation in lexicographical order 

it returns None. 

See [4] section 2.4. 

 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([2, 3, 1, 0]) 

>>> p = Permutation([2, 3, 1, 0]); p.rank() 

17 

>>> p = p.next_lex(); p.rank() 

18 

 

See Also 

======== 

 

rank, unrank_lex 

""" 

perm = self.array_form[:] 

n = len(perm) 

i = n - 2 

while perm[i + 1] < perm[i]: 

i -= 1 

if i == -1: 

return None 

else: 

j = n - 1 

while perm[j] < perm[i]: 

j -= 1 

perm[j], perm[i] = perm[i], perm[j] 

i += 1 

j = n - 1 

while i < j: 

perm[j], perm[i] = perm[i], perm[j] 

i += 1 

j -= 1 

return _af_new(perm) 

 

@classmethod 

def unrank_nonlex(self, n, r): 

""" 

This is a linear time unranking algorithm that does not 

respect lexicographic order [3]. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.print_cyclic = False 

>>> Permutation.unrank_nonlex(4, 5) 

Permutation([2, 0, 3, 1]) 

>>> Permutation.unrank_nonlex(4, -1) 

Permutation([0, 1, 2, 3]) 

 

See Also 

======== 

 

next_nonlex, rank_nonlex 

""" 

def _unrank1(n, r, a): 

if n > 0: 

a[n - 1], a[r % n] = a[r % n], a[n - 1] 

_unrank1(n - 1, r//n, a) 

 

id_perm = list(range(n)) 

n = int(n) 

r = r % ifac(n) 

_unrank1(n, r, id_perm) 

return _af_new(id_perm) 

 

def rank_nonlex(self, inv_perm=None): 

""" 

This is a linear time ranking algorithm that does not 

enforce lexicographic order [3]. 

 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([0, 1, 2, 3]) 

>>> p.rank_nonlex() 

23 

 

See Also 

======== 

 

next_nonlex, unrank_nonlex 

""" 

def _rank1(n, perm, inv_perm): 

if n == 1: 

return 0 

s = perm[n - 1] 

t = inv_perm[n - 1] 

perm[n - 1], perm[t] = perm[t], s 

inv_perm[n - 1], inv_perm[s] = inv_perm[s], t 

return s + n*_rank1(n - 1, perm, inv_perm) 

 

if inv_perm is None: 

inv_perm = (~self).array_form 

if not inv_perm: 

return 0 

perm = self.array_form[:] 

r = _rank1(len(perm), perm, inv_perm) 

return r 

 

def next_nonlex(self): 

""" 

Returns the next permutation in nonlex order [3]. 

If self is the last permutation in this order it returns None. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.print_cyclic = False 

>>> p = Permutation([2, 0, 3, 1]); p.rank_nonlex() 

5 

>>> p = p.next_nonlex(); p 

Permutation([3, 0, 1, 2]) 

>>> p.rank_nonlex() 

6 

 

See Also 

======== 

 

rank_nonlex, unrank_nonlex 

""" 

r = self.rank_nonlex() 

if r == ifac(self.size) - 1: 

return None 

return Perm.unrank_nonlex(self.size, r + 1) 

 

def rank(self): 

""" 

Returns the lexicographic rank of the permutation. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([0, 1, 2, 3]) 

>>> p.rank() 

0 

>>> p = Permutation([3, 2, 1, 0]) 

>>> p.rank() 

23 

 

See Also 

======== 

 

next_lex, unrank_lex, cardinality, length, order, size 

""" 

if not self._rank is None: 

return self._rank 

rank = 0 

rho = self.array_form[:] 

n = self.size - 1 

size = n + 1 

psize = int(ifac(n)) 

for j in range(size - 1): 

rank += rho[j]*psize 

for i in range(j + 1, size): 

if rho[i] > rho[j]: 

rho[i] -= 1 

psize //= n 

n -= 1 

self._rank = rank 

return rank 

 

@property 

def cardinality(self): 

""" 

Returns the number of all possible permutations. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([0, 1, 2, 3]) 

>>> p.cardinality 

24 

 

See Also 

======== 

 

length, order, rank, size 

""" 

return int(ifac(self.size)) 

 

def parity(self): 

""" 

Computes the parity of a permutation. 

 

The parity of a permutation reflects the parity of the 

number of inversions in the permutation, i.e., the 

number of pairs of x and y such that ``x > y`` but ``p[x] < p[y]``. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([0, 1, 2, 3]) 

>>> p.parity() 

0 

>>> p = Permutation([3, 2, 0, 1]) 

>>> p.parity() 

1 

 

See Also 

======== 

 

_af_parity 

""" 

if self._cyclic_form is not None: 

return (self.size - self.cycles) % 2 

 

return _af_parity(self.array_form) 

 

@property 

def is_even(self): 

""" 

Checks if a permutation is even. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([0, 1, 2, 3]) 

>>> p.is_even 

True 

>>> p = Permutation([3, 2, 1, 0]) 

>>> p.is_even 

True 

 

See Also 

======== 

 

is_odd 

""" 

return not self.is_odd 

 

@property 

def is_odd(self): 

""" 

Checks if a permutation is odd. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([0, 1, 2, 3]) 

>>> p.is_odd 

False 

>>> p = Permutation([3, 2, 0, 1]) 

>>> p.is_odd 

True 

 

See Also 

======== 

 

is_even 

""" 

return bool(self.parity() % 2) 

 

@property 

def is_Singleton(self): 

""" 

Checks to see if the permutation contains only one number and is 

thus the only possible permutation of this set of numbers 

 

Examples 

======== 

 

>>> from sympy.combinatorics import Permutation 

>>> Permutation([0]).is_Singleton 

True 

>>> Permutation([0, 1]).is_Singleton 

False 

 

See Also 

======== 

 

is_Empty 

""" 

return self.size == 1 

 

@property 

def is_Empty(self): 

""" 

Checks to see if the permutation is a set with zero elements 

 

Examples 

======== 

 

>>> from sympy.combinatorics import Permutation 

>>> Permutation([]).is_Empty 

True 

>>> Permutation([0]).is_Empty 

False 

 

See Also 

======== 

 

is_Singleton 

""" 

return self.size == 0 

 

@property 

def is_Identity(self): 

""" 

Returns True if the Permutation is an identity permutation. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([]) 

>>> p.is_Identity 

True 

>>> p = Permutation([[0], [1], [2]]) 

>>> p.is_Identity 

True 

>>> p = Permutation([0, 1, 2]) 

>>> p.is_Identity 

True 

>>> p = Permutation([0, 2, 1]) 

>>> p.is_Identity 

False 

 

See Also 

======== 

 

order 

""" 

af = self.array_form 

return not af or all(i == af[i] for i in range(self.size)) 

 

def ascents(self): 

""" 

Returns the positions of ascents in a permutation, ie, the location 

where p[i] < p[i+1] 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([4, 0, 1, 3, 2]) 

>>> p.ascents() 

[1, 2] 

 

See Also 

======== 

 

descents, inversions, min, max 

""" 

a = self.array_form 

pos = [i for i in range(len(a) - 1) if a[i] < a[i + 1]] 

return pos 

 

def descents(self): 

""" 

Returns the positions of descents in a permutation, ie, the location 

where p[i] > p[i+1] 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([4, 0, 1, 3, 2]) 

>>> p.descents() 

[0, 3] 

 

See Also 

======== 

 

ascents, inversions, min, max 

""" 

a = self.array_form 

pos = [i for i in range(len(a) - 1) if a[i] > a[i + 1]] 

return pos 

 

def max(self): 

""" 

The maximum element moved by the permutation. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([1, 0, 2, 3, 4]) 

>>> p.max() 

1 

 

See Also 

======== 

 

min, descents, ascents, inversions 

""" 

max = 0 

a = self.array_form 

for i in range(len(a)): 

if a[i] != i and a[i] > max: 

max = a[i] 

return max 

 

def min(self): 

""" 

The minimum element moved by the permutation. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([0, 1, 4, 3, 2]) 

>>> p.min() 

2 

 

See Also 

======== 

 

max, descents, ascents, inversions 

""" 

a = self.array_form 

min = len(a) 

for i in range(len(a)): 

if a[i] != i and a[i] < min: 

min = a[i] 

return min 

 

def inversions(self): 

""" 

Computes the number of inversions of a permutation. 

 

An inversion is where i > j but p[i] < p[j]. 

 

For small length of p, it iterates over all i and j 

values and calculates the number of inversions. 

For large length of p, it uses a variation of merge 

sort to calculate the number of inversions. 

 

References 

========== 

 

[1] http://www.cp.eng.chula.ac.th/~piak/teaching/algo/algo2008/count-inv.htm 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([0, 1, 2, 3, 4, 5]) 

>>> p.inversions() 

0 

>>> Permutation([3, 2, 1, 0]).inversions() 

6 

 

See Also 

======== 

 

descents, ascents, min, max 

""" 

inversions = 0 

a = self.array_form 

n = len(a) 

if n < 130: 

for i in range(n - 1): 

b = a[i] 

for c in a[i + 1:]: 

if b > c: 

inversions += 1 

else: 

k = 1 

right = 0 

arr = a[:] 

temp = a[:] 

while k < n: 

i = 0 

while i + k < n: 

right = i + k * 2 - 1 

if right >= n: 

right = n - 1 

inversions += _merge(arr, temp, i, i + k, right) 

i = i + k * 2 

k = k * 2 

return inversions 

 

def commutator(self, x): 

"""Return the commutator of self and x: ``~x*~self*x*self`` 

 

If f and g are part of a group, G, then the commutator of f and g 

is the group identity iff f and g commute, i.e. fg == gf. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.print_cyclic = False 

>>> p = Permutation([0, 2, 3, 1]) 

>>> x = Permutation([2, 0, 3, 1]) 

>>> c = p.commutator(x); c 

Permutation([2, 1, 3, 0]) 

>>> c == ~x*~p*x*p 

True 

 

>>> I = Permutation(3) 

>>> p = [I + i for i in range(6)] 

>>> for i in range(len(p)): 

... for j in range(len(p)): 

... c = p[i].commutator(p[j]) 

... if p[i]*p[j] == p[j]*p[i]: 

... assert c == I 

... else: 

... assert c != I 

... 

 

References 

========== 

 

http://en.wikipedia.org/wiki/Commutator 

""" 

 

a = self.array_form 

b = x.array_form 

n = len(a) 

if len(b) != n: 

raise ValueError("The permutations must be of equal size.") 

inva = [None]*n 

for i in range(n): 

inva[a[i]] = i 

invb = [None]*n 

for i in range(n): 

invb[b[i]] = i 

return _af_new([a[b[inva[i]]] for i in invb]) 

 

def signature(self): 

""" 

Gives the signature of the permutation needed to place the 

elements of the permutation in canonical order. 

 

The signature is calculated as (-1)^<number of inversions> 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([0, 1, 2]) 

>>> p.inversions() 

0 

>>> p.signature() 

1 

>>> q = Permutation([0,2,1]) 

>>> q.inversions() 

1 

>>> q.signature() 

-1 

 

See Also 

======== 

 

inversions 

""" 

if self.is_even: 

return 1 

return -1 

 

def order(self): 

""" 

Computes the order of a permutation. 

 

When the permutation is raised to the power of its 

order it equals the identity permutation. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.print_cyclic = False 

>>> p = Permutation([3, 1, 5, 2, 4, 0]) 

>>> p.order() 

4 

>>> (p**(p.order())) 

Permutation([], size=6) 

 

See Also 

======== 

 

identity, cardinality, length, rank, size 

""" 

 

return reduce(lcm, [len(cycle) for cycle in self.cyclic_form], 1) 

 

def length(self): 

""" 

Returns the number of integers moved by a permutation. 

 

Examples 

======== 

 

>>> from sympy.combinatorics import Permutation 

>>> Permutation([0, 3, 2, 1]).length() 

2 

>>> Permutation([[0, 1], [2, 3]]).length() 

4 

 

See Also 

======== 

 

min, max, support, cardinality, order, rank, size 

""" 

 

return len(self.support()) 

 

@property 

def cycle_structure(self): 

"""Return the cycle structure of the permutation as a dictionary 

indicating the multiplicity of each cycle length. 

 

Examples 

======== 

 

>>> from sympy.combinatorics import Permutation 

>>> Permutation.print_cyclic = True 

>>> Permutation(3).cycle_structure 

{1: 4} 

>>> Permutation(0, 4, 3)(1, 2)(5, 6).cycle_structure 

{2: 2, 3: 1} 

""" 

if self._cycle_structure: 

rv = self._cycle_structure 

else: 

rv = defaultdict(int) 

singletons = self.size 

for c in self.cyclic_form: 

rv[len(c)] += 1 

singletons -= len(c) 

if singletons: 

rv[1] = singletons 

self._cycle_structure = rv 

return dict(rv) # make a copy 

 

@property 

def cycles(self): 

""" 

Returns the number of cycles contained in the permutation 

(including singletons). 

 

Examples 

======== 

 

>>> from sympy.combinatorics import Permutation 

>>> Permutation([0, 1, 2]).cycles 

3 

>>> Permutation([0, 1, 2]).full_cyclic_form 

[[0], [1], [2]] 

>>> Permutation(0, 1)(2, 3).cycles 

2 

 

See Also 

======== 

sympy.functions.combinatorial.numbers.stirling 

""" 

return len(self.full_cyclic_form) 

 

def index(self): 

""" 

Returns the index of a permutation. 

 

The index of a permutation is the sum of all subscripts j such 

that p[j] is greater than p[j+1]. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([3, 0, 2, 1, 4]) 

>>> p.index() 

2 

""" 

a = self.array_form 

 

return sum([j for j in range(len(a) - 1) if a[j] > a[j + 1]]) 

 

def runs(self): 

""" 

Returns the runs of a permutation. 

 

An ascending sequence in a permutation is called a run [5]. 

 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([2, 5, 7, 3, 6, 0, 1, 4, 8]) 

>>> p.runs() 

[[2, 5, 7], [3, 6], [0, 1, 4, 8]] 

>>> q = Permutation([1,3,2,0]) 

>>> q.runs() 

[[1, 3], [2], [0]] 

""" 

return runs(self.array_form) 

 

def inversion_vector(self): 

"""Return the inversion vector of the permutation. 

 

The inversion vector consists of elements whose value 

indicates the number of elements in the permutation 

that are lesser than it and lie on its right hand side. 

 

The inversion vector is the same as the Lehmer encoding of a 

permutation. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([4, 8, 0, 7, 1, 5, 3, 6, 2]) 

>>> p.inversion_vector() 

[4, 7, 0, 5, 0, 2, 1, 1] 

>>> p = Permutation([3, 2, 1, 0]) 

>>> p.inversion_vector() 

[3, 2, 1] 

 

The inversion vector increases lexicographically with the rank 

of the permutation, the -ith element cycling through 0..i. 

 

>>> p = Permutation(2) 

>>> while p: 

... print('%s %s %s' % (p, p.inversion_vector(), p.rank())) 

... p = p.next_lex() 

... 

Permutation([0, 1, 2]) [0, 0] 0 

Permutation([0, 2, 1]) [0, 1] 1 

Permutation([1, 0, 2]) [1, 0] 2 

Permutation([1, 2, 0]) [1, 1] 3 

Permutation([2, 0, 1]) [2, 0] 4 

Permutation([2, 1, 0]) [2, 1] 5 

 

See Also 

======== 

from_inversion_vector 

""" 

self_array_form = self.array_form 

n = len(self_array_form) 

inversion_vector = [0] * (n - 1) 

 

for i in range(n - 1): 

val = 0 

for j in range(i + 1, n): 

if self_array_form[j] < self_array_form[i]: 

val += 1 

inversion_vector[i] = val 

return inversion_vector 

 

def rank_trotterjohnson(self): 

""" 

Returns the Trotter Johnson rank, which we get from the minimal 

change algorithm. See [4] section 2.4. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([0, 1, 2, 3]) 

>>> p.rank_trotterjohnson() 

0 

>>> p = Permutation([0, 2, 1, 3]) 

>>> p.rank_trotterjohnson() 

7 

 

See Also 

======== 

 

unrank_trotterjohnson, next_trotterjohnson 

""" 

if self.array_form == [] or self.is_Identity: 

return 0 

if self.array_form == [1, 0]: 

return 1 

perm = self.array_form 

n = self.size 

rank = 0 

for j in range(1, n): 

k = 1 

i = 0 

while perm[i] != j: 

if perm[i] < j: 

k += 1 

i += 1 

j1 = j + 1 

if rank % 2 == 0: 

rank = j1*rank + j1 - k 

else: 

rank = j1*rank + k - 1 

return rank 

 

@classmethod 

def unrank_trotterjohnson(self, size, rank): 

""" 

Trotter Johnson permutation unranking. See [4] section 2.4. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.unrank_trotterjohnson(5, 10) 

Permutation([0, 3, 1, 2, 4]) 

 

See Also 

======== 

 

rank_trotterjohnson, next_trotterjohnson 

""" 

perm = [0]*size 

r2 = 0 

n = ifac(size) 

pj = 1 

for j in range(2, size + 1): 

pj *= j 

r1 = (rank * pj) // n 

k = r1 - j*r2 

if r2 % 2 == 0: 

for i in range(j - 1, j - k - 1, -1): 

perm[i] = perm[i - 1] 

perm[j - k - 1] = j - 1 

else: 

for i in range(j - 1, k, -1): 

perm[i] = perm[i - 1] 

perm[k] = j - 1 

r2 = r1 

return _af_new(perm) 

 

def next_trotterjohnson(self): 

""" 

Returns the next permutation in Trotter-Johnson order. 

If self is the last permutation it returns None. 

See [4] section 2.4. If it is desired to generate all such 

permutations, they can be generated in order more quickly 

with the ``generate_bell`` function. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.print_cyclic = False 

>>> p = Permutation([3, 0, 2, 1]) 

>>> p.rank_trotterjohnson() 

4 

>>> p = p.next_trotterjohnson(); p 

Permutation([0, 3, 2, 1]) 

>>> p.rank_trotterjohnson() 

5 

 

See Also 

======== 

 

rank_trotterjohnson, unrank_trotterjohnson, sympy.utilities.iterables.generate_bell 

""" 

pi = self.array_form[:] 

n = len(pi) 

st = 0 

rho = pi[:] 

done = False 

m = n-1 

while m > 0 and not done: 

d = rho.index(m) 

for i in range(d, m): 

rho[i] = rho[i + 1] 

par = _af_parity(rho[:m]) 

if par == 1: 

if d == m: 

m -= 1 

else: 

pi[st + d], pi[st + d + 1] = pi[st + d + 1], pi[st + d] 

done = True 

else: 

if d == 0: 

m -= 1 

st += 1 

else: 

pi[st + d], pi[st + d - 1] = pi[st + d - 1], pi[st + d] 

done = True 

if m == 0: 

return None 

return _af_new(pi) 

 

def get_precedence_matrix(self): 

""" 

Gets the precedence matrix. This is used for computing the 

distance between two permutations. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation.josephus(3, 6, 1) 

>>> p 

Permutation([2, 5, 3, 1, 4, 0]) 

>>> p.get_precedence_matrix() 

Matrix([ 

[0, 0, 0, 0, 0, 0], 

[1, 0, 0, 0, 1, 0], 

[1, 1, 0, 1, 1, 1], 

[1, 1, 0, 0, 1, 0], 

[1, 0, 0, 0, 0, 0], 

[1, 1, 0, 1, 1, 0]]) 

 

See Also 

======== 

 

get_precedence_distance, get_adjacency_matrix, get_adjacency_distance 

""" 

m = zeros(self.size) 

perm = self.array_form 

for i in range(m.rows): 

for j in range(i + 1, m.cols): 

m[perm[i], perm[j]] = 1 

return m 

 

def get_precedence_distance(self, other): 

""" 

Computes the precedence distance between two permutations. 

 

Suppose p and p' represent n jobs. The precedence metric 

counts the number of times a job j is preceded by job i 

in both p and p'. This metric is commutative. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([2, 0, 4, 3, 1]) 

>>> q = Permutation([3, 1, 2, 4, 0]) 

>>> p.get_precedence_distance(q) 

7 

>>> q.get_precedence_distance(p) 

7 

 

See Also 

======== 

 

get_precedence_matrix, get_adjacency_matrix, get_adjacency_distance 

""" 

if self.size != other.size: 

raise ValueError("The permutations must be of equal size.") 

self_prec_mat = self.get_precedence_matrix() 

other_prec_mat = other.get_precedence_matrix() 

n_prec = 0 

for i in range(self.size): 

for j in range(self.size): 

if i == j: 

continue 

if self_prec_mat[i, j] * other_prec_mat[i, j] == 1: 

n_prec += 1 

d = self.size * (self.size - 1)//2 - n_prec 

return d 

 

def get_adjacency_matrix(self): 

""" 

Computes the adjacency matrix of a permutation. 

 

If job i is adjacent to job j in a permutation p 

then we set m[i, j] = 1 where m is the adjacency 

matrix of p. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation.josephus(3, 6, 1) 

>>> p.get_adjacency_matrix() 

Matrix([ 

[0, 0, 0, 0, 0, 0], 

[0, 0, 0, 0, 1, 0], 

[0, 0, 0, 0, 0, 1], 

[0, 1, 0, 0, 0, 0], 

[1, 0, 0, 0, 0, 0], 

[0, 0, 0, 1, 0, 0]]) 

>>> q = Permutation([0, 1, 2, 3]) 

>>> q.get_adjacency_matrix() 

Matrix([ 

[0, 1, 0, 0], 

[0, 0, 1, 0], 

[0, 0, 0, 1], 

[0, 0, 0, 0]]) 

 

See Also 

======== 

 

get_precedence_matrix, get_precedence_distance, get_adjacency_distance 

""" 

m = zeros(self.size) 

perm = self.array_form 

for i in range(self.size - 1): 

m[perm[i], perm[i + 1]] = 1 

return m 

 

def get_adjacency_distance(self, other): 

""" 

Computes the adjacency distance between two permutations. 

 

This metric counts the number of times a pair i,j of jobs is 

adjacent in both p and p'. If n_adj is this quantity then 

the adjacency distance is n - n_adj - 1 [1] 

 

[1] Reeves, Colin R. Landscapes, Operators and Heuristic search, Annals 

of Operational Research, 86, pp 473-490. (1999) 

 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([0, 3, 1, 2, 4]) 

>>> q = Permutation.josephus(4, 5, 2) 

>>> p.get_adjacency_distance(q) 

3 

>>> r = Permutation([0, 2, 1, 4, 3]) 

>>> p.get_adjacency_distance(r) 

4 

 

See Also 

======== 

 

get_precedence_matrix, get_precedence_distance, get_adjacency_matrix 

""" 

if self.size != other.size: 

raise ValueError("The permutations must be of the same size.") 

self_adj_mat = self.get_adjacency_matrix() 

other_adj_mat = other.get_adjacency_matrix() 

n_adj = 0 

for i in range(self.size): 

for j in range(self.size): 

if i == j: 

continue 

if self_adj_mat[i, j] * other_adj_mat[i, j] == 1: 

n_adj += 1 

d = self.size - n_adj - 1 

return d 

 

def get_positional_distance(self, other): 

""" 

Computes the positional distance between two permutations. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> p = Permutation([0, 3, 1, 2, 4]) 

>>> q = Permutation.josephus(4, 5, 2) 

>>> r = Permutation([3, 1, 4, 0, 2]) 

>>> p.get_positional_distance(q) 

12 

>>> p.get_positional_distance(r) 

12 

 

See Also 

======== 

 

get_precedence_distance, get_adjacency_distance 

""" 

a = self.array_form 

b = other.array_form 

if len(a) != len(b): 

raise ValueError("The permutations must be of the same size.") 

return sum([abs(a[i] - b[i]) for i in range(len(a))]) 

 

@classmethod 

def josephus(self, m, n, s=1): 

"""Return as a permutation the shuffling of range(n) using the Josephus 

scheme in which every m-th item is selected until all have been chosen. 

The returned permutation has elements listed by the order in which they 

were selected. 

 

The parameter ``s`` stops the selection process when there are ``s`` 

items remaining and these are selected by continuing the selection, 

counting by 1 rather than by ``m``. 

 

Consider selecting every 3rd item from 6 until only 2 remain:: 

 

choices chosen 

======== ====== 

012345 

01 345 2 

01 34 25 

01 4 253 

0 4 2531 

0 25314 

253140 

 

Examples 

======== 

 

>>> from sympy.combinatorics import Permutation 

>>> Permutation.josephus(3, 6, 2).array_form 

[2, 5, 3, 1, 4, 0] 

 

References 

========== 

 

1. http://en.wikipedia.org/wiki/Flavius_Josephus 

2. http://en.wikipedia.org/wiki/Josephus_problem 

3. http://www.wou.edu/~burtonl/josephus.html 

 

""" 

from collections import deque 

m -= 1 

Q = deque(list(range(n))) 

perm = [] 

while len(Q) > max(s, 1): 

for dp in range(m): 

Q.append(Q.popleft()) 

perm.append(Q.popleft()) 

perm.extend(list(Q)) 

return Perm(perm) 

 

@classmethod 

def from_inversion_vector(self, inversion): 

""" 

Calculates the permutation from the inversion vector. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.print_cyclic = False 

>>> Permutation.from_inversion_vector([3, 2, 1, 0, 0]) 

Permutation([3, 2, 1, 0, 4, 5]) 

 

""" 

size = len(inversion) 

N = list(range(size + 1)) 

perm = [] 

try: 

for k in range(size): 

val = N[inversion[k]] 

perm.append(val) 

N.remove(val) 

except IndexError: 

raise ValueError("The inversion vector is not valid.") 

perm.extend(N) 

return _af_new(perm) 

 

@classmethod 

def random(self, n): 

""" 

Generates a random permutation of length ``n``. 

 

Uses the underlying Python pseudo-random number generator. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.random(2) in (Permutation([1, 0]), Permutation([0, 1])) 

True 

 

""" 

perm_array = list(range(n)) 

random.shuffle(perm_array) 

return _af_new(perm_array) 

 

@classmethod 

def unrank_lex(self, size, rank): 

""" 

Lexicographic permutation unranking. 

 

Examples 

======== 

 

>>> from sympy.combinatorics.permutations import Permutation 

>>> Permutation.print_cyclic = False 

>>> a = Permutation.unrank_lex(5, 10) 

>>> a.rank() 

10 

>>> a 

Permutation([0, 2, 4, 1, 3]) 

 

See Also 

======== 

 

rank, next_lex 

""" 

perm_array = [0] * size 

psize = 1 

for i in range(size): 

new_psize = psize*(i + 1) 

d = (rank % new_psize) // psize 

rank -= d*psize 

perm_array[size - i - 1] = d 

for j in range(size - i, size): 

if perm_array[j] > d - 1: 

perm_array[j] += 1 

psize = new_psize 

return _af_new(perm_array) 

 

# global flag to control how permutations are printed 

# when True, Permutation([0, 2, 1, 3]) -> Cycle(1, 2) 

# when False, Permutation([0, 2, 1, 3]) -> Permutation([0, 2, 1]) 

print_cyclic = True 

 

 

def _merge(arr, temp, left, mid, right): 

""" 

Merges two sorted arrays and calculates the inversion count. 

 

Helper function for calculating inversions. This method is 

for internal use only. 

""" 

i = k = left 

j = mid 

inv_count = 0 

while i < mid and j <= right: 

if arr[i] < arr[j]: 

temp[k] = arr[i] 

k += 1 

i += 1 

else: 

temp[k] = arr[j] 

k += 1 

j += 1 

inv_count += (mid -i) 

while i < mid: 

temp[k] = arr[i] 

k += 1 

i += 1 

if j <= right: 

k += right - j + 1 

j += right - j + 1 

arr[left:k + 1] = temp[left:k + 1] 

else: 

arr[left:right + 1] = temp[left:right + 1] 

return inv_count 

 

Perm = Permutation 

_af_new = Perm._af_new