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

2836

2837

2838

2839

2840

2841

2842

2843

2844

2845

2846

2847

2848

2849

2850

2851

2852

2853

2854

2855

2856

2857

2858

2859

2860

2861

2862

2863

2864

2865

2866

2867

2868

2869

2870

2871

2872

2873

2874

2875

2876

2877

2878

2879

2880

2881

2882

2883

2884

2885

2886

2887

2888

2889

2890

2891

2892

2893

2894

2895

2896

2897

2898

2899

2900

2901

2902

2903

2904

2905

2906

2907

2908

2909

2910

2911

2912

2913

2914

2915

2916

2917

2918

2919

2920

2921

2922

2923

2924

2925

2926

2927

2928

2929

2930

2931

2932

2933

2934

2935

2936

2937

2938

2939

2940

2941

2942

2943

2944

2945

2946

2947

2948

2949

2950

2951

2952

2953

2954

2955

2956

2957

2958

2959

2960

2961

2962

2963

2964

2965

2966

2967

2968

2969

2970

2971

2972

2973

2974

2975

2976

2977

2978

2979

2980

2981

2982

2983

2984

2985

2986

2987

2988

2989

2990

2991

2992

2993

2994

2995

2996

2997

2998

2999

3000

3001

3002

3003

3004

3005

3006

3007

3008

3009

3010

3011

3012

3013

3014

3015

3016

3017

3018

3019

3020

3021

3022

3023

3024

3025

3026

3027

3028

3029

3030

3031

3032

3033

3034

3035

3036

3037

3038

3039

3040

3041

3042

3043

3044

3045

3046

3047

3048

3049

3050

3051

3052

3053

3054

3055

3056

3057

3058

3059

3060

3061

3062

3063

3064

3065

3066

3067

3068

3069

3070

3071

3072

3073

3074

3075

3076

3077

3078

3079

3080

3081

3082

3083

3084

3085

3086

3087

3088

3089

3090

3091

3092

3093

3094

3095

3096

3097

3098

3099

3100

3101

3102

3103

3104

3105

3106

3107

3108

3109

3110

3111

3112

3113

3114

3115

3116

3117

3118

3119

3120

3121

3122

3123

3124

3125

3126

3127

3128

3129

3130

3131

3132

3133

3134

3135

3136

3137

3138

3139

3140

3141

3142

3143

3144

3145

3146

3147

3148

3149

3150

3151

3152

3153

3154

3155

3156

3157

3158

3159

3160

3161

3162

3163

3164

3165

3166

3167

3168

3169

3170

3171

3172

3173

3174

3175

3176

3177

3178

3179

3180

3181

3182

3183

3184

3185

3186

3187

3188

3189

3190

3191

3192

3193

3194

3195

3196

3197

3198

3199

3200

3201

3202

3203

3204

3205

3206

3207

3208

3209

3210

3211

3212

3213

3214

3215

3216

3217

3218

3219

3220

3221

3222

3223

3224

3225

3226

3227

3228

3229

3230

3231

3232

3233

3234

3235

3236

3237

3238

3239

3240

3241

3242

3243

3244

3245

3246

3247

3248

3249

3250

3251

3252

3253

3254

3255

3256

3257

3258

3259

3260

3261

3262

3263

3264

3265

3266

3267

3268

3269

3270

3271

3272

3273

3274

3275

3276

3277

3278

3279

3280

3281

3282

3283

3284

3285

3286

3287

3288

3289

3290

3291

3292

3293

3294

3295

3296

3297

3298

3299

3300

3301

3302

3303

3304

3305

3306

3307

3308

3309

3310

3311

3312

3313

3314

3315

3316

3317

3318

3319

3320

3321

3322

3323

3324

3325

3326

3327

3328

3329

3330

3331

3332

3333

3334

3335

3336

3337

3338

3339

3340

3341

3342

3343

3344

3345

3346

3347

3348

3349

3350

3351

3352

3353

3354

3355

3356

3357

3358

3359

3360

3361

3362

3363

3364

3365

3366

3367

3368

3369

3370

3371

3372

3373

3374

3375

3376

3377

3378

3379

3380

3381

3382

3383

3384

3385

3386

3387

3388

3389

3390

3391

3392

3393

3394

3395

3396

3397

3398

3399

3400

3401

3402

3403

3404

3405

3406

3407

3408

3409

3410

3411

3412

3413

3414

3415

3416

3417

3418

3419

3420

3421

3422

3423

3424

3425

3426

3427

3428

3429

3430

3431

3432

3433

3434

3435

3436

3437

3438

3439

3440

3441

3442

3443

3444

3445

3446

3447

3448

3449

3450

3451

3452

3453

3454

3455

3456

3457

3458

3459

3460

3461

3462

3463

3464

3465

3466

3467

3468

3469

3470

3471

3472

3473

3474

3475

3476

3477

3478

3479

3480

3481

3482

3483

3484

3485

3486

3487

3488

3489

3490

3491

3492

3493

3494

3495

3496

3497

3498

3499

3500

3501

3502

3503

3504

3505

3506

3507

3508

3509

3510

3511

3512

3513

3514

3515

3516

3517

3518

3519

3520

3521

3522

3523

3524

3525

3526

3527

3528

3529

3530

3531

3532

3533

3534

3535

3536

3537

3538

3539

3540

3541

3542

3543

3544

3545

3546

3547

3548

3549

3550

3551

3552

3553

3554

3555

3556

3557

3558

3559

3560

3561

3562

3563

3564

3565

3566

3567

3568

3569

3570

3571

3572

3573

3574

3575

3576

3577

3578

3579

3580

3581

3582

3583

3584

3585

3586

3587

3588

3589

3590

3591

3592

3593

3594

3595

3596

3597

3598

3599

3600

3601

3602

3603

3604

3605

3606

3607

3608

3609

3610

3611

3612

3613

3614

3615

3616

3617

3618

3619

3620

3621

3622

3623

3624

3625

3626

3627

3628

3629

3630

3631

3632

3633

3634

3635

3636

3637

3638

3639

3640

3641

3642

3643

3644

3645

3646

3647

3648

3649

3650

3651

3652

3653

3654

3655

3656

3657

3658

3659

3660

3661

3662

3663

3664

3665

3666

3667

3668

3669

3670

3671

3672

3673

3674

3675

3676

3677

3678

3679

3680

3681

3682

3683

3684

3685

3686

3687

3688

3689

3690

3691

3692

3693

3694

3695

3696

3697

3698

3699

3700

3701

3702

3703

3704

3705

3706

3707

3708

3709

3710

3711

3712

3713

3714

3715

3716

3717

3718

3719

3720

3721

3722

3723

3724

3725

3726

3727

3728

3729

3730

3731

3732

3733

3734

3735

3736

3737

3738

3739

3740

3741

3742

3743

3744

3745

3746

3747

3748

3749

3750

3751

3752

3753

3754

3755

3756

3757

3758

3759

3760

3761

3762

3763

3764

3765

3766

3767

3768

3769

3770

3771

3772

3773

3774

3775

3776

3777

3778

3779

3780

3781

3782

3783

3784

3785

3786

3787

3788

3789

3790

3791

3792

3793

3794

3795

3796

3797

3798

3799

3800

3801

3802

3803

3804

3805

3806

3807

3808

3809

3810

3811

3812

3813

3814

3815

3816

3817

3818

3819

3820

3821

3822

3823

3824

3825

3826

3827

3828

3829

3830

3831

3832

3833

3834

3835

3836

3837

3838

3839

3840

3841

3842

3843

3844

3845

3846

3847

3848

3849

3850

3851

3852

3853

3854

3855

3856

3857

3858

3859

3860

3861

3862

3863

3864

3865

3866

3867

3868

3869

3870

3871

3872

3873

3874

3875

3876

3877

3878

3879

3880

3881

3882

3883

3884

3885

3886

3887

3888

3889

3890

3891

3892

3893

3894

3895

3896

3897

3898

3899

3900

3901

3902

3903

3904

3905

3906

3907

3908

3909

3910

3911

3912

3913

3914

3915

3916

3917

3918

3919

3920

3921

3922

3923

3924

3925

3926

3927

3928

3929

3930

3931

3932

3933

3934

3935

3936

3937

3938

3939

3940

3941

3942

3943

3944

3945

3946

3947

3948

3949

3950

3951

3952

3953

3954

3955

3956

3957

3958

3959

3960

3961

3962

3963

3964

3965

3966

3967

3968

3969

3970

3971

3972

3973

3974

3975

3976

3977

3978

3979

3980

3981

3982

3983

3984

3985

3986

3987

3988

3989

3990

3991

3992

3993

3994

3995

3996

3997

3998

3999

4000

4001

4002

4003

4004

4005

4006

4007

4008

4009

4010

4011

4012

4013

4014

4015

4016

4017

4018

4019

4020

4021

4022

4023

4024

4025

4026

4027

4028

4029

4030

4031

4032

4033

4034

4035

4036

4037

4038

4039

4040

4041

4042

4043

4044

4045

4046

4047

4048

4049

4050

4051

4052

4053

4054

4055

4056

4057

4058

4059

4060

4061

4062

4063

4064

4065

4066

4067

4068

4069

4070

4071

4072

4073

4074

4075

4076

4077

4078

4079

4080

4081

4082

4083

4084

4085

4086

4087

4088

4089

4090

4091

4092

4093

4094

4095

4096

4097

4098

4099

4100

4101

4102

4103

4104

4105

4106

4107

4108

4109

4110

4111

4112

4113

4114

4115

4116

4117

4118

4119

4120

4121

4122

4123

4124

4125

4126

4127

4128

4129

4130

4131

4132

4133

4134

4135

4136

4137

4138

4139

4140

4141

4142

4143

4144

4145

4146

4147

4148

4149

4150

4151

4152

4153

4154

4155

4156

4157

4158

4159

4160

4161

4162

4163

4164

4165

4166

4167

4168

4169

4170

4171

4172

4173

4174

4175

4176

4177

4178

4179

4180

4181

4182

4183

4184

4185

4186

4187

4188

4189

4190

4191

4192

4193

4194

4195

4196

4197

4198

4199

4200

4201

4202

4203

4204

4205

4206

4207

4208

4209

4210

4211

4212

4213

4214

4215

4216

4217

4218

4219

4220

4221

4222

4223

4224

4225

4226

4227

4228

4229

4230

4231

4232

4233

4234

4235

4236

4237

4238

4239

4240

4241

4242

4243

4244

4245

4246

4247

4248

4249

4250

4251

4252

4253

4254

4255

4256

4257

4258

4259

4260

4261

4262

4263

4264

4265

4266

4267

4268

4269

4270

4271

4272

4273

4274

4275

4276

4277

4278

4279

4280

4281

4282

4283

4284

4285

4286

4287

4288

4289

4290

4291

4292

4293

4294

4295

4296

4297

4298

4299

4300

4301

4302

4303

4304

4305

4306

4307

4308

4309

4310

4311

4312

4313

4314

4315

4316

4317

4318

4319

4320

4321

4322

4323

4324

4325

4326

4327

4328

4329

4330

4331

4332

4333

4334

4335

4336

4337

4338

4339

4340

4341

4342

4343

4344

4345

4346

4347

4348

4349

4350

4351

4352

4353

4354

4355

4356

4357

4358

4359

4360

4361

4362

4363

4364

4365

4366

4367

4368

4369

4370

4371

4372

4373

4374

4375

4376

4377

4378

4379

4380

4381

4382

4383

4384

4385

4386

4387

4388

4389

4390

4391

4392

4393

4394

4395

4396

4397

4398

4399

4400

4401

4402

4403

4404

4405

4406

4407

4408

4409

4410

4411

4412

4413

4414

4415

4416

4417

4418

4419

4420

4421

4422

4423

4424

4425

4426

4427

4428

4429

4430

4431

4432

4433

4434

4435

4436

4437

4438

4439

4440

4441

4442

4443

4444

4445

4446

4447

4448

4449

4450

4451

4452

4453

4454

4455

4456

4457

4458

4459

4460

4461

4462

4463

4464

4465

4466

4467

4468

4469

4470

4471

4472

4473

4474

4475

4476

4477

4478

4479

4480

4481

4482

4483

4484

4485

4486

4487

4488

4489

4490

4491

4492

4493

4494

4495

4496

4497

4498

4499

4500

4501

4502

4503

4504

4505

4506

4507

4508

4509

4510

4511

4512

4513

4514

4515

4516

4517

4518

4519

4520

4521

4522

4523

4524

4525

4526

4527

4528

4529

4530

4531

4532

4533

4534

4535

4536

4537

4538

4539

4540

4541

4542

4543

4544

4545

4546

4547

4548

4549

4550

4551

4552

4553

4554

4555

4556

4557

4558

4559

4560

4561

4562

4563

4564

4565

4566

4567

4568

4569

4570

4571

4572

4573

4574

4575

4576

4577

4578

4579

4580

4581

4582

4583

4584

4585

4586

4587

4588

4589

4590

4591

4592

4593

4594

4595

4596

4597

4598

4599

4600

4601

4602

4603

4604

4605

4606

4607

4608

4609

4610

4611

4612

4613

4614

4615

4616

4617

4618

4619

4620

4621

4622

4623

4624

4625

4626

4627

4628

4629

4630

4631

4632

4633

4634

4635

4636

4637

4638

4639

4640

4641

4642

4643

4644

4645

4646

4647

4648

4649

4650

4651

4652

4653

4654

4655

4656

4657

4658

4659

4660

4661

4662

4663

4664

4665

4666

4667

4668

4669

4670

4671

4672

4673

4674

4675

4676

4677

4678

4679

4680

4681

4682

4683

4684

4685

4686

4687

4688

4689

4690

4691

4692

4693

4694

4695

4696

4697

4698

4699

4700

4701

4702

4703

4704

4705

4706

4707

4708

4709

4710

4711

4712

4713

4714

4715

4716

4717

4718

4719

4720

4721

4722

4723

4724

4725

4726

4727

4728

4729

4730

4731

4732

4733

4734

4735

4736

4737

4738

4739

4740

4741

4742

4743

4744

4745

4746

4747

4748

4749

4750

4751

4752

4753

4754

4755

4756

4757

4758

4759

4760

4761

4762

4763

4764

4765

4766

4767

4768

4769

4770

4771

4772

4773

4774

4775

4776

4777

4778

4779

4780

4781

4782

4783

4784

4785

4786

4787

4788

4789

4790

4791

4792

4793

4794

4795

4796

4797

4798

4799

4800

4801

4802

4803

4804

4805

4806

4807

4808

4809

4810

4811

4812

4813

4814

4815

4816

4817

4818

4819

4820

4821

4822

4823

4824

4825

4826

4827

4828

4829

4830

4831

4832

4833

4834

4835

4836

4837

4838

4839

4840

4841

4842

4843

4844

4845

4846

4847

4848

4849

4850

4851

4852

4853

4854

4855

4856

4857

4858

4859

4860

4861

4862

4863

4864

4865

4866

4867

4868

4869

4870

4871

4872

4873

4874

4875

4876

4877

4878

4879

4880

4881

4882

4883

4884

4885

4886

4887

4888

4889

4890

4891

4892

4893

4894

4895

4896

4897

4898

4899

4900

4901

4902

4903

4904

4905

4906

4907

4908

4909

4910

4911

4912

4913

4914

4915

4916

4917

4918

4919

4920

4921

4922

4923

4924

4925

4926

4927

4928

4929

4930

4931

4932

4933

4934

4935

4936

4937

4938

4939

4940

4941

4942

4943

4944

4945

4946

4947

4948

4949

4950

4951

4952

4953

4954

4955

4956

4957

4958

4959

4960

4961

4962

4963

4964

4965

4966

4967

4968

4969

4970

4971

4972

4973

4974

4975

4976

4977

4978

4979

4980

4981

4982

4983

4984

4985

4986

4987

4988

4989

4990

4991

4992

4993

4994

4995

4996

4997

4998

4999

5000

5001

5002

5003

5004

5005

5006

5007

5008

5009

5010

5011

5012

5013

5014

5015

5016

5017

5018

5019

5020

5021

5022

5023

5024

5025

5026

5027

5028

5029

5030

5031

5032

5033

5034

5035

5036

5037

5038

5039

5040

5041

5042

5043

5044

5045

5046

5047

5048

5049

5050

5051

5052

5053

5054

5055

5056

5057

5058

5059

5060

5061

5062

5063

5064

5065

5066

5067

5068

5069

5070

5071

5072

5073

5074

5075

5076

5077

5078

5079

5080

5081

5082

5083

5084

5085

5086

5087

5088

5089

5090

5091

5092

5093

5094

5095

5096

5097

5098

5099

5100

5101

5102

5103

5104

5105

5106

5107

5108

5109

5110

5111

5112

5113

5114

5115

5116

5117

5118

5119

5120

5121

5122

5123

5124

5125

5126

5127

5128

5129

5130

5131

5132

5133

5134

5135

5136

5137

5138

5139

5140

5141

5142

5143

5144

5145

5146

5147

5148

5149

5150

5151

5152

5153

5154

5155

5156

5157

5158

5159

5160

5161

5162

5163

5164

5165

5166

5167

5168

5169

5170

5171

5172

5173

5174

5175

5176

5177

5178

5179

5180

5181

5182

5183

5184

5185

5186

5187

5188

5189

5190

5191

5192

5193

5194

5195

5196

5197

5198

5199

5200

5201

5202

5203

5204

5205

5206

5207

5208

5209

5210

5211

5212

5213

5214

5215

5216

5217

5218

5219

5220

5221

5222

5223

5224

5225

5226

5227

5228

5229

5230

5231

5232

5233

5234

5235

5236

5237

5238

5239

5240

5241

5242

5243

5244

5245

5246

5247

5248

5249

5250

5251

5252

5253

5254

5255

5256

5257

5258

5259

5260

5261

5262

5263

5264

5265

5266

5267

5268

5269

5270

5271

5272

5273

5274

5275

5276

5277

5278

5279

5280

5281

5282

5283

5284

5285

5286

5287

5288

5289

5290

5291

5292

5293

5294

5295

5296

5297

5298

5299

5300

5301

5302

5303

5304

5305

5306

5307

5308

5309

5310

5311

5312

5313

5314

5315

5316

5317

5318

5319

5320

5321

5322

5323

5324

5325

5326

5327

5328

5329

5330

5331

5332

5333

5334

5335

5336

5337

5338

5339

5340

5341

5342

5343

5344

5345

5346

5347

5348

5349

5350

5351

5352

5353

5354

5355

5356

5357

5358

5359

5360

5361

5362

5363

5364

5365

5366

5367

5368

5369

5370

5371

5372

5373

5374

5375

5376

5377

5378

5379

5380

5381

5382

5383

5384

5385

5386

5387

5388

5389

5390

5391

5392

5393

5394

5395

5396

5397

5398

5399

5400

5401

5402

5403

5404

5405

5406

5407

5408

5409

5410

5411

5412

5413

5414

5415

5416

5417

5418

5419

5420

5421

5422

5423

5424

5425

5426

5427

5428

5429

5430

5431

5432

5433

5434

5435

5436

5437

5438

5439

5440

5441

5442

5443

5444

5445

5446

5447

5448

5449

5450

5451

5452

5453

5454

5455

5456

5457

5458

5459

5460

5461

5462

5463

5464

5465

5466

5467

5468

5469

5470

5471

5472

5473

5474

5475

5476

5477

5478

5479

5480

5481

5482

5483

5484

5485

5486

5487

5488

5489

5490

5491

5492

5493

5494

5495

5496

5497

5498

5499

5500

5501

5502

5503

5504

5505

5506

5507

5508

5509

5510

5511

5512

5513

5514

5515

5516

5517

5518

5519

5520

5521

5522

5523

5524

5525

5526

5527

5528

5529

5530

5531

5532

5533

5534

5535

5536

5537

5538

5539

5540

5541

5542

5543

5544

5545

5546

5547

5548

5549

5550

5551

5552

5553

5554

5555

5556

5557

5558

5559

5560

5561

5562

5563

5564

5565

5566

5567

5568

5569

5570

5571

5572

5573

5574

5575

5576

5577

5578

5579

5580

5581

5582

5583

5584

5585

5586

5587

5588

5589

5590

5591

5592

5593

5594

5595

5596

5597

5598

5599

5600

5601

5602

5603

5604

5605

5606

5607

5608

5609

5610

5611

5612

5613

5614

5615

5616

5617

5618

5619

5620

5621

5622

5623

5624

5625

5626

5627

5628

5629

5630

5631

5632

5633

5634

5635

5636

5637

5638

5639

5640

5641

5642

5643

5644

5645

5646

5647

5648

5649

5650

5651

5652

5653

5654

5655

5656

5657

5658

5659

5660

5661

5662

5663

5664

5665

5666

5667

5668

5669

5670

5671

5672

5673

5674

5675

5676

5677

5678

5679

5680

5681

5682

5683

5684

5685

5686

5687

5688

5689

5690

5691

5692

5693

5694

5695

5696

5697

5698

5699

5700

5701

5702

5703

5704

5705

5706

5707

5708

5709

5710

5711

5712

5713

5714

5715

5716

5717

5718

5719

5720

5721

5722

5723

5724

5725

5726

5727

5728

5729

5730

5731

5732

5733

5734

5735

5736

5737

5738

5739

5740

5741

5742

5743

5744

5745

5746

5747

5748

5749

5750

5751

5752

5753

5754

5755

5756

5757

5758

5759

5760

5761

5762

5763

5764

5765

5766

5767

5768

5769

5770

5771

5772

5773

5774

5775

5776

5777

5778

5779

5780

5781

5782

5783

5784

5785

5786

5787

5788

5789

5790

5791

5792

5793

5794

5795

5796

5797

5798

5799

5800

5801

5802

5803

5804

5805

5806

5807

5808

5809

5810

5811

5812

5813

5814

5815

5816

5817

5818

5819

5820

5821

5822

5823

5824

5825

5826

5827

5828

5829

5830

5831

5832

5833

5834

5835

5836

5837

5838

5839

5840

5841

5842

5843

5844

5845

5846

5847

5848

5849

5850

5851

5852

5853

5854

5855

5856

5857

5858

5859

5860

5861

5862

5863

5864

5865

5866

5867

5868

5869

5870

5871

5872

5873

5874

5875

5876

5877

5878

5879

5880

5881

5882

5883

5884

5885

5886

5887

5888

5889

5890

5891

5892

5893

5894

5895

5896

5897

5898

5899

5900

5901

5902

5903

5904

5905

5906

5907

5908

5909

5910

5911

5912

5913

5914

5915

5916

5917

5918

5919

5920

5921

5922

5923

5924

5925

5926

5927

5928

5929

5930

5931

5932

5933

5934

5935

5936

5937

5938

5939

5940

5941

5942

5943

5944

5945

5946

5947

5948

5949

5950

5951

5952

5953

5954

5955

5956

5957

5958

5959

5960

5961

5962

5963

5964

5965

5966

5967

5968

5969

5970

5971

5972

5973

5974

5975

5976

5977

5978

5979

5980

5981

5982

5983

5984

5985

5986

5987

5988

5989

5990

5991

5992

5993

5994

5995

5996

5997

5998

5999

6000

6001

6002

6003

6004

6005

6006

6007

6008

6009

6010

6011

6012

6013

6014

6015

6016

6017

6018

6019

6020

6021

6022

6023

6024

6025

6026

6027

6028

6029

6030

6031

6032

6033

6034

6035

6036

6037

6038

6039

6040

6041

6042

6043

6044

6045

6046

6047

6048

6049

6050

6051

6052

6053

6054

6055

6056

6057

6058

6059

6060

6061

6062

6063

6064

6065

6066

6067

6068

6069

6070

6071

6072

6073

6074

6075

6076

6077

6078

6079

6080

6081

6082

6083

6084

6085

6086

6087

6088

6089

6090

6091

6092

6093

6094

6095

6096

6097

6098

6099

6100

6101

6102

6103

6104

6105

6106

6107

6108

6109

6110

6111

6112

6113

6114

6115

6116

6117

6118

6119

6120

6121

6122

6123

6124

6125

6126

6127

6128

6129

6130

6131

6132

6133

6134

6135

6136

6137

6138

6139

6140

6141

6142

6143

6144

6145

6146

6147

6148

6149

6150

6151

6152

6153

6154

6155

6156

6157

6158

6159

6160

6161

6162

6163

6164

6165

6166

6167

6168

6169

6170

6171

6172

6173

6174

6175

6176

6177

6178

6179

6180

6181

6182

6183

6184

6185

6186

6187

6188

6189

6190

6191

6192

6193

6194

6195

6196

6197

6198

6199

6200

6201

6202

6203

6204

6205

6206

6207

6208

6209

6210

6211

6212

6213

6214

6215

6216

6217

6218

6219

6220

6221

6222

6223

6224

6225

6226

6227

6228

6229

6230

6231

6232

6233

6234

6235

6236

6237

6238

6239

6240

6241

6242

6243

6244

6245

6246

6247

6248

6249

6250

6251

6252

6253

6254

6255

6256

6257

6258

6259

6260

6261

6262

6263

6264

6265

6266

6267

6268

6269

6270

6271

6272

6273

6274

6275

6276

6277

6278

6279

6280

6281

6282

6283

6284

6285

6286

6287

6288

6289

6290

6291

6292

6293

6294

6295

6296

6297

6298

6299

6300

6301

6302

6303

6304

6305

6306

6307

6308

6309

6310

6311

6312

6313

6314

6315

6316

6317

6318

6319

6320

6321

6322

6323

6324

6325

6326

6327

6328

6329

6330

6331

6332

6333

6334

6335

6336

6337

6338

6339

6340

6341

6342

6343

6344

6345

6346

6347

6348

6349

6350

6351

6352

6353

6354

6355

6356

6357

6358

6359

6360

6361

6362

6363

6364

6365

6366

6367

6368

6369

6370

6371

6372

6373

6374

6375

6376

6377

6378

6379

6380

6381

6382

6383

6384

6385

6386

6387

6388

6389

6390

6391

6392

6393

6394

6395

6396

6397

6398

6399

6400

6401

6402

6403

6404

6405

6406

6407

6408

6409

6410

6411

6412

6413

6414

6415

6416

6417

6418

6419

6420

6421

6422

6423

6424

6425

6426

6427

6428

6429

6430

6431

6432

6433

6434

6435

6436

6437

6438

6439

6440

6441

6442

6443

6444

6445

6446

6447

6448

6449

6450

6451

6452

6453

6454

6455

6456

6457

6458

6459

6460

6461

6462

6463

6464

6465

6466

6467

6468

6469

6470

6471

6472

6473

6474

6475

6476

6477

6478

6479

6480

6481

6482

6483

6484

6485

6486

6487

6488

6489

6490

6491

6492

6493

6494

6495

6496

6497

6498

6499

6500

6501

6502

6503

6504

6505

6506

6507

6508

6509

6510

6511

6512

6513

6514

6515

6516

6517

6518

6519

6520

6521

6522

6523

6524

6525

6526

6527

6528

6529

6530

6531

6532

6533

6534

6535

6536

6537

6538

6539

6540

6541

6542

6543

6544

6545

6546

6547

6548

6549

6550

6551

6552

6553

6554

6555

6556

6557

6558

6559

6560

6561

6562

6563

6564

6565

6566

6567

6568

6569

6570

6571

6572

6573

6574

6575

6576

6577

6578

6579

6580

6581

6582

6583

6584

6585

6586

6587

6588

6589

6590

6591

6592

6593

6594

6595

6596

6597

6598

6599

6600

6601

6602

6603

6604

6605

6606

6607

6608

6609

6610

6611

6612

6613

6614

6615

6616

6617

6618

6619

6620

6621

6622

6623

6624

6625

6626

6627

6628

6629

6630

6631

6632

6633

6634

6635

6636

6637

6638

6639

6640

6641

6642

6643

6644

6645

6646

6647

6648

6649

6650

6651

6652

6653

6654

6655

6656

6657

6658

6659

6660

6661

6662

6663

6664

6665

6666

6667

6668

6669

6670

6671

6672

6673

6674

6675

6676

6677

6678

6679

6680

6681

6682

6683

6684

6685

6686

6687

6688

6689

6690

6691

6692

6693

6694

6695

6696

6697

6698

6699

6700

6701

6702

6703

6704

6705

6706

6707

6708

6709

6710

6711

6712

6713

6714

6715

6716

6717

6718

6719

6720

6721

6722

6723

6724

6725

6726

6727

6728

6729

6730

6731

6732

6733

6734

6735

6736

6737

6738

6739

6740

6741

6742

6743

6744

6745

6746

6747

6748

6749

6750

6751

6752

6753

6754

6755

6756

6757

6758

6759

6760

6761

6762

6763

6764

6765

6766

6767

6768

6769

6770

6771

6772

6773

6774

6775

6776

6777

6778

6779

6780

6781

6782

6783

6784

6785

6786

6787

6788

6789

6790

6791

6792

6793

6794

6795

6796

6797

6798

6799

6800

6801

6802

6803

6804

6805

6806

6807

6808

6809

6810

6811

6812

6813

6814

6815

6816

6817

6818

6819

6820

6821

6822

6823

6824

6825

6826

6827

6828

6829

6830

6831

6832

6833

6834

6835

6836

6837

6838

6839

6840

6841

6842

6843

6844

6845

6846

6847

6848

6849

6850

6851

6852

6853

6854

6855

6856

6857

6858

6859

6860

6861

6862

6863

6864

6865

6866

6867

6868

6869

6870

6871

6872

6873

6874

6875

6876

6877

6878

6879

6880

6881

6882

6883

6884

6885

6886

6887

6888

6889

6890

6891

6892

6893

6894

6895

6896

6897

6898

6899

6900

6901

6902

6903

6904

6905

6906

6907

6908

6909

6910

6911

6912

6913

6914

6915

6916

6917

6918

6919

6920

6921

6922

6923

6924

6925

6926

6927

6928

6929

6930

6931

6932

6933

6934

6935

6936

6937

6938

6939

6940

6941

6942

6943

6944

6945

6946

6947

6948

6949

6950

6951

6952

6953

6954

6955

6956

6957

6958

6959

6960

6961

6962

6963

6964

6965

6966

6967

6968

6969

6970

6971

6972

6973

6974

6975

6976

6977

6978

6979

6980

6981

6982

6983

6984

6985

6986

6987

6988

6989

6990

6991

6992

6993

6994

6995

6996

6997

6998

6999

7000

7001

7002

7003

7004

7005

7006

7007

7008

7009

7010

7011

7012

7013

7014

7015

7016

7017

7018

7019

7020

7021

7022

7023

7024

7025

7026

7027

7028

7029

7030

7031

7032

7033

7034

7035

7036

7037

7038

7039

7040

7041

7042

7043

7044

7045

7046

7047

7048

7049

7050

7051

7052

7053

7054

7055

7056

7057

7058

7059

7060

7061

7062

7063

7064

7065

7066

7067

7068

7069

7070

7071

7072

7073

7074

7075

7076

7077

7078

7079

7080

7081

7082

7083

7084

7085

7086

7087

7088

7089

7090

7091

7092

7093

7094

7095

7096

7097

7098

7099

7100

7101

7102

7103

7104

7105

7106

7107

7108

7109

7110

7111

7112

7113

7114

7115

7116

7117

7118

7119

7120

7121

7122

7123

7124

7125

7126

7127

7128

7129

7130

7131

7132

7133

7134

7135

7136

7137

7138

7139

7140

7141

7142

7143

7144

7145

7146

7147

7148

7149

7150

7151

7152

7153

7154

7155

7156

7157

7158

7159

7160

7161

7162

7163

7164

7165

7166

7167

7168

7169

7170

7171

7172

7173

7174

7175

7176

7177

7178

7179

7180

7181

7182

7183

7184

7185

7186

7187

7188

7189

7190

7191

7192

7193

7194

7195

7196

7197

7198

7199

7200

# -*- coding: utf-8 -*- 

r""" 

Finite word 

 

AUTHORS: 

 

- Arnaud Bergeron 

- Amy Glen 

- Sébastien Labbé 

- Franco Saliola 

- Julien Leroy (March 2010): reduced_rauzy_graph 

 

EXAMPLES: 

 

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

Creation of a finite word 

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

 

Finite words from Python strings, lists and tuples:: 

 

sage: Word("abbabaab") 

word: abbabaab 

sage: Word([0, 1, 1, 0, 1, 0, 0, 1]) 

word: 01101001 

sage: Word( ('a', 0, 5, 7, 'b', 9, 8) ) 

word: a057b98 

 

Finite words from functions:: 

 

sage: f = lambda n : n%3 

sage: Word(f, length=13) 

word: 0120120120120 

 

Finite words from iterators:: 

 

sage: from itertools import count 

sage: Word(count(), length=10) 

word: 0123456789 

 

:: 

 

sage: Word( iter('abbccdef') ) 

word: abbccdef 

 

Finite words from words via concatenation:: 

 

sage: u = Word("abcccabba") 

sage: v = Word([0, 4, 8, 8, 3]) 

sage: u * v 

word: abcccabba04883 

sage: v * u 

word: 04883abcccabba 

sage: u + v 

word: abcccabba04883 

sage: u^3 * v^(8/5) 

word: abcccabbaabcccabbaabcccabba04883048 

 

Finite words from infinite words:: 

 

sage: vv = v^Infinity 

sage: vv[10000:10015] 

word: 048830488304883 

 

Finite words in a specific combinatorial class:: 

 

sage: W = Words("ab") 

sage: W 

Finite and infinite words over {'a', 'b'} 

sage: W("abbabaab") 

word: abbabaab 

sage: W(["a","b","b","a","b","a","a","b"]) 

word: abbabaab 

sage: W( iter('ababab') ) 

word: ababab 

 

Finite word as the image under a morphism:: 

 

sage: m = WordMorphism({0:[4,4,5,0],5:[0,5,5],4:[4,0,0,0]}) 

sage: m(0) 

word: 4450 

sage: m(0, order=2) 

word: 400040000554450 

sage: m(0, order=3) 

word: 4000445044504450400044504450445044500550... 

 

.. NOTE:: 

 

The following two finite words have the same string representation:: 

 

sage: w = Word('010120') 

sage: z = Word([0, 1, 0, 1, 2, 0]) 

sage: w 

word: 010120 

sage: z 

word: 010120 

 

but are not equal:: 

 

sage: w == z 

False 

 

Indeed, w and z are defined on different alphabets:: 

 

sage: w[2] 

'0' 

sage: z[2] 

0 

 

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

Functions and algorithms 

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

 

There are more than 100 functions defined on a finite word. Here are some 

of them:: 

 

sage: w = Word('abaabbba'); w 

word: abaabbba 

sage: w.is_palindrome() 

False 

sage: w.is_lyndon() 

False 

sage: w.number_of_factors() 

28 

sage: w.critical_exponent() 

3 

 

:: 

 

sage: print(w.lyndon_factorization()) 

(ab, aabbb, a) 

sage: print(w.crochemore_factorization()) 

(a, b, a, ab, bb, a) 

 

:: 

 

sage: st = w.suffix_tree() 

sage: st 

Implicit Suffix Tree of the word: abaabbba 

sage: st.show(word_labels=True) 

 

:: 

 

sage: T = words.FibonacciWord('ab') 

sage: T.longest_common_prefix(Word('abaabababbbbbb')) 

word: abaababa 

 

As matrix and many other sage objects, words have a parent:: 

 

sage: u = Word('xyxxyxyyy') 

sage: u.parent() 

Finite words over Set of Python objects of class 'object' 

 

:: 

 

sage: v = Word('xyxxyxyyy', alphabet='xy') 

sage: v.parent() 

Finite words over {'x', 'y'} 

 

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

Factors and Rauzy Graphs 

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

 

Enumeration of factors, the successive values returned by ``next(it)`` 

can appear in a different order depending on hardware. Therefore we 

mark the three first results of the test ``random``. The important test 

is that the iteration stops properly on the fourth call:: 

 

sage: w = Word([4,5,6])^7 

sage: it = w.factor_iterator(4) 

sage: next(it) # random 

word: 6456 

sage: next(it) # random 

word: 5645 

sage: next(it) # random 

word: 4564 

sage: next(it) 

Traceback (most recent call last): 

... 

StopIteration 

 

The set of factors:: 

 

sage: sorted(w.factor_set(3)) 

[word: 456, word: 564, word: 645] 

sage: sorted(w.factor_set(4)) 

[word: 4564, word: 5645, word: 6456] 

sage: w.factor_set().cardinality() 

61 

 

Rauzy graphs:: 

 

sage: f = words.FibonacciWord()[:30] 

sage: f.rauzy_graph(4) 

Looped digraph on 5 vertices 

sage: f.reduced_rauzy_graph(4) 

Looped multi-digraph on 2 vertices 

 

Left-special and bispecial factors:: 

 

sage: f.number_of_left_special_factors(7) 

1 

sage: f.bispecial_factors() 

[word: , word: 0, word: 010, word: 010010, word: 01001010010] 

""" 

#***************************************************************************** 

# Copyright (C) 2008 Arnaud Bergeron <abergeron@gmail.com>, 

# 2008 Amy Glen <amy.glen@gmail.com>, 

# 2008-2012 Sébastien Labbé <slabqc@gmail.com>, 

# 2008-2010 Franco Saliola <saliola@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 collections import defaultdict 

from itertools import islice, cycle 

from sage.combinat.words.abstract_word import Word_class 

from sage.combinat.words.words import Words 

from sage.misc.cachefunc import cached_method 

from sage.combinat.words.word_options import word_options 

from sage.rings.all import Integer, Infinity, ZZ 

from sage.sets.set import Set 

from sage.misc.superseded import deprecated_function_alias 

 

class FiniteWord_class(Word_class): 

def __str__(self): 

r""" 

Return the full (not truncated) string representation of the word 

without identifier. 

 

TESTS:: 

 

sage: Word('abc').__str__() 

'abc' 

sage: Word([0, 1, 0, 0, 1] * 10).__str__() 

'01001010010100101001010010100101001010010100101001' 

sage: Word([0,1,10,101]).__str__() 

'0,1,10,101' 

 

Insertion into a ``str``:: 

 

sage: w = Word(range(5)) 

sage: "Let's insert the word w = %s in this string." % w 

"Let's insert the word w = 01234 in this string." 

 

Using ``LatexExpr``:: 

 

sage: from sage.misc.latex import LatexExpr 

sage: LatexExpr(w) 

01234 

 

With the ``print`` statement:: 

 

sage: print(w) 

01234 

 

No truncation is done for finite words:: 

 

sage: w = Word([i % 5 for i in range(60)]) 

sage: print(w) 

012340123401234012340123401234012340123401234012340123401234 

""" 

global word_options 

if word_options['display'] == 'string': 

ls = word_options['letter_separator'] 

letters = [str(_) for _ in self] 

if all(len(a)==1 for a in letters): 

return ''.join(letters) 

else: 

return ls.join(letters) 

elif word_options['display'] == 'list': 

return str(list(self)) 

 

def _repr_(self): 

r""" 

Return a string representation of ``self``. 

 

TESTS:: 

 

sage: Word(range(10))._repr_() 

'word: 0123456789' 

sage: Word(range(100))._repr_() 

'word: 0,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,...' 

""" 

global word_options 

if word_options['old_repr']: 

if word_options['truncate'] and \ 

self.length() > word_options['truncate_length']: 

return "Finite word of length %s over %s" % (self.length(), str(self.parent().alphabet())[17:]) 

return word_options['identifier'] + self.string_rep() 

 

def coerce(self, other): 

r""" 

Try to return a pair of words with a common parent; raise an 

exception if this is not possible. 

 

This function begins by checking if both words have the same 

parent. If this is the case, then no work is done and both words 

are returned as-is. 

 

Otherwise it will attempt to convert ``other`` to the domain of ``self``. 

If that fails, it will attempt to convert ``self`` to the domain of 

``other``. If both attempts fail, it raises a ``TypeError`` to signal 

failure. 

 

EXAMPLES:: 

 

sage: W1 = Words('abc'); W2 = Words('ab') 

sage: w1 = W1('abc'); w2 = W2('abba'); w3 = W1('baab') 

sage: w1.parent() is w2.parent() 

False 

sage: a, b = w1.coerce(w2) 

sage: a.parent() is b.parent() 

True 

sage: w1.parent() is w2.parent() 

False 

""" 

if self.parent() != other.parent(): 

try: 

other = self.parent()(other) 

other.parent()._check(other, length=None) 

except Exception: 

try: 

self = other.parent()(self) 

self.parent()._check(self, length=None) 

except Exception: 

raise TypeError("no coercion rule between %r and %r" % (self.parent(), other.parent())) 

return self, other 

 

def __hash__(self): 

r""" 

Return the hash for this word. 

 

TESTS:: 

 

sage: h = hash(Word('abc')) # indirect test 

sage: Word('abc').__hash__() == Word('abc').__hash__() 

True 

""" 

if self._hash is None: 

res = 5381 

for s in self._to_integer_iterator(): 

res = ((res << 5) + res) + s 

self._hash = res 

return self._hash 

 

def concatenate(self, other): 

r""" 

Return the concatenation of ``self`` and ``other``. 

 

INPUT: 

 

- ``other`` -- a word over the same alphabet as ``self`` 

 

EXAMPLES: 

 

Concatenation may be made using ``+`` or ``*`` operations:: 

 

sage: w = Word('abadafd') 

sage: y = Word([5,3,5,8,7]) 

sage: w * y 

word: abadafd53587 

sage: w + y 

word: abadafd53587 

sage: w.concatenate(y) 

word: abadafd53587 

 

Both words must be defined over the same alphabet:: 

 

sage: z = Word('12223', alphabet = '123') 

sage: z + y 

Traceback (most recent call last): 

... 

ValueError: 5 not in alphabet! 

 

Eventually, it should work:: 

 

sage: z = Word('12223', alphabet = '123') 

sage: z + y #todo: not implemented 

word: 1222353587 

 

TESTS: 

 

The empty word is not considered by concatenation:: 

 

sage: type(Word([]) * Word('abcd')) 

<class 'sage.combinat.words.word.FiniteWord_str'> 

sage: type(Word('abcd') * Word()) 

<class 'sage.combinat.words.word.FiniteWord_str'> 

sage: type(Word('abcd') * Word([])) 

<class 'sage.combinat.words.word.FiniteWord_str'> 

sage: type(Word('abcd') * Word(())) 

<class 'sage.combinat.words.word.FiniteWord_str'> 

sage: type(Word([1,2,3]) * Word('')) 

<class 'sage.combinat.words.word.FiniteWord_list'> 

 

Concatenation of finite words with infinite words works as expected:: 

 

sage: from itertools import repeat 

sage: W = Words('ab') 

sage: w1 = W('aba') 

sage: w2 = W(repeat('b'), length='infinite') 

sage: w1*w2 

word: ababbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb... 

sage: _.parent() 

Infinite words over {'a', 'b'} 

""" 

if self.is_empty(): 

return other 

if isinstance(other, Word_class) and other.is_empty(): 

return self 

f = CallableFromListOfWords([self,other]) 

length = self.length() + other.length() 

parent = self._parent 

if length == Infinity: 

parent = parent.shift() 

return parent(f, datatype='callable', caching=True) 

else: 

return parent(f, length=length, datatype='callable', caching=True) 

 

__mul__ = concatenate 

 

__add__ = concatenate 

 

# TODO: This function is using domain=range(n) for Word but 

# should be a domain=slice(n) # Seb : Feb 23th : I think this is fine now!! 

def __pow__(self, exp): 

r""" 

Return the ``exp``-th power of ``self``. 

 

If ``exp`` is `\infty`, returns the infinite periodic word of base ``self``. 

Otherwise, `|w|\cdot exp` must be a non-negative integer. 

 

INPUT: 

 

- ``exp`` -- an integer, a rational, a float number or plus infinity 

 

OUTPUT: 

 

word -- the ``exp``-th power of ``self`` 

 

EXAMPLES: 

 

You can take non-negative integer powers:: 

 

sage: w = Word(range(6)); w 

word: 012345 

sage: w^2 

word: 012345012345 

sage: w^1 

word: 012345 

sage: w^0 

word: 

sage: w^(-1) 

Traceback (most recent call last): 

... 

ValueError: Power of the word is not defined on the exponent -1: the length of the word (6) times the exponent (-1) must be a positive integer 

 

 

You can take non-negative rational powers:: 

 

sage: w = Word(range(6)); w 

word: 012345 

sage: w^(.5) 

word: 012 

sage: w^(1/3) 

word: 01 

sage: (w*w)^(1/2) == w 

True 

sage: w^(5/2) 

word: 012345012345012 

 

...but the length of the word times the exponent must be an integer:: 

 

sage: w = Word(range(6)) 

sage: w^(1/4) 

Traceback (most recent call last): 

... 

ValueError: Power of the word is not defined on the exponent 1/4: the length of the word (6) times the exponent (1/4) must be a positive integer 

 

You can take infinite power:: 

 

sage: w = Word(range(6)); w 

word: 012345 

sage: u = w^oo; u 

word: 0123450123450123450123450123450123450123... 

sage: u[10000000:20000000] 

word: 4501234501234501234501234501234501234501... 

sage: u[10000000:10000020] 

word: 45012345012345012345 

sage: Word()^oo 

word: 

""" 

# powers of the empty word 

if self.is_empty(): 

return self 

 

# infinite power of a non-empty word 

fcn = lambda n: self[n % self.length()] 

if exp is Infinity: 

return self._parent.shift()(fcn) 

 

#If exp*|self| is not an integer 

length = exp* self.length() 

if length in ZZ and length >= 0: 

return self._parent(fcn, length=length) 

else: 

raise ValueError("Power of the word is not defined on the exponent {}:" 

" the length of the word ({}) times the exponent ({}) must" 

" be a positive integer".format(exp,self.length(),exp)) 

 

def length(self): 

r""" 

Return the length of ``self``. 

 

TESTS:: 

 

sage: from sage.combinat.words.word import Word_class 

sage: w = Word(iter('abba'*40), length="finite") 

sage: w._len is None 

True 

sage: w.length() 

160 

sage: w = Word(iter('abba'), length=4) 

sage: w._len 

4 

sage: w.length() 

4 

sage: def f(n): 

....: return list(range(2,12,2))[n] 

sage: w = Word(f, length=5) 

sage: w.length() 

5 

""" 

if self._len is None: 

self._len = Integer(sum(1 for _ in self)) 

return self._len 

 

def content(self, n=None): 

r""" 

Return content of ``self``. 

 

INPUT: 

 

- ``n`` -- (optional) an integer specifying the maximal 

letter in the alphabet 

 

OUTPUT: 

 

- a list where the `i`-th entry indiciates the multiplicity 

of the `i`-th letter in the alphabet in ``self`` 

 

EXAMPLES:: 

 

sage: w = Word([1,2,4,3,2,2,2]) 

sage: w.content() 

[1, 4, 1, 1] 

sage: w = Word([3,1]) 

sage: w.content() 

[1, 1] 

sage: w.content(n=3) 

[1, 0, 1] 

sage: w = Word([2,4],alphabet=[1,2,3,4]) 

sage: w.content(n=3) 

[0, 1, 0] 

sage: w.content() 

[0, 1, 0, 1] 

""" 

if n is not None: 

alphabet = range(1,n+1) 

elif not self.parent().alphabet().cardinality() == +Infinity: 

alphabet = self.parent().alphabet() 

else: 

alphabet = sorted(self.letters()) 

return [self.count(i) for i in alphabet] 

 

def is_yamanouchi(self, n=None): 

r""" 

Return whether ``self`` is Yamanouchi. 

 

A word `w` is Yamanouchi if, when read from right to left, it 

always has weakly more `i`'s than `i+1`'s for all `i` that 

appear in `w`. 

 

INPUT: 

 

- ``n`` -- (optional) an integer specifying the maximal 

letter in the alphabet 

 

EXAMPLES:: 

 

sage: w = Word([1,2,4,3,2,2,2]) 

sage: w.is_yamanouchi() 

False 

sage: w = Word([2,3,4,3,1,2,1,1,2,1]) 

sage: w.is_yamanouchi() 

True 

sage: w = Word([3,1]) 

sage: w.is_yamanouchi(n=3) 

False 

sage: w.is_yamanouchi() 

True 

sage: w = Word([3,1],alphabet=[1,2,3]) 

sage: w.is_yamanouchi() 

False 

sage: w = Word([2,1,1,2]) 

sage: w.is_yamanouchi() 

False 

""" 

from sage.combinat.words.word import Word 

if n is not None: 

w = Word(self, alphabet=list(range(1,n+1))) 

elif not self.parent().alphabet().cardinality() == +Infinity: 

w = self 

else: 

w = Word(self, alphabet=sorted(self.letters())) 

l = w.length() 

for a in range(l-1,-1,-1): 

mu = w.parent()(self[a:]).content() 

if not all(mu[i] >= mu[i+1] for i in range(len(mu)-1)): 

return False 

return True 

 

def schuetzenberger_involution(self, n = None): 

""" 

Return the Schützenberger involution of the word ``self``, which is obtained 

by reverting the word and then complementing all letters within the 

underlying ordered alphabet. If ``n`` is specified, the underlying 

alphabet is assumed to be `[1,2,\ldots,n]`. If no alphabet is specified, 

`n` is the maximal letter appearing in ``self``. 

 

INPUT: 

 

- ``self`` -- a word 

- ``n`` -- an integer specifying the maximal letter in the alphabet (optional) 

 

OUTPUT: 

 

a word, the Schützenberger involution of ``self`` 

 

EXAMPLES:: 

 

sage: w = Word([9,7,4,1,6,2,3]) 

sage: v = w.schuetzenberger_involution(); v 

word: 7849631 

sage: v.parent() 

Finite words over Set of Python objects of class 'object' 

 

sage: w = Word([1,2,3],alphabet=[1,2,3,4,5]) 

sage: v = w.schuetzenberger_involution();v 

word: 345 

sage: v.parent() 

Finite words over {1, 2, 3, 4, 5} 

 

sage: w = Word([1,2,3]) 

sage: v = w.schuetzenberger_involution(n=5);v 

word: 345 

sage: v.parent() 

Finite words over Set of Python objects of class 'object' 

 

sage: w = Word([11,32,69,2,53,1,2,3,18,41]) 

sage: w.schuetzenberger_involution() 

word: 29,52,67,68,69,17,68,1,38,59 

 

sage: w = Word([],alphabet=[1,2,3,4,5]) 

sage: w.schuetzenberger_involution() 

word: 

 

sage: w = Word([]) 

sage: w.schuetzenberger_involution() 

word: 

""" 

if self.length() == 0: 

return self 

r = self.reversal() 

w = list(r) 

parent = self.parent() 

if n is None: 

alphsize = parent.alphabet().cardinality() 

if not alphsize == +Infinity: 

n = max(parent.alphabet()) 

elif r.length()>0: 

n = max(w) 

for k in range(r.length()): 

w[k] = n+1 - w[k] 

return parent(w, check=False) 

 

def foata_bijection(self): 

r""" 

Return word ``self`` under the Foata bijection. 

 

The Foata bijection `\phi` is a bijection on the set of words 

of given content (by a slight generalization of Section 2 in [FoSc78]_). 

It can be defined by induction on the size of the word: Given a word 

`w_1 w_2 \cdots w_n`, start with `\phi(w_1) = w_1`. At the `i`-th step, if 

`\phi(w_1 w_2 \cdots w_i) = v_1 v_2 \cdots v_i`, we define 

`\phi(w_1 w_2 \cdots w_i w_{i+1})` by placing `w_{i+1}` on the end of 

the word `v_1 v_2 \cdots v_i` and breaking the word up into blocks 

as follows. If `w_{i+1} \ge v_i`, place a vertical line to the right 

of each `v_k` for which `w_{i+1} \ge v_k`. Otherwise, if 

`w_{i+1} < v_i`, place a vertical line to the right of each `v_k` 

for which `w_{i+1} < v_k`. In either case, place a vertical line at 

the start of the word as well. Now, within each block between 

vertical lines, cyclically shift the entries one place to the 

right. 

 

For instance, to compute `\phi([4,1,5,4,2,2,3])`, the sequence of 

words is 

 

* `4`, 

* `|4|1 \to 41`, 

* `|4|1|5 \to 415`, 

* `|415|4 \to 5414`, 

* `|5|4|14|2 \to 54412`, 

* `|5441|2|2 \to 154422`, 

* `|1|5442|2|3 \to 1254423`. 

 

So `\phi([4,1,5,4,2,2,3]) = [1,2,5,4,4,2,3]`. 

 

.. SEEALSO:: 

 

:meth:`Foata bijection on Permutations <sage.combinat.permutation.Permutation.foata_bijection()>`. 

 

EXAMPLES:: 

 

sage: w = Word([2,2,2,1,1,1]) 

sage: w.foata_bijection() 

word: 112221 

sage: w = Word([2,2,1,2,2,2,1,1,2,1]) 

sage: w.foata_bijection() 

word: 2122212211 

sage: w = Word([4,1,5,4,2,2,3]) 

sage: w.foata_bijection() 

word: 1254423 

 

TESTS:: 

 

sage: w = Word('121314') 

sage: w.foata_bijection() 

word: 231114 

sage: w = Word('1133a1') 

sage: w.foata_bijection() 

word: 3113a1 

""" 

s = self.standard_permutation() 

ordered_alphabet = sorted(self.letters(), 

key=self.parent().sortkey_letters) 

eval_dict = self.evaluation_dict() 

weight = [eval_dict[a] for a in ordered_alphabet] 

return (s.foata_bijection()).destandardize(weight, ordered_alphabet=ordered_alphabet) 

 

def major_index(self, final_descent=False): 

r""" 

Return the major index of ``self``. 

 

The major index of a word `w` is the sum of the descents of `w`. 

 

With the ``final_descent`` option, the last position of a 

non-empty word is also considered as a descent. 

 

.. SEEALSO:: 

 

:meth:`major index on Permutations <sage.combinat.permutation.Permutation.major_index()>`. 

 

EXAMPLES:: 

 

sage: w = Word([2,1,3,3,2]) 

sage: w.major_index() 

5 

sage: w = Word([2,1,3,3,2]) 

sage: w.major_index(final_descent=True) 

10 

""" 

return (self.standard_permutation()).major_index(final_descent=final_descent) 

 

def number_of_inversions(self): 

r""" 

Return the number of inversions in ``self``. 

 

An inversion of a word `w = w_1 \ldots w_n` is a pair of indices `(i, j)` 

with `i < j` and `w_i > w_j`. 

 

.. SEEALSO:: 

 

:meth:`number of inversions on Permutations <sage.combinat.permutation.Permutation.number_of_inversions()>`. 

 

EXAMPLES:: 

 

sage: w = Word([2,1,3,3,2]) 

sage: w.number_of_inversions() 

3 

""" 

return (self.standard_permutation()).number_of_inversions() 

 

def is_empty(self): 

r""" 

Return ``True`` if the length of ``self`` is zero, and ``False`` otherwise. 

 

EXAMPLES:: 

 

sage: Word([]).is_empty() 

True 

sage: Word('a').is_empty() 

False 

""" 

return self.length()==0 

 

def is_finite(self): 

r""" 

Return ``True``. 

 

EXAMPLES:: 

 

sage: Word([]).is_finite() 

True 

sage: Word('a').is_finite() 

True 

""" 

return True 

 

def to_integer_word(self): 

r""" 

Return a word defined over the integers ``[0,1,...,self.length()-1]`` 

whose letters are in the same relative order in the parent. 

 

EXAMPLES:: 

 

sage: from itertools import count 

sage: w = Word('abbabaab') 

sage: w.to_integer_word() 

word: 01101001 

sage: w = Word(iter("cacao"), length="finite") 

sage: w.to_integer_word() 

word: 10102 

 

sage: w = Words([3,2,1])([2,3,3,1]) 

sage: w.to_integer_word() 

word: 1002 

""" 

from sage.combinat.words.word import Word 

return Word(self.to_integer_list()) 

 

def to_integer_list(self): 

r""" 

Return a list of integers from ``[0,1,...,self.length()-1]`` in the 

same relative order as the letters in ``self`` in the parent. 

 

EXAMPLES:: 

 

sage: from itertools import count 

sage: w = Word('abbabaab') 

sage: w.to_integer_list() 

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

sage: w = Word(iter("cacao"), length="finite") 

sage: w.to_integer_list() 

[1, 0, 1, 0, 2] 

sage: w = Words([3,2,1])([2,3,3,1]) 

sage: w.to_integer_list() 

[1, 0, 0, 2] 

""" 

cmp_key = self._parent.sortkey_letters 

ordered_alphabet = sorted(self.letters(), key=cmp_key) 

index = dict((b,a) for (a,b) in enumerate(ordered_alphabet)) 

return [index[a] for a in self] 

 

# To fix : do not slice here ! (quite expensive in copy) 

def is_suffix(self, other): 

r""" 

Return ``True`` if ``self`` is a suffix of ``other``, and ``False`` otherwise. 

 

EXAMPLES:: 

 

sage: w = Word('0123456789') 

sage: y = Word('56789') 

sage: y.is_suffix(w) 

True 

sage: w.is_suffix(y) 

False 

sage: Word('579').is_suffix(w) 

False 

sage: Word().is_suffix(y) 

True 

sage: w.is_suffix(Word()) 

False 

sage: Word().is_suffix(Word()) 

True 

""" 

return self.is_empty() or self == other[-self.length():] 

 

def is_proper_suffix(self, other): 

r""" 

Return ``True`` if ``self`` is a proper suffix of ``other``, and ``False`` otherwise. 

 

EXAMPLES:: 

 

sage: Word('23').is_proper_suffix(Word('123')) 

True 

sage: Word('12').is_proper_suffix(Word('12')) 

False 

sage: Word().is_proper_suffix(Word('123')) 

True 

sage: Word('123').is_proper_suffix(Word('12')) 

False 

""" 

return self.is_suffix(other) and self.length() < other.length() 

 

def has_suffix(self, other): 

""" 

Test whether ``self`` has ``other`` as a suffix. 

 

.. note:: 

 

Some word datatype classes, like :class:`WordDatatype_str`, 

override this method. 

 

INPUT: 

 

- ``other`` -- a word, or data describing a word 

 

OUTPUT: 

 

boolean 

 

EXAMPLES:: 

 

sage: w = Word("abbabaabababa") 

sage: u = Word("ababa") 

sage: w.has_suffix(u) 

True 

sage: u.has_suffix(w) 

False 

sage: u.has_suffix("ababa") 

True 

 

:: 

 

sage: w = Word([0,1,1,0,1,0,0,1,0,1,0,1,0]) 

sage: u = Word([0,1,0,1,0]) 

sage: w.has_suffix(u) 

True 

sage: u.has_suffix(w) 

False 

sage: u.has_suffix([0,1,0,1,0]) 

True 

 

""" 

from sage.combinat.words.word import Word 

w = Word(other) 

return w.is_suffix(self) 

 

def is_prefix(self, other): 

r""" 

Return ``True`` if ``self`` is a prefix of ``other``, and ``False`` otherwise. 

 

EXAMPLES:: 

 

sage: w = Word('0123456789') 

sage: y = Word('012345') 

sage: y.is_prefix(w) 

True 

sage: w.is_prefix(y) 

False 

sage: w.is_prefix(Word()) 

False 

sage: Word().is_prefix(w) 

True 

sage: Word().is_prefix(Word()) 

True 

""" 

return self == other[:self.length()] 

 

def is_proper_prefix(self, other): 

r""" 

Return ``True`` if ``self`` is a proper prefix of ``other``, and ``False`` otherwise. 

 

EXAMPLES:: 

 

sage: Word('12').is_proper_prefix(Word('123')) 

True 

sage: Word('12').is_proper_prefix(Word('12')) 

False 

sage: Word().is_proper_prefix(Word('123')) 

True 

sage: Word('123').is_proper_prefix(Word('12')) 

False 

sage: Word().is_proper_prefix(Word()) 

False 

""" 

return self.is_prefix(other) and self.length() < other.length() 

 

def has_prefix(self, other): 

r""" 

Test whether ``self`` has ``other`` as a prefix. 

 

INPUT: 

 

- ``other`` -- a word, or data describing a word 

 

OUTPUT: 

 

boolean 

 

EXAMPLES:: 

 

sage: w = Word("abbabaabababa") 

sage: u = Word("abbab") 

sage: w.has_prefix(u) 

True 

sage: u.has_prefix(w) 

False 

sage: u.has_prefix("abbab") 

True 

 

:: 

 

sage: w = Word([0,1,1,0,1,0,0,1,0,1,0,1,0]) 

sage: u = Word([0,1,1,0,1]) 

sage: w.has_prefix(u) 

True 

sage: u.has_prefix(w) 

False 

sage: u.has_prefix([0,1,1,0,1]) 

True 

 

 

""" 

from sage.combinat.words.word import Word 

w = Word(other) 

return w.is_prefix(self) 

 

def reversal(self): 

r""" 

Return the reversal of ``self``. 

 

EXAMPLES:: 

 

sage: Word('124563').reversal() 

word: 365421 

""" 

return self[::-1] 

 

@cached_method 

def prefix_function_table(self): 

r""" 

Return a vector containing the length of the proper prefix-suffixes 

for all the non-empty prefixes of ``self``. 

 

EXAMPLES:: 

 

sage: Word('121321').prefix_function_table() 

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

sage: Word('1241245').prefix_function_table() 

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

sage: Word().prefix_function_table() 

[] 

""" 

k = 0 

res = [0]*self.length() 

for q in range(1, self.length()): 

while k > 0 and self[k] != self[q]: 

k = res[k-1] 

if self[k] == self[q]: 

k += 1 

res[q] = k 

return res 

 

@cached_method 

def good_suffix_table(self): 

r""" 

Return a table of the maximum skip you can do in order not to miss 

a possible occurrence of ``self`` in a word. 

 

This is a part of the Boyer-Moore algorithm to find factors. See [1]. 

 

EXAMPLES:: 

 

sage: Word('121321').good_suffix_table() 

[5, 5, 5, 5, 3, 3, 1] 

sage: Word('12412').good_suffix_table() 

[3, 3, 3, 3, 3, 1] 

 

REFERENCES: 

 

- [1] R.S. Boyer, J.S. Moore, A fast string searching algorithm, 

Communications of the ACM 20 (1977) 762--772. 

""" 

l = self.length() 

p = self.reversal().prefix_function_table() 

res = [l - p[-1]]*(l+1) 

for i in range(1, l+1): 

j = l - p[i - 1] 

if res[j] > (i - p[i-1]): 

res[j] = i - p[i-1] 

return res 

 

@cached_method 

def suffix_trie(self): 

r""" 

Return the suffix trie of ``self``. 

 

The *suffix trie* of a finite word `w` is a data structure 

representing the factors of `w`. It is a tree whose edges are 

labelled with letters of `w`, and whose leafs correspond to 

suffixes of `w`. 

 

Type ``sage.combinat.words.suffix_trees.SuffixTrie?`` for more information. 

 

EXAMPLES:: 

 

sage: w = Word("cacao") 

sage: w.suffix_trie() 

Suffix Trie of the word: cacao 

 

:: 

 

sage: w = Word([0,1,0,1,1]) 

sage: w.suffix_trie() 

Suffix Trie of the word: 01011 

""" 

from sage.combinat.words.suffix_trees import SuffixTrie 

return SuffixTrie(self) 

 

def implicit_suffix_tree(self): 

r""" 

Return the implicit suffix tree of ``self``. 

 

The *suffix tree* of a word `w` is a compactification of the 

suffix trie for `w`. The compactification removes all nodes that have 

exactly one incoming edge and exactly one outgoing edge. It consists of 

two components: a tree and a word. Thus, instead of labelling the edges 

by factors of `w`, we can label them by indices of the occurrence of 

the factors in `w`. 

 

Type ``sage.combinat.words.suffix_trees.ImplicitSuffixTree?`` for more information. 

 

EXAMPLES:: 

 

sage: w = Word("cacao") 

sage: w.implicit_suffix_tree() 

Implicit Suffix Tree of the word: cacao 

 

:: 

 

sage: w = Word([0,1,0,1,1]) 

sage: w.implicit_suffix_tree() 

Implicit Suffix Tree of the word: 01011 

""" 

from sage.combinat.words.suffix_trees import ImplicitSuffixTree 

return ImplicitSuffixTree(self) 

 

@cached_method 

def suffix_tree(self): 

r""" 

Alias for ``implicit_suffix_tree()``. 

 

EXAMPLES:: 

 

sage: Word('abbabaab').suffix_tree() 

Implicit Suffix Tree of the word: abbabaab 

""" 

return self.implicit_suffix_tree() 

 

def number_of_factors(self, n=None, algorithm='suffix tree'): 

r""" 

Count the number of distinct factors of ``self``. 

 

INPUT: 

 

- ``n`` -- an integer, or ``None``. 

- ``algorithm`` -- string (default: ``'suffix tree'``), takes the 

following values: 

 

- ``'suffix tree'`` -- construct and use the suffix tree of the word 

- ``'naive'`` -- algorithm uses a sliding window 

 

OUTPUT: 

 

If ``n`` is an integer, returns the number of distinct factors 

of length ``n``. If ``n`` is ``None``, returns the total number of 

distinct factors. 

 

EXAMPLES:: 

 

sage: w = Word([1,2,1,2,3]) 

sage: w.number_of_factors() 

13 

sage: [w.number_of_factors(i) for i in range(6)] 

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

 

:: 

 

sage: w = words.ThueMorseWord()[:100] 

sage: [w.number_of_factors(i) for i in range(10)] 

[1, 2, 4, 6, 10, 12, 16, 20, 22, 24] 

 

:: 

 

sage: Word('1213121').number_of_factors() 

22 

sage: Word('1213121').number_of_factors(1) 

3 

 

:: 

 

sage: Word('a'*100).number_of_factors() 

101 

sage: Word('a'*100).number_of_factors(77) 

1 

 

:: 

 

sage: Word().number_of_factors() 

1 

sage: Word().number_of_factors(17) 

0 

 

:: 

 

sage: blueberry = Word("blueberry") 

sage: blueberry.number_of_factors() 

43 

sage: [blueberry.number_of_factors(i) for i in range(10)] 

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

""" 

if algorithm == 'suffix tree': 

return self.suffix_tree().number_of_factors(n) 

elif algorithm == 'naive': 

return len(self.factor_set(n, algorithm='naive')) 

else: 

raise ValueError('Unknown algorithm (={})'.format(algorithm)) 

 

def factor_iterator(self, n=None): 

r""" 

Generate distinct factors of ``self``. 

 

INPUT: 

 

- ``n`` -- an integer, or ``None``. 

 

OUTPUT: 

 

If ``n`` is an integer, returns an iterator over all distinct 

factors of length ``n``. If ``n`` is ``None``, returns an iterator 

generating all distinct factors. 

 

EXAMPLES:: 

 

sage: w = Word('1213121') 

sage: sorted( w.factor_iterator(0) ) 

[word: ] 

sage: sorted( w.factor_iterator(10) ) 

[] 

sage: sorted( w.factor_iterator(1) ) 

[word: 1, word: 2, word: 3] 

sage: sorted( w.factor_iterator(4) ) 

[word: 1213, word: 1312, word: 2131, word: 3121] 

sage: sorted( w.factor_iterator() ) 

[word: , word: 1, word: 12, word: 121, word: 1213, word: 12131, word: 121312, word: 1213121, word: 13, word: 131, word: 1312, word: 13121, word: 2, word: 21, word: 213, word: 2131, word: 21312, word: 213121, word: 3, word: 31, word: 312, word: 3121] 

 

:: 

 

sage: u = Word([1,2,1,2,3]) 

sage: sorted( u.factor_iterator(0) ) 

[word: ] 

sage: sorted( u.factor_iterator(10) ) 

[] 

sage: sorted( u.factor_iterator(1) ) 

[word: 1, word: 2, word: 3] 

sage: sorted( u.factor_iterator(5) ) 

[word: 12123] 

sage: sorted( u.factor_iterator() ) 

[word: , word: 1, word: 12, word: 121, word: 1212, word: 12123, word: 123, word: 2, word: 21, word: 212, word: 2123, word: 23, word: 3] 

 

:: 

 

sage: xxx = Word("xxx") 

sage: sorted( xxx.factor_iterator(0) ) 

[word: ] 

sage: sorted( xxx.factor_iterator(4) ) 

[] 

sage: sorted( xxx.factor_iterator(2) ) 

[word: xx] 

sage: sorted( xxx.factor_iterator() ) 

[word: , word: x, word: xx, word: xxx] 

 

:: 

 

sage: e = Word() 

sage: sorted( e.factor_iterator(0) ) 

[word: ] 

sage: sorted( e.factor_iterator(17) ) 

[] 

sage: sorted( e.factor_iterator() ) 

[word: ] 

 

TESTS:: 

 

sage: type( Word('cacao').factor_iterator() ) 

<... 'generator'> 

""" 

return self.suffix_tree().factor_iterator(n) 

 

def factor_set(self, n=None, algorithm='suffix tree'): 

r""" 

Return the set of factors (of length ``n``) of ``self``. 

 

INPUT: 

 

- ``n`` -- an integer or ``None`` (default: ``None``). 

- ``algorithm`` -- string (default: ``'suffix tree'``), takes the 

following values: 

 

- ``'suffix tree'`` -- construct and use the suffix tree of the word 

- ``'naive'`` -- algorithm uses a sliding window 

 

OUTPUT: 

 

If ``n`` is an integer, returns the set of all distinct 

factors of length ``n``. If ``n`` is ``None``, returns the set 

of all distinct factors. 

 

EXAMPLES:: 

 

sage: w = Word('121') 

sage: sorted(w.factor_set()) 

[word: , word: 1, word: 12, word: 121, word: 2, word: 21] 

sage: sorted(w.factor_set(algorithm='naive')) 

[word: , word: 1, word: 12, word: 121, word: 2, word: 21] 

 

:: 

 

sage: w = Word('1213121') 

sage: for i in range(w.length()): sorted(w.factor_set(i)) 

[word: ] 

[word: 1, word: 2, word: 3] 

[word: 12, word: 13, word: 21, word: 31] 

[word: 121, word: 131, word: 213, word: 312] 

[word: 1213, word: 1312, word: 2131, word: 3121] 

[word: 12131, word: 13121, word: 21312] 

[word: 121312, word: 213121] 

 

:: 

 

sage: w = Word([1,2,1,2,3]) 

sage: s = w.factor_set() 

sage: sorted(s) 

[word: , word: 1, word: 12, word: 121, word: 1212, word: 12123, word: 123, word: 2, word: 21, word: 212, word: 2123, word: 23, word: 3] 

 

TESTS:: 

 

sage: w = Word("xx") 

sage: s = w.factor_set() 

sage: sorted(s) 

[word: , word: x, word: xx] 

 

:: 

 

sage: Set(Word().factor_set()) 

{word: } 

 

:: 

 

sage: w = Word(range(10), alphabet=range(10)) 

sage: S1 = w.factor_set(3, algorithm='suffix tree') 

sage: S2 = w.factor_set(3, algorithm='naive') 

sage: S1 == S2 

True 

""" 

if algorithm == 'suffix tree': 

return Set(self.factor_iterator(n)) 

elif algorithm == 'naive': 

if n is None: 

S = set([self[0:0]]) 

for n in range(1, self.length()+1): 

for i in range(self.length()-n+1): 

S.add(self[i:i+n]) 

return Set(S) 

else: 

S = set() 

for i in range(self.length()-n+1): 

S.add(self[i:i+n]) 

return Set(S) 

else: 

raise ValueError('Unknown algorithm (={})'.format(algorithm)) 

 

def topological_entropy(self, n): 

r""" 

Return the topological entropy for the factors of length ``n``. 

 

The topological entropy of a sequence `u` is defined as the 

exponential growth rate of the complexity of `u` as the length 

increases: `H_{top}(u)=\lim_{n\to\infty}\frac{\log_d(p_u(n))}{n}` 

where `d` denotes the cardinality of the alphabet and `p_u(n)` is 

the complexity function, i.e. the number of factors of length `n` 

in the sequence `u` [1]. 

 

INPUT: 

 

- ``self`` -- a word defined over a finite alphabet 

- ``n`` -- positive integer 

 

OUTPUT: 

 

real number (a symbolic expression) 

 

EXAMPLES:: 

 

sage: W = Words([0, 1]) 

sage: w = W([0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1]) 

sage: t = w.topological_entropy(3); t 

1/3*log(7)/log(2) 

sage: n(t) 

0.935784974019201 

 

:: 

 

sage: w = words.ThueMorseWord()[:100] 

sage: topo = w.topological_entropy 

sage: for i in range(0, 41, 5): 

....: print("{} {}".format(i, n(topo(i), digits=5))) 

0 1.0000 

5 0.71699 

10 0.48074 

15 0.36396 

20 0.28774 

25 0.23628 

30 0.20075 

35 0.17270 

40 0.14827 

 

If no alphabet is specified, an error is raised:: 

 

sage: w = Word(range(20)) 

sage: w.topological_entropy(3) 

Traceback (most recent call last): 

... 

TypeError: The word must be defined over a finite alphabet 

 

The following is ok:: 

 

sage: W = Words(range(20)) 

sage: w = W(range(20)) 

sage: w.topological_entropy(3) 

1/3*log(18)/log(20) 

 

REFERENCES: 

 

[1] N. Pytheas Fogg, Substitutions in Dynamics, Arithmetics, 

and Combinatorics, Lecture Notes in Mathematics 1794, Springer 

Verlag. V. Berthe, S. Ferenczi, C. Mauduit and A. Siegel, Eds. 

(2002). 

""" 

d = self.parent().alphabet().cardinality() 

if d is Infinity: 

raise TypeError("The word must be defined over a finite alphabet") 

if n == 0: 

return 1 

pn = self.number_of_factors(n) 

from sage.functions.all import log 

return log(pn, base=d)/n 

 

def rauzy_graph(self, n): 

r""" 

Return the Rauzy graph of the factors of length ``n`` of ``self``. 

 

The vertices are the factors of length `n` and there is an edge from 

`u` to `v` if `ua = bv` is a factor of length `n+1` for some letters 

`a` and `b`. 

 

INPUT: 

 

- ``n`` -- integer 

 

EXAMPLES:: 

 

sage: w = Word(range(10)); w 

word: 0123456789 

sage: g = w.rauzy_graph(3); g 

Looped digraph on 8 vertices 

sage: WordOptions(identifier='') 

sage: g.vertices() 

[012, 123, 234, 345, 456, 567, 678, 789] 

sage: g.edges() 

[(012, 123, 3), 

(123, 234, 4), 

(234, 345, 5), 

(345, 456, 6), 

(456, 567, 7), 

(567, 678, 8), 

(678, 789, 9)] 

sage: WordOptions(identifier='word: ') 

 

:: 

 

sage: f = words.FibonacciWord()[:100] 

sage: f.rauzy_graph(8) 

Looped digraph on 9 vertices 

 

:: 

 

sage: w = Word('1111111') 

sage: g = w.rauzy_graph(3) 

sage: g.edges() 

[(word: 111, word: 111, word: 1)] 

 

:: 

 

sage: w = Word('111') 

sage: for i in range(5) : w.rauzy_graph(i) 

Looped multi-digraph on 1 vertex 

Looped digraph on 1 vertex 

Looped digraph on 1 vertex 

Looped digraph on 1 vertex 

Looped digraph on 0 vertices 

 

Multi-edges are allowed for the empty word:: 

 

sage: W = Words('abcde') 

sage: w = W('abc') 

sage: w.rauzy_graph(0) 

Looped multi-digraph on 1 vertex 

sage: _.edges() 

[(word: , word: , word: a), 

(word: , word: , word: b), 

(word: , word: , word: c)] 

""" 

from sage.graphs.digraph import DiGraph 

multiedges = n == 0 

g = DiGraph(loops=True, multiedges=multiedges) 

if n == self.length(): 

g.add_vertex(self) 

else: 

for w in self.factor_iterator(n+1): 

u = w[:-1] 

v = w[1:] 

a = w[-1:] 

g.add_edge(u,v,a) 

return g 

 

def reduced_rauzy_graph(self, n): 

r""" 

Return the reduced Rauzy graph of order ``n`` of ``self``. 

 

INPUT: 

 

- ``n`` -- a non-negative integer. Every vertex of a reduced 

Rauzy graph of order ``n`` is a factor of length ``n`` of ``self``. 

 

OUTPUT: 

 

a looped multi-digraph 

 

DEFINITION: 

 

For infinite periodic words (resp. for finite words of type `u^i 

u[0:j]`), the reduced Rauzy graph of order `n` (resp. for `n` 

smaller or equal to `(i-1)|u|+j`) is the directed graph whose 

unique vertex is the prefix `p` of length `n` of ``self`` and which has 

an only edge which is a loop on `p` labelled by `w[n+1:|w|] p` 

where `w` is the unique return word to `p`. 

 

In other cases, it is the directed graph defined as followed. Let 

`G_n` be the Rauzy graph of order `n` of self. The vertices are the 

vertices of `G_n` that are either special or not prolongable to the 

right or to the left. For each couple (`u`, `v`) of such vertices 

and each directed path in `G_n` from `u` to `v` that contains no 

other vertices that are special, there is an edge from `u` to `v` 

in the reduced Rauzy graph of order `n` whose label is the label of 

the path in `G_n`. 

 

.. NOTE:: 

 

In the case of infinite recurrent non-periodic words, this 

definition corresponds to the following one that can be found in 

[1] and [2] where a simple path is a path that begins with a 

special factor, ends with a special factor and contains no 

other vertices that are special: 

 

The reduced Rauzy graph of factors of length `n` is obtained 

from `G_n` by replacing each simple path `P=v_1 v_2 ... 

v_{\ell}` with an edge `v_1 v_{\ell}` whose label is the 

concatenation of the labels of the edges of `P`. 

 

EXAMPLES:: 

 

sage: w = Word(range(10)); w 

word: 0123456789 

sage: g = w.reduced_rauzy_graph(3); g 

Looped multi-digraph on 2 vertices 

sage: g.vertices() 

[word: 012, word: 789] 

sage: g.edges() 

[(word: 012, word: 789, word: 3456789)] 

 

For the Fibonacci word:: 

 

sage: f = words.FibonacciWord()[:100] 

sage: g = f.reduced_rauzy_graph(8);g 

Looped multi-digraph on 2 vertices 

sage: g.vertices() 

[word: 01001010, word: 01010010] 

sage: g.edges() 

[(word: 01001010, word: 01010010, word: 010), (word: 01010010, word: 01001010, word: 01010), (word: 01010010, word: 01001010, word: 10)] 

 

For periodic words:: 

 

sage: from itertools import cycle 

sage: w = Word(cycle('abcd'))[:100] 

sage: g = w.reduced_rauzy_graph(3) 

sage: g.edges() 

[(word: abc, word: abc, word: dabc)] 

 

:: 

 

sage: w = Word('111') 

sage: for i in range(5) : w.reduced_rauzy_graph(i) 

Looped digraph on 1 vertex 

Looped digraph on 1 vertex 

Looped digraph on 1 vertex 

Looped multi-digraph on 1 vertex 

Looped multi-digraph on 0 vertices 

 

For ultimately periodic words:: 

 

sage: sigma = WordMorphism('a->abcd,b->cd,c->cd,d->cd') 

sage: w = sigma.fixed_point('a')[:100]; w 

word: abcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd... 

sage: g = w.reduced_rauzy_graph(5) 

sage: g.vertices() 

[word: abcdc, word: cdcdc] 

sage: g.edges() 

[(word: abcdc, word: cdcdc, word: dc), (word: cdcdc, word: cdcdc, word: dc)] 

 

AUTHOR: 

 

Julien Leroy (March 2010): initial version 

 

REFERENCES: 

 

- [1] M. Bucci et al. A. De Luca, A. Glen, L. Q. Zamboni, A 

connection between palindromic and factor complexity using 

return words," Advances in Applied Mathematics 42 (2009) 60-74. 

 

- [2] L'ubomira Balkova, Edita Pelantova, and Wolfgang Steiner. 

Sequences with constant number of return words. Monatsh. Math, 

155 (2008) 251-263. 

""" 

from sage.graphs.digraph import DiGraph 

from copy import copy 

g = copy(self.rauzy_graph(n)) 

# Otherwise it changes the rauzy_graph function. 

l = [v for v in g if g.in_degree(v)==1 and g.out_degree(v)==1] 

if g.num_verts() != 0 and len(l) == g.num_verts(): 

# In this case, the Rauzy graph is simply a cycle. 

g = DiGraph() 

g.allow_loops(True) 

g.add_vertex(self[:n]) 

g.add_edge(self[:n],self[:n],self[n:n+len(l)]) 

else: 

g.allow_loops(True) 

g.allow_multiple_edges(True) 

for v in l: 

[i] = g.neighbors_in(v) 

[o] = g.neighbors_out(v) 

g.add_edge(i,o,g.edge_label(i,v)[0]*g.edge_label(v,o)[0]) 

g.delete_vertex(v) 

return g 

 

def left_special_factors_iterator(self, n=None): 

r""" 

Return an iterator over the left special factors (of length ``n``). 

 

A factor `u` of a word `w` is *left special* if there are 

two distinct letters `a` and `b` such that `au` and `bu` 

are factors of `w`. 

 

INPUT: 

 

- ``n`` -- integer (optional, default: ``None``). If ``None``, it returns 

an iterator over all left special factors. 

 

EXAMPLES:: 

 

sage: alpha, beta, x = 0.54, 0.294, 0.1415 

sage: w = words.CodingOfRotationWord(alpha, beta, x)[:40] 

sage: sorted(w.left_special_factors_iterator(3)) 

[word: 000, word: 010] 

sage: sorted(w.left_special_factors_iterator(4)) 

[word: 0000, word: 0101] 

sage: sorted(w.left_special_factors_iterator(5)) 

[word: 00000, word: 01010] 

""" 

if n is None: 

for i in range(self.length()): 

for w in self.left_special_factors_iterator(i): 

yield w 

else: 

left_extensions = defaultdict(set) 

for w in self.factor_iterator(n+1): 

v = w[1:] 

left_extensions[v].add(w[0]) 

for v in left_extensions: 

if len(left_extensions[v]) > 1: 

yield v 

 

def left_special_factors(self, n=None): 

r""" 

Return the left special factors (of length ``n``). 

 

A factor `u` of a word `w` is *left special* if there are 

two distinct letters `a` and `b` such that `au` and `bu` 

are factors of `w`. 

 

INPUT: 

 

- ``n`` -- integer (optional, default: ``None``). If ``None``, it 

returns all left special factors. 

 

OUTPUT: 

 

a list of words 

 

EXAMPLES:: 

 

sage: alpha, beta, x = 0.54, 0.294, 0.1415 

sage: w = words.CodingOfRotationWord(alpha, beta, x)[:40] 

sage: for i in range(5): 

....: print("{} {}".format(i, sorted(w.left_special_factors(i)))) 

0 [word: ] 

1 [word: 0] 

2 [word: 00, word: 01] 

3 [word: 000, word: 010] 

4 [word: 0000, word: 0101] 

""" 

return list(self.left_special_factors_iterator(n)) 

 

def right_special_factors_iterator(self, n=None): 

r""" 

Return an iterator over the right special factors (of length ``n``). 

 

A factor `u` of a word `w` is *right special* if there are 

two distinct letters `a` and `b` such that `ua` and `ub` 

are factors of `w`. 

 

INPUT: 

 

- ``n`` -- integer (optional, default: ``None``). If ``None``, it returns 

an iterator over all right special factors. 

 

EXAMPLES:: 

 

sage: alpha, beta, x = 0.61, 0.54, 0.3 

sage: w = words.CodingOfRotationWord(alpha, beta, x)[:40] 

sage: sorted(w.right_special_factors_iterator(3)) 

[word: 010, word: 101] 

sage: sorted(w.right_special_factors_iterator(4)) 

[word: 0101, word: 1010] 

sage: sorted(w.right_special_factors_iterator(5)) 

[word: 00101, word: 11010] 

""" 

if n is None: 

for i in range(self.length()): 

for w in self.right_special_factors_iterator(i): 

yield w 

else: 

right_extensions = defaultdict(set) 

for w in self.factor_iterator(n+1): 

v = w[:-1] 

right_extensions[v].add(w[-1]) 

for v in right_extensions: 

if len(right_extensions[v]) > 1: 

yield v 

 

def right_special_factors(self, n=None): 

r""" 

Return the right special factors (of length ``n``). 

 

A factor `u` of a word `w` is *right special* if there are 

two distinct letters `a` and `b` such that `ua` and `ub` 

are factors of `w`. 

 

INPUT: 

 

- ``n`` -- integer (optional, default: ``None``). If ``None``, it returns 

all right special factors. 

 

OUTPUT: 

 

a list of words 

 

EXAMPLES:: 

 

sage: w = words.ThueMorseWord()[:30] 

sage: for i in range(5): 

....: print("{} {}".format(i, sorted(w.right_special_factors(i)))) 

0 [word: ] 

1 [word: 0, word: 1] 

2 [word: 01, word: 10] 

3 [word: 001, word: 010, word: 101, word: 110] 

4 [word: 0110, word: 1001] 

""" 

return list(self.right_special_factors_iterator(n)) 

 

def bispecial_factors_iterator(self, n=None): 

r""" 

Return an iterator over the bispecial factors (of length ``n``). 

 

A factor `u` of a word `w` is *bispecial* if it is right special 

and left special. 

 

INPUT: 

 

- ``n`` -- integer (optional, default: ``None``). If ``None``, it returns 

an iterator over all bispecial factors. 

 

EXAMPLES:: 

 

sage: w = words.ThueMorseWord()[:30] 

sage: for i in range(10): 

....: for u in sorted(w.bispecial_factors_iterator(i)): 

....: print("{} {}".format(i,u)) 

0 

1 0 

1 1 

2 01 

2 10 

3 010 

3 101 

4 0110 

4 1001 

6 011001 

6 100110 

8 10010110 

 

:: 

 

sage: key = lambda u : (len(u), u) 

sage: for u in sorted(w.bispecial_factors_iterator(), key=key): u 

word: 

word: 0 

word: 1 

word: 01 

word: 10 

word: 010 

word: 101 

word: 0110 

word: 1001 

word: 011001 

word: 100110 

word: 10010110 

""" 

if n is None: 

for i in range(self.length()): 

for w in self.bispecial_factors_iterator(i): 

yield w 

else: 

left_extensions = defaultdict(set) 

right_extensions = defaultdict(set) 

for w in self.factor_iterator(n+2): 

v = w[1:-1] 

left_extensions[v].add(w[0]) 

right_extensions[v].add(w[-1]) 

for v in left_extensions: 

if (len(left_extensions[v]) > 1 and 

len(right_extensions[v]) > 1): 

yield v 

 

def bispecial_factors(self, n=None): 

r""" 

Return the bispecial factors (of length ``n``). 

 

A factor `u` of a word `w` is *bispecial* if it is right special 

and left special. 

 

INPUT: 

 

- ``n`` -- integer (optional, default: ``None``). If ``None``, it returns 

all bispecial factors. 

 

OUTPUT: 

 

a list of words 

 

EXAMPLES:: 

 

sage: w = words.FibonacciWord()[:30] 

sage: w.bispecial_factors() 

[word: , word: 0, word: 010, word: 010010, word: 01001010010] 

 

:: 

 

sage: w = words.ThueMorseWord()[:30] 

sage: for i in range(10): 

....: print("{} {}".format(i, sorted(w.bispecial_factors(i)))) 

0 [word: ] 

1 [word: 0, word: 1] 

2 [word: 01, word: 10] 

3 [word: 010, word: 101] 

4 [word: 0110, word: 1001] 

5 [] 

6 [word: 011001, word: 100110] 

7 [] 

8 [word: 10010110] 

9 [] 

""" 

return list(self.bispecial_factors_iterator(n)) 

 

def number_of_left_special_factors(self, n): 

r""" 

Return the number of left special factors of length ``n``. 

 

A factor `u` of a word `w` is *left special* if there are 

two distinct letters `a` and `b` such that `au` and `bu` 

are factors of `w`. 

 

INPUT: 

 

- ``n`` -- integer 

 

OUTPUT: 

 

a non-negative integer 

 

EXAMPLES:: 

 

sage: w = words.FibonacciWord()[:100] 

sage: [w.number_of_left_special_factors(i) for i in range(10)] 

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

 

:: 

 

sage: w = words.ThueMorseWord()[:100] 

sage: [w.number_of_left_special_factors(i) for i in range(10)] 

[1, 2, 2, 4, 2, 4, 4, 2, 2, 4] 

""" 

it = self.left_special_factors_iterator(n) 

return sum(1 for _ in it) 

 

def number_of_right_special_factors(self, n): 

r""" 

Return the number of right special factors of length ``n``. 

 

A factor `u` of a word `w` is *right special* if there are 

two distinct letters `a` and `b` such that `ua` and `ub` 

are factors of `w`. 

 

INPUT: 

 

- ``n`` -- integer 

 

OUTPUT: 

 

a non-negative integer 

 

EXAMPLES:: 

 

sage: w = words.FibonacciWord()[:100] 

sage: [w.number_of_right_special_factors(i) for i in range(10)] 

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

 

:: 

 

sage: w = words.ThueMorseWord()[:100] 

sage: [w.number_of_right_special_factors(i) for i in range(10)] 

[1, 2, 2, 4, 2, 4, 4, 2, 2, 4] 

""" 

it = self.right_special_factors_iterator(n) 

return sum(1 for _ in it) 

 

def commutes_with(self, other): 

r""" 

Return ``True`` if ``self`` commutes with ``other``, and ``False`` otherwise. 

 

EXAMPLES:: 

 

sage: Word('12').commutes_with(Word('12')) 

True 

sage: Word('12').commutes_with(Word('11')) 

False 

sage: Word().commutes_with(Word('21')) 

True 

""" 

return (self * other) == (other * self) 

 

def conjugate(self, pos): 

r""" 

Return the conjugate at ``pos`` of ``self``. 

 

``pos`` can be any integer, the distance used is the modulo by the length 

of ``self``. 

 

EXAMPLES:: 

 

sage: Word('12112').conjugate(1) 

word: 21121 

sage: Word().conjugate(2) 

word: 

sage: Word('12112').conjugate(8) 

word: 12121 

sage: Word('12112').conjugate(-1) 

word: 21211 

""" 

if self.is_empty(): 

return self 

pos_mod = pos % self.length() 

return self[pos_mod:] * self[:pos_mod] 

 

def _conjugates_list(self): 

r""" 

Return the list of conjugates of ``self``, ordered from the `0`-th to the 

`(L-1)`-st conjugate, where `L` is the length of ``self``. 

 

TESTS:: 

 

sage: Word('cbbca')._conjugates_list() 

[word: cbbca, word: bbcac, word: bcacb, word: cacbb, word: acbbc] 

sage: Word('abcabc')._conjugates_list() 

[word: abcabc, 

word: bcabca, 

word: cabcab, 

word: abcabc, 

word: bcabca, 

word: cabcab] 

sage: Word()._conjugates_list() 

[word: ] 

sage: Word('a')._conjugates_list() 

[word: a] 

""" 

S = [self] 

for i in range(1,self.length()): 

S.append(self.conjugate(i)) 

return S 

 

def conjugates_iterator(self): 

r""" 

Return an iterator over the conjugates of ``self``. 

 

EXAMPLES:: 

 

sage: it = Word(range(4)).conjugates_iterator() 

sage: for w in it: w 

word: 0123 

word: 1230 

word: 2301 

word: 3012 

""" 

yield self 

for i in range(1, self.primitive_length()): 

yield self.conjugate(i) 

 

def conjugates(self): 

r""" 

Return the list of unique conjugates of ``self``. 

 

EXAMPLES:: 

 

sage: Word(range(6)).conjugates() 

[word: 012345, 

word: 123450, 

word: 234501, 

word: 345012, 

word: 450123, 

word: 501234] 

sage: Word('cbbca').conjugates() 

[word: cbbca, word: bbcac, word: bcacb, word: cacbb, word: acbbc] 

 

The result contains each conjugate only once:: 

 

sage: Word('abcabc').conjugates() 

[word: abcabc, word: bcabca, word: cabcab] 

 

TESTS:: 

 

sage: Word().conjugates() 

[word: ] 

sage: Word('a').conjugates() 

[word: a] 

""" 

return list(self.conjugates_iterator()) 

 

def conjugate_position(self, other): 

r""" 

Return the position where ``self`` is conjugate with ``other``. 

Return ``None`` if there is no such position. 

 

EXAMPLES:: 

 

sage: Word('12113').conjugate_position(Word('31211')) 

1 

sage: Word('12131').conjugate_position(Word('12113')) is None 

True 

sage: Word().conjugate_position(Word('123')) is None 

True 

 

TESTS: 

 

We check that :trac:`11128` is fixed:: 

 

sage: w = Word([0,0,1,0,2,1]) 

sage: [w.conjugate(i).conjugate_position(w) for i in range(w.length())] 

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

""" 

if self.length() != other.length(): 

return None 

other_square = other * other 

pos = other_square.find(self) 

return pos if pos != -1 else None 

 

def is_conjugate_with(self, other): 

r""" 

Return ``True` if ``self`` is a conjugate of ``other``, and ``False`` otherwise. 

 

INPUT: 

 

- ``other`` -- a finite word 

 

OUTPUT: 

 

bool 

 

EXAMPLES:: 

 

sage: w = Word([0..20]) 

sage: z = Word([7..20] + [0..6]) 

sage: w 

word: 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 

sage: z 

word: 7,8,9,10,11,12,13,14,15,16,17,18,19,20,0,1,2,3,4,5,6 

sage: w.is_conjugate_with(z) 

True 

sage: z.is_conjugate_with(w) 

True 

sage: u = Word([4]*21) 

sage: u.is_conjugate_with(w) 

False 

sage: u.is_conjugate_with(z) 

False 

 

Both words must be finite:: 

 

sage: w = Word(iter([2]*100),length='unknown') 

sage: z = Word([2]*100) 

sage: z.is_conjugate_with(w) #TODO: Not implemented for word of unknown length 

True 

sage: wf = Word(iter([2]*100),length='finite') 

sage: z.is_conjugate_with(wf) 

True 

sage: wf.is_conjugate_with(z) 

True 

 

TESTS:: 

 

sage: Word('11213').is_conjugate_with(Word('31121')) 

True 

sage: Word().is_conjugate_with(Word('123')) 

False 

sage: Word('112131').is_conjugate_with(Word('11213')) 

False 

sage: Word('12131').is_conjugate_with(Word('11213')) 

True 

 

We make sure that :trac:`11128` is fixed:: 

 

sage: Word('abaa').is_conjugate_with(Word('aaba')) 

True 

sage: Word('aaba').is_conjugate_with(Word('abaa')) 

True 

""" 

return self.length() == other.length() and self.is_factor(other * other) 

 

def is_cadence(self, seq): 

r""" 

Return ``True`` if ``seq`` is a cadence of ``self``, and ``False`` otherwise. 

 

A *cadence* is an increasing sequence of indexes that all map to 

the same letter. 

 

EXAMPLES:: 

 

sage: Word('121132123').is_cadence([0, 2, 6]) 

True 

sage: Word('121132123').is_cadence([0, 1, 2]) 

False 

sage: Word('121132123').is_cadence([]) 

True 

""" 

if len(seq) == 0: 

return True 

try: 

it = iter(self) 

s = next(islice(it, seq[0], None)) 

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

steps = seq[i] - seq[i-1] 

for n in range(steps-1): next(it) 

if next(it) != s: 

return False 

except StopIteration: 

return False 

return True 

 

def longest_forward_extension(self, x, y): 

r""" 

Compute the length of the longest factor of ``self`` that 

starts at ``x`` and that matches a factor that starts at ``y``. 

 

INPUT: 

 

- ``x``, ``y`` -- positions in ``self`` 

 

EXAMPLES:: 

 

sage: w = Word('0011001') 

sage: w.longest_forward_extension(0, 4) 

3 

sage: w.longest_forward_extension(0, 2) 

0 

 

The method also accepts negative positions indicating the distance from 

the end of the word (in order to be consist with how negative indices 

work with lists). For instance, for a word of length `7`, using 

positions `-3` and `2` is the same as using positions `4` and `2`:: 

 

sage: w.longest_forward_extension(1, -2) 

2 

sage: w.longest_forward_extension(4, -3) 

3 

 

TESTS:: 

 

sage: w = Word('0011001') 

sage: w.longest_forward_extension(-10, 2) 

Traceback (most recent call last): 

... 

ValueError: x and y must be valid positions in self 

 

""" 

length = self.length() 

if not (-length <= x < length and -length <= y < length): 

raise ValueError("x and y must be valid positions in self") 

if x < 0: 

x = x + length 

if y < 0: 

y = y + length 

l = 0 

while x < length and y < length and self[x] == self[y]: 

l += 1 

x += 1 

y += 1 

return l 

 

def longest_backward_extension(self, x, y): 

r""" 

Compute the length of the longest factor of ``self`` that 

ends at ``x`` and that matches a factor that ends at ``y``. 

 

INPUT: 

 

- ``x``, ``y`` -- positions in ``self`` 

 

EXAMPLES:: 

 

sage: w = Word('0011001') 

sage: w.longest_backward_extension(6, 2) 

3 

sage: w.longest_backward_extension(1, 4) 

1 

sage: w.longest_backward_extension(1, 3) 

0 

 

The method also accepts negative positions indicating the distance from 

the end of the word (in order to be consist with how negative indices 

work with lists). For instance, for a word of length `7`, using 

positions `6` and `-5` is the same as using positions `6` and `2`:: 

 

sage: w.longest_backward_extension(6, -5) 

3 

sage: w.longest_backward_extension(-6, 4) 

1 

 

TESTS:: 

 

sage: w = Word('0011001') 

sage: w.longest_backward_extension(4, 23) 

Traceback (most recent call last): 

... 

ValueError: x and y must be valid positions in self 

sage: w.longest_backward_extension(-9, 4) 

Traceback (most recent call last): 

... 

ValueError: x and y must be valid positions in self 

""" 

length = self.length() 

if not (-length <= x < length and -length <= y < length): 

raise ValueError("x and y must be valid positions in self") 

if x < 0: 

x = x + length 

if y < 0: 

y = y + length 

l = 0 

while x >= 0 and y >= 0 and self[x] == self[y]: 

l += 1 

x -= 1 

y -= 1 

return l 

 

def longest_common_suffix(self, other): 

r""" 

Return the longest common suffix of ``self`` and ``other``. 

 

EXAMPLES:: 

 

sage: w = Word('112345678') 

sage: u = Word('1115678') 

sage: w.longest_common_suffix(u) 

word: 5678 

sage: u.longest_common_suffix(u) 

word: 1115678 

sage: u.longest_common_suffix(w) 

word: 5678 

sage: w.longest_common_suffix(w) 

word: 112345678 

sage: y = Word('549332345') 

sage: w.longest_common_suffix(y) 

word: 

 

TESTS: 

 

With the empty word:: 

 

sage: w.longest_common_suffix(Word()) 

word: 

sage: Word().longest_common_suffix(w) 

word: 

sage: Word().longest_common_suffix(Word()) 

word: 

 

With an infinite word:: 

 

sage: t=words.ThueMorseWord('ab') 

sage: w.longest_common_suffix(t) 

Traceback (most recent call last): 

... 

TypeError: other must be a finite word 

""" 

if not isinstance(other, FiniteWord_class): 

raise TypeError("other must be a finite word") 

 

if self.is_empty(): 

return self 

if other.is_empty(): 

return other 

 

iter = enumerate(zip(reversed(self), reversed(other))) 

i,(b,c) = next(iter) 

if b != c: 

#In this case, return the empty word 

return self[:0] 

 

for i,(b,c) in iter: 

if b != c: 

return self[-i:] 

else: 

return self[-i-1:] 

 

def is_palindrome(self, f=None): 

r""" 

Return ``True`` if ``self`` is a palindrome (or a ``f``-palindrome), and 

``False`` otherwise. 

 

Let `f : \Sigma \rightarrow \Sigma` be an involution that extends 

to a morphism on `\Sigma^*`. We say that `w\in\Sigma^*` is a 

*`f`-palindrome* if `w=f(\tilde{w})` [1]. Also called 

*`f`-pseudo-palindrome* [2]. 

 

INPUT: 

 

- ``f`` -- involution (default: ``None``) on the alphabet of ``self``. 

It must be callable on letters as well as words (e.g. 

:class:`~sage.combinat.words.morphism.WordMorphism`). The 

default value corresponds to usual palindromes, i.e., ``f`` 

equal to the identity. 

 

EXAMPLES:: 

 

sage: Word('esope reste ici et se repose').is_palindrome() 

False 

sage: Word('esoperesteicietserepose').is_palindrome() 

True 

sage: Word('I saw I was I').is_palindrome() 

True 

sage: Word('abbcbba').is_palindrome() 

True 

sage: Word('abcbdba').is_palindrome() 

False 

 

Some `f`-palindromes:: 

 

sage: f = WordMorphism('a->b,b->a') 

sage: Word('aababb').is_palindrome(f) 

True 

 

:: 

 

sage: f = WordMorphism('a->b,b->a,c->c') 

sage: Word('abacbacbab').is_palindrome(f) 

True 

 

:: 

 

sage: f = WordMorphism({'a':'b','b':'a'}) 

sage: Word('aababb').is_palindrome(f) 

True 

 

:: 

 

sage: f = WordMorphism({0:[1],1:[0]}) 

sage: w = words.ThueMorseWord()[:8]; w 

word: 01101001 

sage: w.is_palindrome(f) 

True 

 

The word must be in the domain of the involution:: 

 

sage: f = WordMorphism('a->a') 

sage: Word('aababb').is_palindrome(f) 

Traceback (most recent call last): 

... 

KeyError: 'b' 

 

TESTS: 

 

If the given involution is not an involution:: 

 

sage: f = WordMorphism('a->b,b->b') 

sage: Word('abab').is_palindrome(f) 

Traceback (most recent call last): 

... 

TypeError: self (=a->b, b->b) is not an endomorphism 

 

:: 

 

sage: Y = Word 

sage: Y().is_palindrome() 

True 

sage: Y('a').is_palindrome() 

True 

sage: Y('ab').is_palindrome() 

False 

sage: Y('aba').is_palindrome() 

True 

sage: Y('aa').is_palindrome() 

True 

sage: E = WordMorphism('a->b,b->a') 

sage: Y().is_palindrome(E) 

True 

sage: Y('a').is_palindrome(E) 

False 

sage: Y('ab').is_palindrome(E) 

True 

sage: Y('aa').is_palindrome(E) 

False 

sage: Y('aba').is_palindrome(E) 

False 

sage: Y('abab').is_palindrome(E) 

True 

 

REFERENCES: 

 

- [1] S. Labbé, Propriétés combinatoires des `f`-palindromes, 

Mémoire de maîtrise en Mathématiques, Montréal, UQAM, 2008, 

109 pages. 

- [2] V. Anne, L.Q. Zamboni, I. Zorca, Palindromes and Pseudo- 

Palindromes in Episturmian and Pseudo-Palindromic Infinite Words, 

in : S. Brlek, C. Reutenauer (Eds.), Words 2005, Publications du 

LaCIM, Vol. 36 (2005) 91--100. 

""" 

l = self.length() 

if f is None: 

return self[:l//2] == self[l//2 + l%2:].reversal() 

else: 

from sage.combinat.words.morphism import WordMorphism 

if not isinstance(f, WordMorphism): 

f = WordMorphism(f) 

if not f.is_involution(): 

raise ValueError("f must be an involution") 

return self[:l//2 + l%2] == f(self[l//2:].reversal()) 

 

def lps(self, f=None, l=None): 

r""" 

Return the longest palindromic (or ``f``-palindromic) suffix of ``self``. 

 

INPUT: 

 

- ``f`` -- involution (default: ``None``) on the alphabet of ``self``. 

It must be callable on letters as well as words (e.g. ``WordMorphism``). 

- ``l`` -- integer (default: ``None``) the length of the longest 

palindrome suffix of ````self[:-1]````, if known. 

 

OUTPUT: 

 

word -- If ``f`` is ``None``, the longest palindromic suffix of ``self``; 

otherwise, the longest ``f``-palindromic suffix of ``self``. 

 

EXAMPLES:: 

 

sage: Word('0111').lps() 

word: 111 

sage: Word('011101').lps() 

word: 101 

sage: Word('6667').lps() 

word: 7 

sage: Word('abbabaab').lps() 

word: baab 

sage: Word().lps() 

word: 

sage: f = WordMorphism('a->b,b->a') 

sage: Word('abbabaab').lps(f=f) 

word: abbabaab 

sage: w = Word('33412321') 

sage: w.lps(l=3) 

word: 12321 

sage: Y = Word 

sage: w = Y('01101001') 

sage: w.lps(l=2) 

word: 1001 

sage: w.lps() 

word: 1001 

sage: w.lps(l=None) 

word: 1001 

sage: Y().lps(l=2) 

Traceback (most recent call last): 

... 

IndexError: list index out of range 

sage: v = Word('abbabaab') 

sage: pal = v[:0] 

sage: for i in range(1, v.length()+1): 

....: pal = v[:i].lps(l=pal.length()) 

....: pal 

word: a 

word: b 

word: bb 

word: abba 

word: bab 

word: aba 

word: aa 

word: baab 

sage: f = WordMorphism('a->b,b->a') 

sage: v = Word('abbabaab') 

sage: pal = v[:0] 

sage: for i in range(1, v.length()+1): 

....: pal = v[:i].lps(f=f, l=pal.length()) 

....: pal 

word: 

word: ab 

word: 

word: ba 

word: ab 

word: baba 

word: bbabaa 

word: abbabaab 

""" 

#If the length of the lps of self[:-1] is not known: 

if l is None: 

l = self.lps_lengths(f)[-1] 

return self[len(self)-l:] 

 

#If l == w[:-1].length(), there is no shortcut 

if self.length() == l + 1: 

return self.lps(f=f) 

 

#Obtain the letter to the left (g) and to the right (d) of the 

#precedent lps of self 

g = self[-l-2] 

d = self[-1] 

 

#If the word g*d is a `f`-palindrome, the result follows 

if f is None: 

if g == d: 

return self[-l-2:] 

else: 

#Otherwise, the length of the lps of self is smallest than l+2 

return self[-l-1:].lps() 

else: 

from sage.combinat.words.morphism import WordMorphism 

f = WordMorphism(f) 

if f(g)[0] == d: 

return self[-l-2:] 

else: 

return self[-l-1:].lps(f=f) 

 

@cached_method 

def palindromic_lacunas_study(self, f=None): 

r""" 

Return interesting statistics about longest (``f``-)palindromic suffixes 

and lacunas of ``self`` (see [1] and [2]). 

 

Note that a word `w` has at most `|w| + 1` different palindromic factors 

(see [3]). For `f`-palindromes (or pseudopalidromes or theta-palindromes), 

the maximum number of `f`-palindromic factors is `|w|+1-g_f(w)`, where 

`g_f(w)` is the number of pairs `\{a, f(a)\}` such that `a` is a letter, 

`a` is not equal to `f(a)`, and `a` or `f(a)` occurs in `w`, see [4]. 

 

INPUT: 

 

- ``f`` -- involution (default: ``None``) on the alphabet of ``self``. 

It must be callable on letters as well as words (e.g. ``WordMorphism``). 

The default value corresponds to usual palindromes, i.e., 

``f`` equal to the identity. 

 

OUTPUT: 

 

- ``list`` -- list of the length of the longest palindromic 

suffix (lps) for each non-empty prefix of ``self`` 

- ``list`` -- list of all the lacunas, i.e. positions where there is no 

unioccurrent lps 

- ``set`` -- set of palindromic factors of ``self`` 

 

EXAMPLES:: 

 

sage: a,b,c = Word('abbabaabbaab').palindromic_lacunas_study() 

sage: a 

[1, 1, 2, 4, 3, 3, 2, 4, 2, 4, 6, 8] 

sage: b 

[8, 9] 

sage: c # random order 

set([word: , word: b, word: bab, word: abba, word: bb, word: aa, word: baabbaab, word: baab, word: aba, word: aabbaa, word: a]) 

 

:: 

 

sage: f = WordMorphism('a->b,b->a') 

sage: a,b,c = Word('abbabaab').palindromic_lacunas_study(f=f) 

sage: a 

[0, 2, 0, 2, 2, 4, 6, 8] 

sage: b 

[0, 2, 4] 

sage: c # random order 

set([word: , word: ba, word: baba, word: ab, word: bbabaa, word: abbabaab]) 

sage: c == set([Word(), Word('ba'), Word('baba'), Word('ab'), Word('bbabaa'), Word('abbabaab')]) 

True 

 

REFERENCES: 

 

- [1] A. Blondin-Massé, S. Brlek, S. Labbé, Palindromic lacunas 

of the Thue-Morse word, Proc. GASCOM 2008 (June 16-20 2008, 

Bibbiena, Arezzo-Italia), 53--67. 

- [2] A. Blondin-Massé, S. Brlek, A. Frosini, S. Labbé, S. Rinaldi, 

Reconstructing words from a fixed palindromic length sequence, 

Proc. TCS 2008, 5th IFIP International Conference on Theoretical 

Computer Science (September 8-10 2008, Milano, Italia), accepted. 

- [3] X. Droubay, J. Justin, G. Pirillo, Episturmian words and 

some constructions of de Luca and Rauzy, Theoret. Comput. Sci. 

255 (2001) 539--553. 

- [4] Š. Starosta, On Theta-palindromic Richness, Theoret. Comp. 

Sci. 412 (2011) 1111--1121 

""" 

#Initialize the results of computations 

palindromes = set() 

lengths_lps = [None] * self.length() 

lacunas = [] 

 

#Initialize the first lps 

pal = self[:0] 

palindromes.add(pal) 

 

#For all the non-empty prefixes of self, 

for i in range(self.length()): 

 

#Compute its longest `f`-palindromic suffix using the preceding lps (pal) 

pal = self[:i+1].lps(l=pal.length(),f=f) 

 

lengths_lps[i] = pal.length() 

 

if pal in palindromes: 

lacunas.append(i) 

else : 

palindromes.add(pal) 

 

return lengths_lps, lacunas, palindromes 

 

def lengths_lps(self, f=None): 

r""" 

Return the list of the length of the longest palindromic 

suffix (lps) for each non-empty prefix of ``self``. 

 

It corresponds to the function `G_w` defined in [1]. 

 

INPUT: 

 

- ``f`` -- involution (default: ``None``) on the alphabet of ``self``. It must 

be callable on letters as well as words (e.g. ``WordMorphism``). 

 

OUTPUT: 

 

a list -- list of the length of the longest palindromic 

suffix (lps) for each non-empty prefix of ``self`` 

 

EXAMPLES:: 

 

sage: Word().lengths_lps() 

[] 

sage: Word('a').lengths_lps() 

[1] 

sage: Word('aaa').lengths_lps() 

[1, 2, 3] 

sage: Word('abbabaabbaab').lengths_lps() 

[1, 1, 2, 4, 3, 3, 2, 4, 2, 4, 6, 8] 

 

:: 

 

sage: f = WordMorphism('a->b,b->a') 

sage: Word('abbabaabbaab').lengths_lps(f) 

[0, 2, 0, 2, 2, 4, 6, 8, 4, 6, 4, 6] 

 

:: 

 

sage: f = WordMorphism({5:[8],8:[5]}) 

sage: Word([5,8,5,5,8,8,5,5,8,8,5,8,5]).lengths_lps(f) 

[0, 2, 2, 0, 2, 4, 6, 4, 6, 8, 10, 12, 4] 

 

REFERENCES: 

 

- [1] A. Blondin-Massé, S. Brlek, A. Frosini, S. Labbé, 

S. Rinaldi, Reconstructing words from a fixed palindromic length 

sequence, Proc. TCS 2008, 5th IFIP International Conference on 

Theoretical Computer Science (September 8-10 2008, Milano, 

Italia), accepted. 

""" 

return self.palindromic_lacunas_study(f=f)[0] 

 

def lacunas(self, f=None): 

r""" 

Return the list of all the lacunas of ``self``. 

 

A *lacuna* is a position in a word where the longest (`f`-)palindromic 

suffix is not unioccurrent (see [1]). 

 

INPUT: 

 

- ``f`` -- involution (default: ``None``) on the alphabet of ``self``. It must 

be callable on letters as well as words (e.g. ``WordMorphism``). The 

default value corresponds to usual palindromes, i.e., ``f`` equal to 

the identity. 

 

OUTPUT: 

 

a list -- list of all the lacunas of self 

 

EXAMPLES:: 

 

sage: w = Word([0,1,1,2,3,4,5,1,13,3]) 

sage: w.lacunas() 

[7, 9] 

sage: words.ThueMorseWord()[:100].lacunas() 

[8, 9, 24, 25, 32, 33, 34, 35, 36, 37, 38, 39, 96, 97, 98, 99] 

sage: f = WordMorphism({0:[1],1:[0]}) 

sage: words.ThueMorseWord()[:50].lacunas(f) 

[0, 2, 4, 12, 16, 17, 18, 19, 48, 49] 

 

REFERENCES: 

 

- [1] A. Blondin-Massé, S. Brlek, S. Labbé, Palindromic lacunas 

of the Thue-Morse word, Proc. GASCOM 2008 (June 16-20 2008, 

Bibbiena, Arezzo-Italia), 53--67. 

""" 

return self.palindromic_lacunas_study(f=f)[1] 

 

def lengths_unioccurrent_lps(self, f=None): 

r""" 

Return the list of the lengths of the unioccurrent longest 

(``f``)-palindromic suffixes (lps) for each non-empty prefix of ``self.`` No 

unioccurrent lps are indicated by ``None``. 

 

It corresponds to the function `H_w` defined in [1] and [2]. 

 

INPUT: 

 

- ``f`` -- involution (default: ``None``) on the alphabet of ``self``. It must 

be callable on letters as well as words (e.g. ``WordMorphism``). The 

default value corresponds to usual palindromes, i.e., ``f`` equal to 

the identity. 

 

OUTPUT: 

 

a list -- list of the length of the unioccurrent longest palindromic 

suffix (lps) for each non-empty prefix of ``self``. 

No unioccurrent lps are indicated by ``None``. 

 

EXAMPLES:: 

 

sage: w = Word([0,1,1,2,3,4,5,1,13,3]) 

sage: w.lengths_unioccurrent_lps() 

[1, 1, 2, 1, 1, 1, 1, None, 1, None] 

sage: f = words.FibonacciWord()[:20] 

sage: f.lengths_unioccurrent_lps() == f.lengths_lps() 

True 

sage: t = words.ThueMorseWord() 

sage: t[:20].lengths_unioccurrent_lps() 

[1, 1, 2, 4, 3, 3, 2, 4, None, None, 6, 8, 10, 12, 14, 16, 6, 8, 10, 12] 

sage: f = WordMorphism({1:[0],0:[1]}) 

sage: t[:15].lengths_unioccurrent_lps(f) 

[None, 2, None, 2, None, 4, 6, 8, 4, 6, 4, 6, None, 4, 6] 

 

REFERENCES: 

 

- [1] A. Blondin-Massé, S. Brlek, S. Labbé, Palindromic lacunas of 

the Thue-Morse word, Proc. GASCOM 2008 (June 16-20 2008, Bibbiena, 

Arezzo-Italia), 53--67. 

- [2] A. Blondin-Massé, S. Brlek, A. Frosini, S. Labbé, S. Rinaldi, 

Reconstructing words from a fixed palindromic length sequence, 

Proc. TCS 2008, 5th IFIP International Conference on Theoretical 

Computer Science (September 8-10 2008, Milano, Italia), accepted. 

""" 

l = self.lengths_lps(f=f) 

for i in self.lacunas(f=f): 

l[i] = None 

return l 

 

def length_maximal_palindrome(self, j, m=None, f=None): 

r""" 

Return the length of the longest palindrome centered at position ``j``. 

 

INPUT: 

 

- ``j`` -- rational, position of the symmetry axis of the palindrome. 

Must return an integer when doubled. It is an integer when the 

center of the palindrome is a letter. 

 

- ``m`` -- integer (default: ``None``), minimal length of palindrome, if known. 

The parity of ``m`` can't be the same as the parity of ``2j``. 

 

- ``f`` -- involution (default: ``None``), on the alphabet. It must be 

callable on letters as well as words (e.g. ``WordMorphism``). 

 

OUTPUT: 

 

length of the longest ``f``-palindrome centered at position ``j`` 

 

EXAMPLES:: 

 

sage: Word('01001010').length_maximal_palindrome(3/2) 

0 

sage: Word('01101001').length_maximal_palindrome(3/2) 

4 

sage: Word('01010').length_maximal_palindrome(j=3, f='0->1,1->0') 

0 

sage: Word('01010').length_maximal_palindrome(j=2.5, f='0->1,1->0') 

4 

sage: Word('0222220').length_maximal_palindrome(3, f='0->1,1->0,2->2') 

5 

 

:: 

 

sage: w = Word('abcdcbaxyzzyx') 

sage: w.length_maximal_palindrome(3) 

7 

sage: w.length_maximal_palindrome(3, 3) 

7 

sage: w.length_maximal_palindrome(3.5) 

0 

sage: w.length_maximal_palindrome(9.5) 

6 

sage: w.length_maximal_palindrome(9.5, 2) 

6 

 

TESTS: 

 

These are wrong inputs:: 

 

sage: w.length_maximal_palindrome(9.6) 

Traceback (most recent call last): 

... 

ValueError: j must be positive, inferior to length of self 

sage: w.length_maximal_palindrome(3, 2) 

Traceback (most recent call last): 

... 

ValueError: (2*j-m-1)/2(=3/2) must be an integer, i.e., 2*j(=6) and 

m(=2) can't have the same parity 

sage: w.length_maximal_palindrome(9.5, 3) 

Traceback (most recent call last): 

... 

ValueError: (2*j-m-1)/2(=15/2) must be an integer, i.e., 2*j(=19) and 

m(=3) can't have the same parity 

 

""" 

# Ensure `f` is an involutory word morphism 

if f is not None: 

from sage.combinat.words.morphism import WordMorphism 

if not isinstance(f, WordMorphism): 

f = WordMorphism(f) 

if not f.is_involution(): 

raise ValueError("f must be an involution") 

 

# Ensure j is a valid entry 

jj = 2*j 

if not jj.is_integer() or j < 0 or j >= len(self): 

raise ValueError("j must be positive, inferior to length of self") 

jj = Integer(jj) 

 

# Initialize length of the known palindrome 

if m is None: 

m = 0 if jj % 2 == 1 else -1 

 

# Initialize the next (left) position to check 

i = (jj - m - 1) / 2 

if not i.is_integer(): 

raise ValueError("(2*j-m-1)/2(={}) must be an integer, i.e., " 

"2*j(={}) and m(={}) can't " 

"have the same parity".format(i, jj, m)) 

i = Integer(i) 

 

# Compute 

if f is None: 

while i >= 0 and jj-i < len(self) and self[i] == self[jj-i]: 

i -= 1 

else: 

while i >= 0 and jj-i < len(self) and self[i] == f(self[jj-i])[0]: 

i -= 1 

if jj == 2 * i: 

return 0 

else: 

return jj - 2*i - 1 

 

def lengths_maximal_palindromes(self, f=None): 

r""" 

Return the length of maximal palindromes centered at each position. 

 

INPUT: 

 

- ``f`` -- involution (default: ``None``) on the alphabet of ``self``. It must 

be callable on letters as well as words (e.g. ``WordMorphism``). 

 

OUTPUT: 

 

a list -- The length of the maximal palindrome (or ``f``-palindrome) 

with a given symmetry axis (letter or space between two letters). 

 

EXAMPLES:: 

 

sage: Word('01101001').lengths_maximal_palindromes() 

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

sage: Word('00000').lengths_maximal_palindromes() 

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

sage: Word('0').lengths_maximal_palindromes() 

[0, 1, 0] 

sage: Word('').lengths_maximal_palindromes() 

[0] 

sage: Word().lengths_maximal_palindromes() 

[0] 

sage: f = WordMorphism('a->b,b->a') 

sage: Word('abbabaab').lengths_maximal_palindromes(f) 

[0, 0, 2, 0, 0, 0, 2, 0, 8, 0, 2, 0, 0, 0, 2, 0, 0] 

""" 

if f is not None : 

from sage.combinat.words.morphism import WordMorphism 

if not isinstance(f, WordMorphism): 

f = WordMorphism(f) 

if not f.is_involution(): 

raise ValueError("f must be an involution") 

 

LPC = [] # lengths of the maximal palindromes centered at a position 

LPC.append(0) 

 

k = 0 # index, center of rightmost-ending `f`-palindrome encountered 

 

for j in range(1, 2 * len(self) + 1): 

if j >= k + LPC[k]: 

p = self.length_maximal_palindrome((j - 1)*0.5, -(j%2), f) 

LPC.append(p) 

if j + p > k + LPC[k]: 

k = j 

 

# If the center is included in an encountered `f`-palindrome 

else: 

# If the `f`-palindrome centered at position j is not the 

# longest proper `f`-palindromic suffix of the maximal 

# `f`-palindrome centered at k 

if LPC[k] + k - j != LPC[2*k - j]: 

LPC.append(min(LPC[k] + k - j, LPC[2*k - j])) 

 

else: 

mp = LPC[k] + k - j 

p = self.length_maximal_palindrome((j-1)*0.5, mp, f) 

LPC.append(p) 

k = j 

return LPC 

 

def lps_lengths(self, f=None): 

r""" 

Return the length of the longest palindromic suffix of each prefix. 

 

INPUT: 

 

- ``f`` -- involution (default: ``None``) on the alphabet of ``self``. It must 

be callable on letters as well as words (e.g. ``WordMorphism``). 

 

OUTPUT: 

 

a list -- The length of the longest palindromic (or ``f``-palindromic) 

suffix of each prefix of ``self``. 

 

EXAMPLES:: 

 

sage: Word('01101001').lps_lengths() 

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

sage: Word('00000').lps_lengths() 

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

sage: Word('0').lps_lengths() 

[0, 1] 

sage: Word('').lps_lengths() 

[0] 

sage: Word().lps_lengths() 

[0] 

sage: f = WordMorphism('a->b,b->a') 

sage: Word('abbabaab').lps_lengths(f) 

[0, 0, 2, 0, 2, 2, 4, 6, 8] 

""" 

LPC = self.lengths_maximal_palindromes(f) 

LPS = [] # lengths of the longest palindromic suffix of prefixes 

k = 0 

LPS.append(0) 

 

for j in range(1, 2*len(self)+1): 

if j + LPC[j] > k + LPC[k]: 

for i in range(k + LPC[k] + 1, j + LPC[j] + 1): 

if i % 2 == 0: 

LPS.append(i-j) 

k = j 

return LPS 

 

def palindromes(self, f=None): 

r""" 

Return the set of all palindromic (or ``f``-palindromic) factors of ``self``. 

 

INPUT: 

 

- ``f`` -- involution (default: ``None``) on the alphabet of ``self``. It must 

be callable on letters as well as words (e.g. ``WordMorphism``). 

 

OUTPUT: 

 

a set -- If ``f`` is ``None``, the set of all palindromic factors of ``self``; 

otherwise, the set of all ``f``-palindromic factors of ``self``. 

 

EXAMPLES:: 

 

sage: sorted(Word('01101001').palindromes()) 

[word: , word: 0, word: 00, word: 010, word: 0110, word: 1, word: 1001, word: 101, word: 11] 

sage: sorted(Word('00000').palindromes()) 

[word: , word: 0, word: 00, word: 000, word: 0000, word: 00000] 

sage: sorted(Word('0').palindromes()) 

[word: , word: 0] 

sage: sorted(Word('').palindromes()) 

[word: ] 

sage: sorted(Word().palindromes()) 

[word: ] 

sage: f = WordMorphism('a->b,b->a') 

sage: sorted(Word('abbabaab').palindromes(f)) 

[word: , word: ab, word: abbabaab, word: ba, word: baba, word: bbabaa] 

""" 

LPS = self.lps_lengths(f) 

return set(self[i-LPS[i] : i] for i in range(len(self)+1)) 

 

def palindrome_prefixes(self): 

r""" 

Return a list of all palindrome prefixes of ``self``. 

 

OUTPUT: 

 

a list -- A list of all palindrome prefixes of ``self``. 

 

EXAMPLES:: 

 

sage: w = Word('abaaba') 

sage: w.palindrome_prefixes() 

[word: , word: a, word: aba, word: abaaba] 

sage: w = Word('abbbbbbbbbb') 

sage: w.palindrome_prefixes() 

[word: , word: a] 

""" 

return list(self.palindrome_prefixes_iterator()) 

 

def defect(self, f=None): 

r""" 

Return the defect of ``self``. 

 

The *defect* of a finite word `w` is given by the difference between 

the maximum number of possible palindromic factors in a word of length 

`|w|` and the actual number of palindromic factors contained in `w`. 

It is well known that the maximum number of palindromic factors in `w` 

is `|w|+1` (see [DJP01]_). 

 

An optional involution on letters ``f`` can be given. In that case, the 

*f-palindromic defect* (or *pseudopalindromic defect*, or 

*theta-palindromic defect*) of `w` is returned. It is a 

generalization of defect to f-palindromes. More precisely, the defect is 

`D(w)=|w|+1-g_f(w)-|PAL_f(w)|`, where `PAL_f(w)` denotes the set of 

f-palindromic factors of `w` (including the empty word) and `g_f(w)` is 

the number of pairs `\{a, f(a)\}` such that `a` is a letter, `a` is not 

equal to `f(a)`, and `a` or `f(a)` occurs in `w`. In the case of usual 

palindromes (i.e., for ``f`` not given or equal to the identity), 

`g_f(w) = 0` for all `w`. See [BHNR04]_ for usual palindromes and [Sta11]_ 

for f-palindromes. 

 

INPUT: 

 

- ``f`` -- involution (default: ``None``) on the alphabet of ``self``. It must 

be callable on letters as well as words (e.g. ``WordMorphism``). The 

default value corresponds to usual palindromes, i.e., ``f`` equal to 

the identity. 

 

OUTPUT: 

 

an integer -- If ``f`` is ``None``, the palindromic defect of ``self``; 

otherwise, the ``f``-palindromic defect of ``self``. 

 

EXAMPLES:: 

 

sage: Word('ara').defect() 

0 

sage: Word('abcacba').defect() 

1 

 

It is known that Sturmian words (see [DJP01]_) have zero defect:: 

 

sage: words.FibonacciWord()[:100].defect() 

0 

 

sage: sa = WordMorphism('a->ab,b->b') 

sage: sb = WordMorphism('a->a,b->ba') 

sage: w = (sa*sb*sb*sa*sa*sa*sb).fixed_point('a') 

sage: w[:30].defect() 

0 

sage: w[110:140].defect() 

0 

 

It is even conjectured that the defect of an aperiodic word which is 

a fixed point of a primitive morphism is either `0` or infinite 

(see [BBGL08]_):: 

 

sage: w = words.ThueMorseWord() 

sage: w[:50].defect() 

12 

sage: w[:100].defect() 

16 

sage: w[:300].defect() 

52 

 

For generalized defect with an involution different from the identity, 

there is always a letter which is not a palindrome! This is the reason 

for the modification of the definition:: 

 

sage: f = WordMorphism('a->b,b->a') 

sage: Word('a').defect(f) 

0 

sage: Word('ab').defect(f) 

0 

sage: Word('aa').defect(f) 

1 

sage: Word('abbabaabbaababba').defect(f) 

3 

 

:: 

 

sage: f = WordMorphism('a->b,b->a,c->c') 

sage: Word('cabc').defect(f) 

0 

sage: Word('abcaab').defect(f) 

2 

 

Other examples:: 

 

sage: Word('000000000000').defect() 

0 

sage: Word('011010011001').defect() 

2 

sage: Word('0101001010001').defect() 

0 

sage: Word().defect() 

0 

sage: Word('abbabaabbaababba').defect() 

2 

 

REFERENCES: 

 

.. [BBGL08] \A. Blondin Massé, S. Brlek, A. Garon, and S. Labbé, 

Combinatorial properties of f -palindromes in the Thue-Morse 

sequence. Pure Math. Appl., 19(2-3):39--52, 2008. 

 

.. [BHNR04] \S. Brlek, S. Hamel, M. Nivat, C. Reutenauer, On the 

Palindromic Complexity of Infinite Words, in J. Berstel, J. 

Karhumaki, D. Perrin, Eds, Combinatorics on Words with Applications, 

International Journal of Foundation of Computer Science, Vol. 15, 

No. 2 (2004) 293--306. 

 

.. [DJP01] \X. Droubay, J. Justin, G. Pirillo, Episturmian words and some 

constructions of de Luca and Rauzy, Theoret. Comput. Sci. 255, 

(2001), no. 1--2, 539--553. 

 

.. [Sta11] \Š. Starosta, On Theta-palindromic Richness, Theoret. Comp. 

Sci. 412 (2011) 1111--1121 

""" 

g_w = 0 

if f is not None: 

from sage.combinat.words.morphism import WordMorphism 

if not isinstance(f, WordMorphism): 

f = WordMorphism(f) 

if not f.is_involution(): 

raise ValueError("f must be an involution") 

D = f.domain() 

A = set(map(D, self.letters())) 

while A: 

x = A.pop() 

if f(x) != x: # count only non f-palindromic letters 

if f(x) in A: 

A.remove(f(x)) 

g_w +=1 

 

return self.length()+1-g_w-len(self.palindromes(f=f)) 

 

def is_full(self, f=None): 

r""" 

Return ``True`` if ``self`` has defect `0`, and ``False`` otherwise. 

 

A word is *full* (or *rich*) if its defect is zero (see [1]). 

If ``f`` is given, then the ``f``-palindromic defect is used (see [2]). 

 

INPUT: 

 

- ``f`` -- involution (default: ``None``) on the alphabet of ``self``. It must 

be callable on letters as well as words (e.g. ``WordMorphism``). 

 

OUTPUT: 

 

boolean -- If ``f`` is ``None``, whether ``self`` is full; 

otherwise, whether ``self`` is full of ``f``-palindromes. 

 

EXAMPLES:: 

 

sage: words.ThueMorseWord()[:100].is_full() 

False 

sage: words.FibonacciWord()[:100].is_full() 

True 

sage: Word('000000000000000').is_full() 

True 

sage: Word('011010011001').is_full() 

False 

sage: Word('2194').is_full() 

True 

sage: Word().is_full() 

True 

 

:: 

 

sage: f = WordMorphism('a->b,b->a') 

sage: Word().is_full(f) 

True 

sage: w = Word('ab') 

sage: w.is_full() 

True 

sage: w.is_full(f) 

True 

 

:: 

 

sage: f = WordMorphism('a->b,b->a') 

sage: Word('abab').is_full(f) 

True 

sage: Word('abba').is_full(f) 

False 

 

A simple example of an infinite word full of f-palindromes:: 

 

sage: p = WordMorphism({0:'abc',1:'ab'}) 

sage: f = WordMorphism('a->b,b->a,c->c') 

sage: p(words.FibonacciWord()[:50]).is_full(f) 

True 

sage: p(words.FibonacciWord()[:150]).is_full(f) 

True 

 

REFERENCES: 

 

- [1] S. Brlek, S. Hamel, M. Nivat, C. Reutenauer, On the Palindromic 

Complexity of Infinite Words, in J. Berstel, J. Karhumaki, 

D. Perrin, Eds, Combinatorics on Words with Applications, 

International Journal of Foundation of Computer Science, Vol. 15, 

No. 2 (2004) 293--306. 

 

- [2] E. Pelantová, Š. Starosta, Infinite words rich and almost rich 

in generalized palindromes, in: G. Mauri, A. Leporati (Eds.), 

Developments in Language Theory, volume 6795 of Lecture Notes 

in Computer Science, Springer-Verlag, Berlin, Heidelberg, 2011, 

pp. 406--416 

""" 

return self.defect(f=f) == 0 

 

is_rich = is_full 

 

def palindromic_closure(self, side='right', f=None): 

r""" 

Return the shortest palindrome having ``self`` as a prefix 

(or as a suffix if ``side`` is ``'left'``). 

 

See [1]. 

 

INPUT: 

 

- ``side`` -- ``'right'`` or ``'left'`` (default: ``'right'``) the 

direction of the closure 

 

- ``f`` -- involution (default: ``None``) on the alphabet of ``self``. 

It must be callable on letters as well as words (e.g. ``WordMorphism``). 

 

OUTPUT: 

 

a word -- If ``f`` is ``None``, the right palindromic closure of ``self``; 

otherwise, the right ``f``-palindromic closure of ``self``. 

If ``side`` is ``'left'``, the left palindromic closure. 

 

EXAMPLES:: 

 

sage: Word('1233').palindromic_closure() 

word: 123321 

sage: Word('12332').palindromic_closure() 

word: 123321 

sage: Word('0110343').palindromic_closure() 

word: 01103430110 

sage: Word('0110343').palindromic_closure(side='left') 

word: 3430110343 

sage: Word('01105678').palindromic_closure(side='left') 

word: 876501105678 

sage: w = Word('abbaba') 

sage: w.palindromic_closure() 

word: abbababba 

 

:: 

 

sage: f = WordMorphism('a->b,b->a') 

sage: w.palindromic_closure(f=f) 

word: abbabaab 

sage: w.palindromic_closure(f=f, side='left') 

word: babaabbaba 

 

TESTS:: 

 

sage: f = WordMorphism('a->c,c->a') 

sage: w.palindromic_closure(f=f, side='left') 

Traceback (most recent call last): 

... 

KeyError: 'b' 

 

REFERENCES: 

 

- [1] A. de Luca, A. De Luca, Pseudopalindrome closure operators 

in free monoids, Theoret. Comput. Sci. 362 (2006) 282--300. 

""" 

if f is None: 

if side == 'right': 

l = self.lps().length() 

#return self * self[-(l+1)::-1] 

return self * self[:self.length()-l].reversal() 

elif side == 'left': 

l = self.reversal().lps().length() 

return self[:l-1:-1] * self 

else: 

raise ValueError("side must be either 'left' or 'right' (not %s) " % side) 

else: 

from sage.combinat.words.morphism import WordMorphism 

f = WordMorphism(f) 

if not f.is_involution(): 

raise ValueError("f must be an involution") 

if side == 'right': 

l = self.lps(f=f).length() 

return self * f(self[-(l+1)::-1]) 

elif side == 'left': 

l = self.reversal().lps(f=f).length() 

return f(self[:l-1:-1]) * self 

else: 

raise ValueError("side must be either 'left' or 'right' (not %s) " % side) 

 

def is_symmetric(self, f=None): 

r""" 

Return ``True`` if ``self`` is symmetric (or ``f``-symmetric), and 

``False`` otherwise. 

 

A word is *symmetric* (resp. `f`-*symmetric*) if it is the 

product of two palindromes (resp. `f`-palindromes). See [1] and [2]. 

 

INPUT: 

 

- ``f`` -- involution (default: ``None``) on the alphabet of ``self``. It must 

be callable on letters as well as words (e.g. ``WordMorphism``). 

 

EXAMPLES:: 

 

sage: Word('abbabab').is_symmetric() 

True 

sage: Word('ababa').is_symmetric() 

True 

sage: Word('aababaabba').is_symmetric() 

False 

sage: Word('aabbbaababba').is_symmetric() 

False 

sage: f = WordMorphism('a->b,b->a') 

sage: Word('aabbbaababba').is_symmetric(f) 

True 

 

REFERENCES: 

 

- [1] S. Brlek, S. Hamel, M. Nivat, C. Reutenauer, On the Palindromic 

Complexity of Infinite Words, in J. Berstel, J. Karhumaki, 

D. Perrin, Eds, Combinatorics on Words with Applications, 

International Journal of Foundation of Computer Science, Vol. 15, 

No. 2 (2004) 293--306. 

- [2] A. de Luca, A. De Luca, Pseudopalindrome closure operators 

in free monoids, Theoret. Comput. Sci. 362 (2006) 282--300. 

""" 

 

square = self*self 

return square.lps_lengths(f)[-1] >= self.length() 

 

def length_border(self): 

r""" 

Return the length of the border of ``self``. 

 

The *border* of a word is the longest word that is both a proper 

prefix and a proper suffix of ``self``. 

 

EXAMPLES:: 

 

sage: Word('121').length_border() 

1 

sage: Word('1').length_border() 

0 

sage: Word('1212').length_border() 

2 

sage: Word('111').length_border() 

2 

sage: Word().length_border() is None 

True 

""" 

if self.is_empty(): 

return None 

return self.prefix_function_table()[-1] 

 

def border(self): 

r""" 

Return the longest word that is both a proper prefix and a proper 

suffix of ``self``. 

 

EXAMPLES:: 

 

sage: Word('121212').border() 

word: 1212 

sage: Word('12321').border() 

word: 1 

sage: Word().border() is None 

True 

""" 

if self.is_empty(): 

return None 

return self[:self.length_border()] 

 

def minimal_period(self): 

r""" 

Return the period of ``self``. 

 

Let `A` be an alphabet. An integer `p\geq 1` is a *period* of a 

word `w=a_1a_2\cdots a_n` where `a_i\in A` if `a_i=a_{i+p}` for 

`i=1,\ldots,n-p`. The smallest period of `w` is called *the* 

period of `w`. See Chapter 1 of [1]. 

 

EXAMPLES:: 

 

sage: Word('aba').minimal_period() 

2 

sage: Word('abab').minimal_period() 

2 

sage: Word('ababa').minimal_period() 

2 

sage: Word('ababaa').minimal_period() 

5 

sage: Word('ababac').minimal_period() 

6 

sage: Word('aaaaaa').minimal_period() 

1 

sage: Word('a').minimal_period() 

1 

sage: Word().minimal_period() 

1 

 

REFERENCES: 

 

- [1] M. Lothaire, Algebraic Combinatorics On Words, vol. 90 of 

Encyclopedia of Mathematics and its Applications, Cambridge 

University Press, U.K., 2002. 

""" 

if self.is_empty(): 

return 1 

return self.length()-self.length_border() 

 

def order(self): 

r""" 

Return the order of ``self``. 

 

Let `p(w)` be the period of a word `w`. The positive rational number 

`|w|/p(w)` is the *order* of `w`. See Chapter 8 of [1]. 

 

OUTPUT: 

 

rational -- the order 

 

EXAMPLES:: 

 

sage: Word('abaaba').order() 

2 

sage: Word('ababaaba').order() 

8/5 

sage: Word('a').order() 

1 

sage: Word('aa').order() 

2 

sage: Word().order() 

0 

 

REFERENCES: 

 

- [1] M. Lothaire, Algebraic Combinatorics On Words, vol. 90 of 

Encyclopedia of Mathematics and its Applications, Cambridge 

University Press, U.K., 2002. 

""" 

from sage.rings.rational import Rational 

return Rational((self.length(),self.minimal_period())) 

 

def critical_exponent(self): 

r""" 

Return the critical exponent of ``self``. 

 

The *critical exponent* of a word is the supremum of the order of 

all its (finite) factors. See [1]. 

 

.. note:: 

 

The implementation here uses the suffix tree to enumerate all the 

factors. It should be improved. 

 

EXAMPLES:: 

 

sage: Word('aaba').critical_exponent() 

2 

sage: Word('aabaa').critical_exponent() 

2 

sage: Word('aabaaba').critical_exponent() 

7/3 

sage: Word('ab').critical_exponent() 

1 

sage: Word('aba').critical_exponent() 

3/2 

sage: words.ThueMorseWord()[:20].critical_exponent() 

2 

 

REFERENCES: 

 

.. [Dejean] \F. Dejean. Sur un théorème de Thue. J. Combinatorial Theory 

Ser. A 13:90--99, 1972. 

""" 

return max(map(FiniteWord_class.order, self.factor_iterator())) 

 

def is_overlap(self): 

r""" 

Return ``True`` if ``self`` is an overlap, and ``False`` otherwise. 

 

EXAMPLES:: 

 

sage: Word('12121').is_overlap() 

True 

sage: Word('123').is_overlap() 

False 

sage: Word('1231').is_overlap() 

False 

sage: Word('123123').is_overlap() 

False 

sage: Word('1231231').is_overlap() 

True 

sage: Word().is_overlap() 

False 

""" 

if self.length() == 0: 

return False 

return self.length_border() > self.length()//2 

 

def primitive_length(self): 

r""" 

Return the length of the primitive of ``self``. 

 

EXAMPLES:: 

 

sage: Word('1231').primitive_length() 

4 

sage: Word('121212').primitive_length() 

2 

""" 

l = lu = self.length() 

if l == 0: 

return 0 

p = self.prefix_function_table() 

while l > 0: 

l = p[l-1] 

if lu % (lu - l) == 0: 

return lu - l 

 

def is_primitive(self): 

r""" 

Return ``True`` if ``self`` is primitive, and ``False`` otherwise. 

 

A finite word `w` is *primitive* if it is not a positive integer 

power of a shorter word. 

 

EXAMPLES:: 

 

sage: Word('1231').is_primitive() 

True 

sage: Word('111').is_primitive() 

False 

""" 

return self.length() == self.primitive_length() 

 

def primitive(self): 

r""" 

Return the primitive of ``self``. 

 

EXAMPLES:: 

 

sage: Word('12312').primitive() 

word: 12312 

sage: Word('121212').primitive() 

word: 12 

""" 

return self[:self.primitive_length()] 

 

def exponent(self): 

r""" 

Return the exponent of ``self``. 

 

OUTPUT: 

 

integer -- the exponent 

 

EXAMPLES:: 

 

sage: Word('1231').exponent() 

1 

sage: Word('121212').exponent() 

3 

sage: Word().exponent() 

0 

""" 

if self.length() == 0: 

return 0 

return self.length() // self.primitive_length() 

 

def has_period(self, p): 

r""" 

Return ``True`` if ``self`` has the period ``p``, 

``False`` otherwise. 

 

.. NOTE:: 

 

By convention, integers greater than the length 

of ``self`` are periods of ``self``. 

 

INPUT: 

 

- ``p`` -- an integer to check if it is a period 

of ``self``. 

 

EXAMPLES:: 

 

sage: w = Word('ababa') 

sage: w.has_period(2) 

True 

sage: w.has_period(3) 

False 

sage: w.has_period(4) 

True 

sage: w.has_period(-1) 

False 

sage: w.has_period(5) 

True 

sage: w.has_period(6) 

True 

""" 

if p < 0: 

return False 

elif p >= len(self): 

return True 

else: 

for i in range(len(self) - p): 

if self[i] != self[i + p]: 

return False 

return True 

 

def periods(self, divide_length=False): 

r""" 

Return a list containing the periods of ``self`` 

between `1` and `n - 1`, where `n` is the length 

of ``self``. 

 

INPUT: 

 

- ``divide_length`` -- boolean (default: ``False``). 

When set to ``True``, then only periods that divide 

the length of ``self`` are considered. 

 

OUTPUT: 

 

a list of positive integers 

 

EXAMPLES:: 

 

sage: w = Word('ababab') 

sage: w.periods() 

[2, 4] 

sage: w.periods(divide_length=True) 

[2] 

sage: w = Word('ababa') 

sage: w.periods() 

[2, 4] 

sage: w.periods(divide_length=True) 

[] 

""" 

n = len(self) 

if divide_length: 

possible = (i for i in range(1,n) if n % i == 0) 

else: 

possible = range(1, n) 

return [x for x in possible if self.has_period(x)] 

 

def longest_common_subword(self, other): 

r""" 

Return a longest subword of ``self`` and ``other``. 

 

A subword of a word is a subset of the word's letters, read in the 

order in which they appear in the word. 

 

For more information, see 

:wikipedia:`Longest_common_subsequence_problem`. 

 

INPUT: 

 

- ``other`` -- a word 

 

ALGORITHM: 

 

For any indices `i,j`, we compute the longest common subword ``lcs[i,j]`` of 

``self[:i]`` and ``other[:j]``. This can be easily obtained as the longest 

of 

 

- ``lcs[i-1,j]`` 

 

- ``lcs[i,j-1]`` 

 

- ``lcs[i-1,j-1]+self[i]`` if ``self[i]==other[j]`` 

 

EXAMPLES:: 

 

sage: v1 = Word("abc") 

sage: v2 = Word("ace") 

sage: v1.longest_common_subword(v2) 

word: ac 

 

sage: w1 = Word("1010101010101010101010101010101010101010") 

sage: w2 = Word("0011001100110011001100110011001100110011") 

sage: w1.longest_common_subword(w2) 

word: 00110011001100110011010101010 

 

TESTS:: 

 

sage: Word().longest_common_subword(Word()) 

word: 

 

.. SEEALSO:: 

 

:meth:`is_subword_of` 

""" 

from sage.combinat.words.word import Word 

if len(self) == 0 or len(other) == 0: 

return Word() 

 

w2 = list(other) 

 

# In order to avoid storing lcs[i,j] for each pair i,j of indices, we 

# only store the lcs[i,j] for two consecutive values of i. At any step 

# of the algorithm, lcs[i,j] is stored at lcs[0][j] and lcs[i-1,j] is 

# stored at lcs[1][j] 

 

# The weird +1 that follows exists to make sure that lcs[i,-1] returns 

# the empty word. 

lcs = [[[] for i in range(len(w2)+1)] for j in range(2)] 

 

for i,l1 in enumerate(self): 

for j,l2 in enumerate(other): 

lcs[0][j] = max(lcs[0][j-1], lcs[1][j], 

lcs[1][j-1] + ([l1] if l1==l2 else []),key=len) 

 

# Maintaining the meaning of lcs for the next loop 

lcs.pop(1) 

lcs.insert(0,[[] for i in range(len(w2)+1)]) 

 

return Word(lcs[1][-2]) 

 

def is_subword_of(self, other): 

r""" 

Return ``True`` is ``self`` is a subword of ``other``, and ``False`` otherwise. 

 

EXAMPLES:: 

 

sage: Word().is_subword_of(Word('123')) 

True 

sage: Word('123').is_subword_of(Word('3211333213233321')) 

True 

sage: Word('321').is_subword_of(Word('11122212112122133111222332')) 

False 

 

.. SEEALSO:: 

 

:meth:`longest_common_subword` 

 

""" 

its = iter(self) 

try: 

s = next(its) 

for e in other: 

if s == e: 

s = next(its) 

else: 

return False 

except StopIteration: 

return True 

 

def is_lyndon(self): 

r""" 

Return ``True`` if ``self`` is a Lyndon word, and ``False`` 

otherwise. 

 

A *Lyndon word* is a non-empty word that is lexicographically 

smaller than each of its proper suffixes (for the given order 

on its alphabet). That is, `w` is a Lyndon word if `w` is non-empty 

and for each factorization `w = uv` (with `u`, `v` both non-empty), 

we have `w < v`. 

 

Equivalently, `w` is a Lyndon word iff `w` is a non-empty word that is 

lexicographically smaller than each of its proper conjugates for the 

given order on its alphabet. 

 

See for instance [1]. 

 

EXAMPLES:: 

 

sage: Word('123132133').is_lyndon() 

True 

sage: Word().is_lyndon() 

False 

sage: Word('122112').is_lyndon() 

False 

 

TESTS: 

 

A sanity check: ``LyndonWords`` generates Lyndon words, so we 

filter all words of length `n<10` on the alphabet [1,2,3] for 

Lyndon words, and compare with the ``LyndonWords`` generator:: 

 

sage: for n in range(1,10): 

....: lw1 = [w for w in Words([1,2,3], n) if w.is_lyndon()] 

....: lw2 = LyndonWords(3,n) 

....: if set(lw1) != set(lw2): print(False) 

 

Filter all words of length 8 on the alphabet [c,a,b] for Lyndon 

words, and compare with the :class:`LyndonWords` generator after 

mapping [a,b,c] to [2,3,1]:: 

 

sage: lw = [w for w in Words('cab', 8) if w.is_lyndon()] 

sage: phi = WordMorphism({'a':2,'b':3,'c':1}) 

sage: set(map(phi, lw)) == set(LyndonWords(3,8)) 

True 

 

REFERENCES: 

 

- [1] M. Lothaire, Combinatorics On Words, vol. 17 of Encyclopedia 

of Mathematics and its Applications, Addison-Wesley, Reading, 

Massachusetts, 1983. 

 

""" 

if self.is_empty(): 

return False 

key = self.parent().sortkey_letters 

n = self.length() 

i, j = 0, 1 

while j < n: 

ki = key(self[i]) 

kj = key(self[j]) 

if ki == kj: 

# increment i and j 

i += 1 

j += 1 

elif ki < kj: 

# reset i, increment j 

i = 0 

j += 1 

else: 

# we found the first word in the lyndon factorization; 

return False 

else: 

return i == 0 

 

def lyndon_factorization(self): 

r""" 

Return the Lyndon factorization of ``self``. 

 

The *Lyndon factorization* of a finite word `w` is the unique 

factorization of `w` as a non-increasing product of Lyndon words, 

i.e., `w = l_1\cdots l_n` where each `l_i` is a Lyndon word and 

`l_1\geq \cdots \geq l_n`. See for instance [1]. 

 

OUTPUT: 

 

the list `[l_1, \ldots, l_n]` of factors obtained 

 

EXAMPLES:: 

 

sage: Word('010010010001000').lyndon_factorization() 

(01, 001, 001, 0001, 0, 0, 0) 

sage: Words('10')('010010010001000').lyndon_factorization() 

(0, 10010010001000) 

sage: Word('abbababbaababba').lyndon_factorization() 

(abb, ababb, aababb, a) 

sage: Words('ba')('abbababbaababba').lyndon_factorization() 

(a, bbababbaaba, bba) 

sage: Word([1,2,1,3,1,2,1]).lyndon_factorization() 

(1213, 12, 1) 

 

TESTS:: 

 

sage: Words('01')('').lyndon_factorization() 

() 

sage: Word('01').lyndon_factorization() 

(01) 

sage: Words('10')('01').lyndon_factorization() 

(0, 1) 

sage: lynfac = Word('abbababbaababba').lyndon_factorization() 

sage: [x.is_lyndon() for x in lynfac] 

[True, True, True, True] 

sage: lynfac = Words('ba')('abbababbaababba').lyndon_factorization() 

sage: [x.is_lyndon() for x in lynfac] 

[True, True, True] 

sage: w = words.ThueMorseWord()[:1000] 

sage: w == prod(w.lyndon_factorization()) 

True 

 

REFERENCES: 

 

- [1] J.-P. Duval, Factorizing words over an ordered alphabet, 

J. Algorithms 4 (1983) 363--381. 

 

- [2] G. Melancon, Factorizing infinite words using Maple, 

MapleTech journal, vol. 4, no. 1, 1997, pp. 34-42. 

 

""" 

key = self.parent().sortkey_letters 

# We compute the indexes of the factorization. 

n = self.length() 

k = -1 

F = [0] 

while k < n-1: 

i = k+1 

j = k+2 

while j < n: 

ki = key(self[i]) 

kj = key(self[j]) 

if ki < kj: 

i = k+1 

j += 1 

elif ki == kj: 

i += 1 

j += 1 

else: 

break 

while k < i: 

F.append(k + j - i + 1) 

k = k + j - i 

return Factorization([self[F[i]:F[i+1]] for i in range(len(F)-1)]) 

 

def inversions(self): 

r""" 

Return a list of the inversions of ``self``. An inversion is a pair 

`(i,j)` of non-negative integers `i < j` such that ``self[i] > self[j]``. 

 

EXAMPLES:: 

 

sage: Word([1,2,3,2,2,1]).inversions() 

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

sage: Words([3,2,1])([1,2,3,2,2,1]).inversions() 

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

sage: Word('abbaba').inversions() 

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

sage: Words('ba')('abbaba').inversions() 

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

""" 

inversion_list = [] 

cmp_key = self._parent.sortkey_letters 

for (i1, letter1) in enumerate(self): 

k1 = cmp_key(letter1) 

for (i2, letter2) in enumerate(self[i1 + 1:]): 

k2 = cmp_key(letter2) 

if k1 > k2: 

inversion_list.append([i1, i1 + i2 + 1]) 

return inversion_list 

 

# TODO: This function should be defined for words of integers, but it 

# naturally is defined over an alphabet with a rank function.... 

def degree(self, weights=None): 

r""" 

Return the weighted degree of ``self``, where the weighted degree of 

each letter in the ordered alphabet is given by ``weights``, which 

defaults to ``[1, 2, 3, ...]``. 

 

INPUT: 

 

- ``weights`` -- a list or a tuple, or a dictionary keyed by the 

letters occurring in ``self``. 

 

EXAMPLES:: 

 

sage: Word([1,2,3]).degree() 

6 

sage: Word([3,2,1]).degree() 

6 

sage: Words("ab")("abba").degree() 

6 

sage: Words("ab")("abba").degree([0,2]) 

4 

sage: Words("ab")("abba").degree([-1,-1]) 

-4 

sage: Words("ab")("aabba").degree([1,1]) 

5 

sage: Words([1,2,4])([1,2,4]).degree() 

6 

sage: Word([1,2,4]).degree() 

7 

sage: Word("aabba").degree({'a':1,'b':2}) 

7 

sage: Word([0,1,0]).degree({0:17,1:0}) 

34 

""" 

if isinstance(weights, dict): 

deg = 0 

for a in self: 

deg += weights[a] 

return deg 

 

if hasattr(self._parent._alphabet, "rank"): 

rank_fcn = self._parent._alphabet.rank 

deg = 0 

if weights is None: 

rank = {} 

for a in self: 

if a not in rank: 

rank[a] = rank_fcn(a) 

deg += rank[a]+1 

elif isinstance(weights, (list,tuple)): 

rank = {} 

for a in self: 

if a not in rank: 

rank[a] = rank_fcn(a) 

deg += weights[rank[a]] 

return deg 

 

if all(x in ZZ for x in self): 

return sum(self) 

 

raise TypeError("degree is not defined for your word") 

 

def deg_lex_less(self, other, weights=None): 

r""" 

Return ``True`` if ``self`` is degree lexicographically less than ``other``, 

and ``False`` otherwise. The weight of each letter in the ordered 

alphabet is given by ``weights``, which defaults to ``[1, 2, 3, ...]``. 

 

EXAMPLES:: 

 

sage: Word([1,2,3]).deg_lex_less(Word([1,3,2])) 

True 

sage: Word([3,2,1]).deg_lex_less(Word([1,2,3])) 

False 

sage: W = Words(range(5)) 

sage: W([1,2,4]).deg_lex_less(W([1,3,2])) 

False 

sage: Word("abba").deg_lex_less(Word("abbb"), dict(a=1,b=2)) 

True 

sage: Word("abba").deg_lex_less(Word("baba"), dict(a=1,b=2)) 

True 

sage: Word("abba").deg_lex_less(Word("aaba"), dict(a=1,b=2)) 

False 

sage: Word("abba").deg_lex_less(Word("aaba"), dict(a=1,b=0)) 

True 

""" 

deg_self = self.degree(weights) 

deg_other = other.degree(weights) 

if deg_self != deg_other: 

return deg_self < deg_other 

return self.lex_less(other) 

 

def inv_lex_less(self, other): 

r""" 

Return ``True`` if ``self`` is inverse lexicographically less than ``other``. 

 

EXAMPLES:: 

 

sage: Word([1,2,4]).inv_lex_less(Word([1,3,2])) 

False 

sage: Word([3,2,1]).inv_lex_less(Word([1,2,3])) 

True 

""" 

if self.length() != len(other): 

return self.length() < len(other) 

return self.reversal() < other.reversal() 

 

def deg_inv_lex_less(self, other, weights=None): 

r""" 

Return ``True`` if the word ``self`` is degree inverse lexicographically 

less than ``other``. 

 

EXAMPLES:: 

 

sage: Word([1,2,4]).deg_inv_lex_less(Word([1,3,2])) 

False 

sage: Word([3,2,1]).deg_inv_lex_less(Word([1,2,3])) 

True 

""" 

d1 = self.degree(weights) 

d2 = other.degree(weights) 

if d1 != d2: 

return d1 < d2 

return self.inv_lex_less(other) 

 

def rev_lex_less(self, other): 

r""" 

Return ``True`` if the word ``self`` is reverse 

lexicographically less than ``other``. 

 

EXAMPLES:: 

 

sage: Word([1,2,4]).rev_lex_less(Word([1,3,2])) 

True 

sage: Word([3,2,1]).rev_lex_less(Word([1,2,3])) 

False 

""" 

if self.length() != len(other): 

return self.length() > len(other) 

return self.reversal() > other.reversal() 

 

def deg_rev_lex_less(self, other, weights=None): 

r""" 

Return ``True`` if ``self`` is degree reverse 

lexicographically less than ``other``. 

 

EXAMPLES:: 

 

sage: Word([3,2,1]).deg_rev_lex_less(Word([1,2,3])) 

False 

sage: Word([1,2,4]).deg_rev_lex_less(Word([1,3,2])) 

False 

sage: Word([1,2,3]).deg_rev_lex_less(Word([1,2,4])) 

True 

""" 

d1 = self.degree(weights) 

d2 = other.degree(weights) 

if d1 != d2: 

return d1 < d2 

return self.rev_lex_less(other) 

 

@cached_method 

def last_position_dict(self): 

r""" 

Return a dictionary that contains the last position of each letter 

in ``self``. 

 

EXAMPLES:: 

 

sage: Word('1231232').last_position_dict() 

{'1': 3, '2': 6, '3': 5} 

""" 

d = {} 

for (i, letter) in enumerate(self): 

d[letter] = i 

return d 

 

def _pos_in(self, other, p): 

r""" 

Return the position of the first occurrence of ``self`` starting at 

position ``p`` in ``other``. 

 

EXAMPLES:: 

 

sage: Word('12')._pos_in(Word('131231'), 2) 

2 

sage: Word('12')._pos_in(Word('131231'), 3) is None 

True 

sage: Word('32')._pos_in(Word('131231'), 0) is None 

True 

 

The empty word occurs in a word:: 

 

sage: Word('')._pos_in(Word('123'), 0) 

0 

sage: Word('')._pos_in(Word(''), 0) 

0 

""" 

lf = self.length() 

lm = other.length() 

if lf == 0: 

return p 

elif lm == 0: 

return None 

occ = self.last_position_dict() 

suff = self.good_suffix_table() 

s = p 

while s <= lm - lf: 

for j in range(lf-1, -1, -1): 

a = other[s+j] 

if self[j] != a : 

s += max(suff[j + 1], j - occ.get(a,-1)) 

break 

else: 

return s 

return None 

 

def first_pos_in(self, other): 

r""" 

Return the position of the first occurrence of ``self`` in ``other``, 

or ``None`` if ``self`` is not a factor of ``other``. 

 

EXAMPLES:: 

 

sage: Word('12').first_pos_in(Word('131231')) 

2 

sage: Word('32').first_pos_in(Word('131231')) is None 

True 

""" 

return self._pos_in(other, 0) 

 

def find(self, sub, start=0, end=None): 

r""" 

Return the index of the first occurrence of ``sub`` in ``self``, 

such that ``sub`` is contained within ``self[start:end]``. 

Return ``-1`` on failure. 

 

INPUT: 

 

- ``sub`` -- string, list, tuple or word to search for. 

 

- ``start`` -- non-negative integer (default: ``0``) specifying 

the position from which to start the search. 

 

- ``end`` -- non-negative integer (default: ``None``) specifying 

the position at which the search must stop. If ``None``, then 

the search is performed up to the end of the string. 

 

OUTPUT: 

 

a non-negative integer or ``-1`` 

 

EXAMPLES:: 

 

sage: w = Word([0,1,0,0,1]) 

sage: w.find(Word([1,0])) 

1 

 

The ``sub`` argument can also be a tuple or a list:: 

 

sage: w.find([1,0]) 

1 

sage: w.find((1,0)) 

1 

 

Examples using ``start`` and ``end``:: 

 

sage: w.find(Word([0,1]), start=1) 

3 

sage: w.find(Word([0,1]), start=1, end=5) 

3 

sage: w.find(Word([0,1]), start=1, end=4) == -1 

True 

sage: w.find(Word([1,1])) == -1 

True 

sage: w.find("aa") 

-1 

 

Instances of ``Word_str`` handle string inputs as well:: 

 

sage: w = Word('abac') 

sage: w.find('a') 

0 

sage: w.find('ba') 

1 

 

TESTS: 

 

Check that :trac:`12804` is fixed:: 

 

sage: w = Word(iter("ababab"), length="finite") 

sage: w.find("ab") 

0 

sage: w.find("ab", start=1) 

2 

sage: w.find("aa") 

-1 

sage: w.find("abc") 

-1 

sage: w = Words('ab')(tuple('babaabaaab')) 

sage: w.find('abc') 

-1 

 

""" 

if not isinstance(sub, FiniteWord_class): 

try: 

sub = self.parent()(sub) 

except (ValueError,TypeError): 

return -1 

p = sub.first_pos_in(self[start:end]) 

return -1 if p is None else p+start 

 

def rfind(self, sub, start=0, end=None): 

r""" 

Return the index of the last occurrence of ``sub`` in ``self``, 

such that ``sub`` is contained within ``self[start:end]``. 

Return ``-1`` on failure. 

 

INPUT: 

 

- ``sub`` -- string, list, tuple or word to search for. 

 

- ``start`` -- non-negative integer (default: ``0``) specifying 

the position at which the search must stop. 

 

- ``end`` -- non-negative integer (default: ``None``) specifying 

the position from which to start the search. If ``None``, then 

the search is performed up to the end of the string. 

 

OUTPUT: 

 

a non-negative integer or ``-1`` 

 

EXAMPLES:: 

 

sage: w = Word([0,1,0,0,1]) 

sage: w.rfind(Word([0,1])) 

3 

 

The ``sub`` parameter can also be a list or a tuple:: 

 

sage: w.rfind([0,1]) 

3 

sage: w.rfind((0,1)) 

3 

 

Examples using the argument ``start`` and ``end``:: 

 

sage: w.rfind(Word([0,1]), end=4) 

0 

sage: w.rfind(Word([0,1]), end=5) 

3 

sage: w.rfind(Word([0,0]), start=2, end=5) 

2 

sage: w.rfind(Word([0,0]), start=3, end=5) 

-1 

 

Instances of ``Word_str`` handle string inputs as well:: 

 

sage: w = Word('abac') 

sage: w.rfind('a') 

2 

sage: w.rfind(Word('a')) 

2 

sage: w.rfind([0,1]) 

-1 

 

TESTS: 

 

Check that :trac:`12804` is fixed:: 

 

sage: w = Word(iter("abab"), length="finite") 

sage: w.rfind("ab") 

2 

sage: w.rfind("ab", end=3) 

0 

sage: w.rfind("aa") 

-1 

sage: w.rfind([0,0,0]) 

-1 

""" 

if not isinstance(sub, FiniteWord_class): 

try: 

sub = self.parent()(sub) 

except (ValueError,TypeError): 

return -1 

L = len(sub) 

start = max(0, int(start)) 

if end is None: 

i = len(self) - L 

else: 

i = min(end, len(self)) - L 

while i >= start: 

if self[i:i+L] == sub: return i 

i -= 1 

return -1 

 

def is_factor(self, other): 

r""" 

Return ``True`` if ``self`` is a factor of ``other``, and ``False`` otherwise. 

 

EXAMPLES:: 

 

sage: u = Word('2113') 

sage: w = Word('123121332131233121132123') 

sage: u.is_factor(w) 

True 

sage: u = Word('321') 

sage: w = Word('1231241231312312312') 

sage: u.is_factor(w) 

False 

 

The empty word is factor of another word:: 

 

sage: Word().is_factor(Word()) 

True 

sage: Word().is_factor(Word('a')) 

True 

sage: Word().is_factor(Word([1,2,3])) 

True 

sage: Word().is_factor(Word(lambda n:n, length=5)) 

True 

""" 

return self.first_pos_in(other) is not None 

 

def factor_occurrences_in(self, other): 

r""" 

Return an iterator over all occurrences (including overlapping ones) 

of ``self`` in ``other`` in their order of appearance. 

 

EXAMPLES:: 

 

sage: u = Word('121') 

sage: w = Word('121213211213') 

sage: list(u.factor_occurrences_in(w)) 

[0, 2, 8] 

""" 

if self.length() == 0: 

raise NotImplementedError("The factor must be non empty") 

p = self._pos_in(other, 0) 

while p is not None: 

yield p 

p = self._pos_in(other, p+1) 

 

def nb_factor_occurrences_in(self, other): 

r""" 

Return the number of times ``self`` appears as a factor 

in ``other``. 

 

EXAMPLES:: 

 

sage: Word().nb_factor_occurrences_in(Word('123')) 

Traceback (most recent call last): 

... 

NotImplementedError: The factor must be non empty 

sage: Word('123').nb_factor_occurrences_in(Word('112332312313112332121123')) 

4 

sage: Word('321').nb_factor_occurrences_in(Word('11233231231311233221123')) 

0 

""" 

n = 0 

for _ in self.factor_occurrences_in(other): 

n += 1 

return n 

 

def nb_subword_occurrences_in(self, other): 

r""" 

Return the number of times ``self`` appears in ``other`` as a subword. 

 

This corresponds to the notion of `binomial coefficient` of two 

finite words whose properties are presented in the chapter of 

Lothaire's book written by Sakarovitch and Simon [1]. 

 

INPUT: 

 

- ``other`` -- finite word 

 

EXAMPLES:: 

 

sage: tm = words.ThueMorseWord() 

 

sage: u = Word([0,1,0,1]) 

sage: u.nb_subword_occurrences_in(tm[:1000]) 

2604124996 

 

sage: u = Word([0,1,0,1,1,0]) 

sage: u.nb_subword_occurrences_in(tm[:100]) 

20370432 

 

.. NOTE:: 

 

This code, based on [2], actually compute the number of 

occurrences of all prefixes of ``self`` as subwords in all 

prefixes of ``other``. In particular, its complexity is 

bounded by ``len(self) * len(other)``. 

 

TESTS:: 

 

sage: Word('').nb_subword_occurrences_in(Word('')) 

1 

sage: parent(_) 

Integer Ring 

sage: v,u = Word(), Word('123') 

sage: v.nb_subword_occurrences_in(u) 

1 

sage: v,u = Word('123'), Word('1133432311132311112') 

sage: v.nb_subword_occurrences_in(u) 

11 

sage: v,u = Word('4321'), Word('1132231112233212342231112') 

sage: v.nb_subword_occurrences_in(u) 

0 

sage: v,u = Word('3'), Word('122332112321213') 

sage: v.nb_subword_occurrences_in(u) 

4 

sage: v,u = Word([]), words.ThueMorseWord()[:1000] 

sage: v.nb_subword_occurrences_in(u) 

1 

 

REFERENCES: 

 

- [1] M. Lothaire, Combinatorics on Words, Cambridge University 

Press, (1997). 

- [2] Mateescu, A., Salomaa, A., Salomaa, K. and Yu, S., A 

sharpening of the Parikh mapping. Theoret. Informatics Appl. 35 

(2001) 551-564. 

""" 

# record the position of letters in self 

pos = defaultdict(list) 

for i,a in enumerate(self): 

pos[a].append(i) 

for a in pos: 

pos[a].reverse() 

 

# compute the occurrences of all prefixes of self as subwords in other 

occ = [ZZ.zero()] * (len(self)+1) 

occ[0] = ZZ.one() 

for a in other: 

for i in pos[a]: 

occ[i+1] += occ[i] 

 

# return only the number of occurrences of self 

return occ[-1] 

 

def _return_words_list(self, fact): 

r""" 

Return the return words as a list in the order they appear in the word. 

 

INPUT: 

 

- ``fact`` -- a non-empty finite word 

 

OUTPUT: 

 

a Python list of finite words 

 

TESTS:: 

 

sage: Word('baccabccbacbca')._return_words_list(Word('b')) 

[word: bacca, word: bcc, word: bac] 

""" 

return list(self.return_words_iterator(fact)) 

 

def return_words(self, fact): 

r""" 

Return the set of return words of ``fact`` in ``self``. 

 

This is the set of all factors starting by the given factor and ending 

just before the next occurrence of this factor. See [1] and [2]. 

 

INPUT: 

 

- ``fact`` -- a non-empty finite word 

 

OUTPUT: 

 

a Python set of finite words 

 

EXAMPLES:: 

 

sage: Word('21331233213231').return_words(Word('2')) 

{word: 213, word: 21331, word: 233} 

sage: Word().return_words(Word('213')) 

set() 

sage: Word('121212').return_words(Word('1212')) 

{word: 12} 

 

:: 

 

sage: TM = words.ThueMorseWord()[:1000] 

sage: sorted(TM.return_words(Word([0]))) 

[word: 0, word: 01, word: 011] 

 

REFERENCES: 

 

- [1] F. Durand, A characterization of substitutive sequences using 

return words, Discrete Math. 179 (1998) 89-101. 

- [2] C. Holton, L.Q. Zamboni, Descendants of primitive substitutions, 

Theory Comput. Syst. 32 (1999) 133-157. 

""" 

return set(self.return_words_iterator(fact)) 

 

def complete_return_words(self, fact): 

r""" 

Return the set of complete return words of ``fact`` in ``self``. 

 

This is the set of all factors starting by the given factor and ending 

just after the next occurrence of this factor. See for instance [1]. 

 

INPUT: 

 

- ``fact`` -- a non-empty finite word 

 

OUTPUT: 

 

a Python set of finite words 

 

EXAMPLES:: 

 

sage: s = Word('21331233213231').complete_return_words(Word('2')) 

sage: sorted(s) 

[word: 2132, word: 213312, word: 2332] 

sage: Word('').complete_return_words(Word('213')) 

set() 

sage: Word('121212').complete_return_words(Word('1212')) 

{word: 121212} 

 

REFERENCES: 

 

- [1] J. Justin, L. Vuillon, Return words in Sturmian and 

episturmian words, Theor. Inform. Appl. 34 (2000) 343--356. 

""" 

return set(self.complete_return_words_iterator(fact)) 

 

def return_words_derivate(self, fact): 

r""" 

Return the word generated by mapping a letter to each occurrence of 

the return words for the given factor dropping any dangling prefix and 

suffix. See for instance [1]. 

 

EXAMPLES:: 

 

sage: Word('12131221312313122').return_words_derivate(Word('1')) 

word: 123242 

 

REFERENCES: 

 

- [1] F. Durand, A characterization of substitutive sequences using 

return words, Discrete Math. 179 (1998) 89--101. 

""" 

idx = 0 

tab = {} 

ret = [tab.setdefault(w, len(tab)) + 1 for w in self._return_words_list(fact)] 

from sage.combinat.words.word import Word 

return Word(ret) 

 

def is_quasiperiodic(self): 

r""" 

Return ``True`` if ``self`` is quasiperiodic, and ``False`` otherwise. 

 

A finite or infinite word `w` is *quasiperiodic* if it can be 

constructed by concatenations and superpositions of one of its proper 

factors `u`, which is called a *quasiperiod* of `w`. 

See for instance [1], [2], and [3]. 

 

EXAMPLES:: 

 

sage: Word('abaababaabaababaaba').is_quasiperiodic() 

True 

sage: Word('abacaba').is_quasiperiodic() 

False 

sage: Word('a').is_quasiperiodic() 

False 

sage: Word().is_quasiperiodic() 

False 

sage: Word('abaaba').is_quasiperiodic() 

True 

 

REFERENCES: 

 

- [1] A. Apostolico, A. Ehrenfeucht, Efficient detection of 

quasiperiodicities in strings, Theoret. Comput. Sci. 119 (1993) 

247--265. 

- [2] S. Marcus, Quasiperiodic infinite words, Bull. Eur. Assoc. 

Theor. Comput. Sci. 82 (2004) 170-174. 

- [3] A. Glen, F. Levé, G. Richomme, Quasiperiodic and Lyndon 

episturmian words, Preprint, 2008, :arxiv:`0805.0730`. 

""" 

l = self.length() 

if l <= 1: 

return False 

for i in range(1, l - 1): 

return_lengths = [x.length() for x in self.return_words(self[:i])] 

if return_lengths != []: 

if (max(return_lengths) <= i and self[l-i:l] == self[:i]): 

return True 

return False 

 

def quasiperiods(self): 

r""" 

Return the quasiperiods of ``self`` as a list ordered from shortest to 

longest. 

 

Let `w` be a finite or infinite word. A *quasiperiod* of `w` is a 

proper factor `u` of `w` such that the occurrences of `u` in `w` 

entirely cover `w`, i.e., every position of `w` falls within some 

occurrence of `u` in `w`. See for instance [1], [2], and [3]. 

 

EXAMPLES:: 

 

sage: Word('abaababaabaababaaba').quasiperiods() 

[word: aba, word: abaaba, word: abaababaaba] 

sage: Word('abaaba').quasiperiods() 

[word: aba] 

sage: Word('abacaba').quasiperiods() 

[] 

 

REFERENCES: 

 

- [1] A. Apostolico, A. Ehrenfeucht, Efficient detection of 

quasiperiodicities in strings, Theoret. Comput. Sci. 119 (1993) 

247--265. 

- [2] S. Marcus, Quasiperiodic infinite words, Bull. Eur. Assoc. 

Theor. Comput. Sci. 82 (2004) 170-174. 

- [3] A. Glen, F. Levé, G. Richomme, Quasiperiodic and Lyndon 

episturmian words, Preprint, 2008, :arxiv:`0805.0730`. 

""" 

l = self.length() 

if l <= 1: 

return [] 

Q = [] 

for i in range(1, l - 1): 

return_lengths = [x.length() for x in self.return_words(self[:i])] 

if return_lengths != []: 

if (max(return_lengths) <= i and self[l-i:l] == self[:i]): 

Q.append(self[:i]) 

return Q 

 

def crochemore_factorization(self): 

r""" 

Return the Crochemore factorization of ``self`` as an ordered list of 

factors. 

 

The *Crochemore factorization* or the *Lempel-Ziv decomposition* of a 

finite word `w` is the unique factorization: `(x_1, x_2, \ldots, x_n)` 

of `w` with each `x_i` satisfying either: C1. `x_i` is a letter that 

does not appear in `u = x_1\ldots x_{i-1}`; C2. `x_i` is the longest 

prefix of `v = x_i\ldots x_n` that also has an occurrence beginning 

within `u = x_1\ldots x_{i-1}`. See [1]. 

 

EXAMPLES:: 

 

sage: x = Word('abababb') 

sage: x.crochemore_factorization() 

(a, b, abab, b) 

sage: mul(x.crochemore_factorization()) == x 

True 

sage: y = Word('abaababacabba') 

sage: y.crochemore_factorization() 

(a, b, a, aba, ba, c, ab, ba) 

sage: mul(y.crochemore_factorization()) == y 

True 

sage: x = Word([0,1,0,1,0,1,1]) 

sage: x.crochemore_factorization() 

(0, 1, 0101, 1) 

sage: mul(x.crochemore_factorization()) == x 

True 

 

REFERENCES: 

 

- [1] M. Crochemore, Recherche linéaire d'un carré dans un mot, 

C. R. Acad. Sci. Paris Sér. I Math. 296 (1983) 14 781--784. 

""" 

T = self.implicit_suffix_tree() 

cuts = T.LZ_decomposition() 

c = Factorization([self[cuts[i]:cuts[i+1]] for i in range(len(cuts)-1)]) 

return c 

 

LZ_decomposition = crochemore_factorization 

 

def evaluation_dict(self): 

r""" 

Return a dictionary keyed by the letters occurring in ``self`` with 

values the number of occurrences of the letter. 

 

EXAMPLES:: 

 

sage: Word([2,1,4,2,3,4,2]).evaluation_dict() 

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

sage: Word('badbcdb').evaluation_dict() 

{'a': 1, 'b': 3, 'c': 1, 'd': 2} 

sage: Word().evaluation_dict() 

{} 

 

:: 

 

sage: f = Word('1213121').evaluation_dict() # keys appear in random order 

{'1': 4, '2': 2, '3': 1} 

 

TESTS:: 

 

sage: f = Word('1213121').evaluation_dict() 

sage: f['1'] == 4 

True 

sage: f['2'] == 2 

True 

sage: f['3'] == 1 

True 

""" 

return evaluation_dict(self) 

 

def evaluation_sparse(self): 

r""" 

Return a list representing the evaluation of ``self``. The entries of 

the list are two-element lists ``[a, n]``, where ``a`` is a letter 

occurring in ``self`` and ``n`` is the number of occurrences of ``a`` in ``self``. 

 

EXAMPLES:: 

 

sage: Word([4,4,2,5,2,1,4,1]).evaluation_sparse() 

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

sage: Word("abcaccab").evaluation_sparse() 

[('a', 3), ('c', 3), ('b', 2)] 

""" 

return self.evaluation_dict().items() 

 

def evaluation_partition(self): 

r""" 

Return the evaluation of the word w as a partition. 

 

EXAMPLES:: 

 

sage: Word("acdabda").evaluation_partition() 

[3, 2, 1, 1] 

sage: Word([2,1,4,2,3,4,2]).evaluation_partition() 

[3, 2, 1, 1] 

""" 

p = sorted(self.evaluation_dict().values(), reverse=True) 

from sage.combinat.partition import Partition 

if 0 in p: 

return Partition(p[:p.index(0)]) 

else: 

return Partition(p) 

 

def overlap_partition(self, other, delay=0, p=None, involution=None) : 

r""" 

Return the partition of the alphabet induced by the overlap of 

``self`` and ``other`` with the given ``delay``. 

 

The partition of the alphabet is given by the equivalence 

relation obtained from the symmetric, reflexive and transitive 

closure of the set of pairs of letters 

`R_{u,v,d} = \{ (u_k, v_{k-d}) : 0 \leq k < n, 0\leq k-d < m \}` 

where `u = u_0 u_1 \cdots u_{n-1}`, `v = v_0v_1\cdots v_{m-1}` are 

two words on the alphabet `A` and `d` is an integer. 

 

The equivalence relation defined by `R` is inspired from [1]. 

 

INPUT: 

 

- ``other`` -- word on the same alphabet as ``self`` 

- ``delay`` -- integer (default: ``0``) 

- ``p`` -- disjoint sets data structure (optional, default: ``None``), 

a partition of the alphabet into disjoint sets to start with. 

If ``None``, each letter start in distinct equivalence classes. 

- ``involution`` -- callable (optional, default: ``None``), an 

involution on the alphabet. If ``involution`` is not ``None``, the relation 

`R_{u,v,d} \cup R_{involution(u),involution(v),d}` is considered. 

 

OUTPUT: 

 

a disjoint set data structure 

 

EXAMPLES:: 

 

sage: W = Words(list('abc') + list(range(6))) 

sage: u = W('abc') 

sage: v = W(range(5)) 

sage: u.overlap_partition(v) 

{{0, 'a'}, {1, 'b'}, {2, 'c'}, {3}, {4}, {5}} 

sage: u.overlap_partition(v, 2) 

{{'a'}, {'b'}, {0, 'c'}, {1}, {2}, {3}, {4}, {5}} 

sage: u.overlap_partition(v, -1) 

{{0}, {1, 'a'}, {2, 'b'}, {3, 'c'}, {4}, {5}} 

 

You can re-use the same disjoint set and do more than one overlap:: 

 

sage: p = u.overlap_partition(v, 2) 

sage: p 

{{'a'}, {'b'}, {0, 'c'}, {1}, {2}, {3}, {4}, {5}} 

sage: u.overlap_partition(v, 1, p) 

{{'a'}, {0, 1, 'b', 'c'}, {2}, {3}, {4}, {5}} 

 

The function ``overlap_partition`` can be used to study equations 

on words. For example, if a word `w` overlaps itself with delay `d`, then 

`d` is a period of `w`:: 

 

sage: W = Words(range(20)) 

sage: w = W(range(14)); w 

word: 0,1,2,3,4,5,6,7,8,9,10,11,12,13 

sage: d = 5 

sage: p = w.overlap_partition(w, d) 

sage: m = WordMorphism(p.element_to_root_dict()) 

sage: w2 = m(w); w2 

word: 56789567895678 

sage: w2.minimal_period() == d 

True 

 

If a word is equal to its reversal, then it is a palindrome:: 

 

sage: W = Words(range(20)) 

sage: w = W(range(17)); w 

word: 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 

sage: p = w.overlap_partition(w.reversal(), 0) 

sage: m = WordMorphism(p.element_to_root_dict()) 

sage: w2 = m(w); w2 

word: 01234567876543210 

sage: w2.parent() 

Finite words over {0, 1, 2, 3, 4, 5, 6, 7, 8, 17, 18, 19} 

sage: w2.is_palindrome() 

True 

 

If the reversal of a word `w` is factor of its square `w^2`, then 

`w` is symmetric, i.e. the product of two palindromes:: 

 

sage: W = Words(range(10)) 

sage: w = W(range(10)); w 

word: 0123456789 

sage: p = (w*w).overlap_partition(w.reversal(), 4) 

sage: m = WordMorphism(p.element_to_root_dict()) 

sage: w2 = m(w); w2 

word: 0110456654 

sage: w2.is_symmetric() 

True 

 

If the image of the reversal of a word `w` under an involution `f` 

is factor of its square `w^2`, then `w` is `f`-symmetric:: 

 

sage: W = Words([-11,-9,..,11]) 

sage: w = W([1,3,..,11]) 

sage: w 

word: 1,3,5,7,9,11 

sage: inv = lambda x:-x 

sage: f = WordMorphism(dict( (a, inv(a)) for a in W.alphabet())) 

sage: p = (w*w).overlap_partition(f(w).reversal(), 2, involution=f) 

sage: m = WordMorphism(p.element_to_root_dict()) 

sage: m(w) 

word: 1,-1,5,7,-7,-5 

sage: m(w).is_symmetric(f) 

True 

 

TESTS:: 

 

sage: W = Words('abcdef') 

sage: w = W('abc') 

sage: y = W('def') 

sage: w.overlap_partition(y, -3) 

{{'a'}, {'b'}, {'c'}, {'d'}, {'e'}, {'f'}} 

sage: w.overlap_partition(y, -2) 

{{'a', 'f'}, {'b'}, {'c'}, {'d'}, {'e'}} 

sage: w.overlap_partition(y, -1) 

{{'a', 'e'}, {'b', 'f'}, {'c'}, {'d'}} 

sage: w.overlap_partition(y, 0) 

{{'a', 'd'}, {'b', 'e'}, {'c', 'f'}} 

sage: w.overlap_partition(y, 1) 

{{'a'}, {'b', 'd'}, {'c', 'e'}, {'f'}} 

sage: w.overlap_partition(y, 2) 

{{'a'}, {'b'}, {'c', 'd'}, {'e'}, {'f'}} 

sage: w.overlap_partition(y, 3) 

{{'a'}, {'b'}, {'c'}, {'d'}, {'e'}, {'f'}} 

sage: w.overlap_partition(y, 4) 

{{'a'}, {'b'}, {'c'}, {'d'}, {'e'}, {'f'}} 

 

:: 

 

sage: W = Words(range(2)) 

sage: w = W([0,1,0,1,0,1]); w 

word: 010101 

sage: w.overlap_partition(w, 0) 

{{0}, {1}} 

sage: w.overlap_partition(w, 1) 

{{0, 1}} 

 

:: 

 

sage: empty = Word() 

sage: empty.overlap_partition(empty, 'yo') 

Traceback (most recent call last): 

... 

TypeError: delay (=yo) must be an integer 

sage: empty.overlap_partition(empty,2,'yo') 

Traceback (most recent call last): 

... 

TypeError: p(=yo) is not a DisjointSet 

 

The ``involution`` input can be any callable:: 

 

sage: w = Words([-5,..,5])([-5..5]) 

sage: inv = lambda x:-x 

sage: w.overlap_partition(w, 2, involution=inv) 

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

 

REFERENCES: 

 

- [1] S. Labbé, Propriétés combinatoires des `f`-palindromes, 

Mémoire de maîtrise en Mathématiques, Montréal, UQAM, 2008, 

109 pages. 

""" 

if not isinstance(delay, (int, Integer)): 

raise TypeError("delay (=%s) must be an integer"%delay) 

elif delay < 0: 

return other.overlap_partition(self, -delay, p) 

 

from sage.sets.disjoint_set import DisjointSet_class 

if p is None: 

if self.parent().alphabet().cardinality() is Infinity: 

raise ValueError("The alphabet of the parent must be finite") 

from sage.sets.disjoint_set import DisjointSet 

p = DisjointSet(self.parent().alphabet()) 

elif not isinstance(p, DisjointSet_class): 

raise TypeError("p(=%s) is not a DisjointSet" % p) 

 

#Join the classes of each pair of letters that are one above the other 

from sage.combinat.words.morphism import WordMorphism 

S = zip(islice(self, delay, None), other) 

if involution is None: 

for (a,b) in S: 

p.union(a, b) 

elif isinstance(involution, WordMorphism): 

for (a,b) in S: 

p.union(a, b) 

# take the first letter of the word 

p.union(involution(a)[0], involution(b)[0]) 

elif callable(involution): 

for (a,b) in S: 

p.union(a, b) 

p.union(involution(a), involution(b)) 

else: 

raise TypeError("involution (=%s) must be callable"%involution) 

return p 

 

# TODO: requires a parent with a sortkey_letters method 

def standard_permutation(self): 

r""" 

Return the standard permutation of the word 

``self`` on the ordered alphabet. It is defined as 

the permutation with exactly the same number of 

inversions as w. Equivalently, it is the permutation 

of minimal length whose inverse sorts ``self``. 

 

EXAMPLES:: 

 

sage: w = Word([1,2,3,2,2,1]); w 

word: 123221 

sage: p = w.standard_permutation(); p 

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

sage: v = Word(p.inverse().action(w)); v 

word: 112223 

sage: filter(lambda q: q.length() <= p.length() and \ 

....: q.inverse().action(w) == list(v), \ 

....: Permutations(w.length()) ) 

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

 

:: 

 

sage: w = Words([1,2,3])([1,2,3,2,2,1,2,1]); w 

word: 12322121 

sage: p = w.standard_permutation(); p 

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

sage: Word(p.inverse().action(w)) 

word: 11122223 

 

:: 

 

sage: w = Words([3,2,1])([1,2,3,2,2,1,2,1]); w 

word: 12322121 

sage: p = w.standard_permutation(); p 

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

sage: Word(p.inverse().action(w)) 

word: 32222111 

 

:: 

 

sage: w = Words('ab')('abbaba'); w 

word: abbaba 

sage: p = w.standard_permutation(); p 

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

sage: Word(p.inverse().action(w)) 

word: aaabbb 

 

:: 

 

sage: w = Words('ba')('abbaba'); w 

word: abbaba 

sage: p = w.standard_permutation(); p 

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

sage: Word(p.inverse().action(w)) 

word: bbbaaa 

""" 

from sage.combinat.permutation import to_standard 

return to_standard(self, key=self.parent().sortkey_letters) 

 

def _s(self, i): 

r""" 

Implement Lascoux and Schützenberger `s_i` operator, swap the 

number of ``i`` and ``i+1`` in a word. 

 

EXAMPLES:: 

 

sage: w = Word([1,1,2,1,2,2,1,3,1,2]) 

sage: w._s(1) 

word: 1221221312 

 

TESTS:: 

 

sage: w = Word([]) 

sage: w._s(1) 

word: 

sage: w = Words(3)([2,1,2]) 

sage: w._s(1).parent() 

Finite words over {1, 2, 3} 

""" 

unpaired_i = [] # positions of unpaired is 

unpaired_ip = [] # positions of unpaired i+1s 

for p,x in enumerate(self): 

if x == i: 

if unpaired_ip: 

unpaired_ip.pop() 

else: 

unpaired_i.append(p) 

elif x == i+1: 

unpaired_ip.append(p) 

 

unpaired = unpaired_i + unpaired_ip 

 

out = list(self) 

 

# replace the unpaired subword i^a (i+1)^b 

# with i^b (i+1)^a 

 

for j,p in enumerate(unpaired): 

if j < len(unpaired_ip): 

out[p] = i 

else: 

out[p] = i+1 

return self.parent()(out, check=False) 

 

def _to_partition_content(self): 

r""" 

Return the conversion of ``self`` to a word with partition content using 

the `s_i` operators of Lascoux and Schützenberger. 

 

EXAMPLES:: 

 

sage: w = Word([1,3,2,1,2,3,4,6,4,2,3,2]) 

sage: w._to_partition_content() 

word: 132112454132 

sage: Word([])._to_partition_content() 

word: 

""" 

if self.length() == 0: 

return self 

 

from sage.combinat.words.word import Word 

n = max(self) 

ev = Word( Words(n)(self).evaluation() ) 

sig = ev.reversal().standard_permutation().reduced_word() 

 

# sig is now the reverse complement of a reduced word for a minimal 

# length permutation which would sort the letters of ev into a 

# partition 

 

out = self 

for i in reversed(sig): 

out = out._s(n-i) 

return out 

 

def cocharge(self): 

r""" 

Return the cocharge of ``self``. For a word `w`, this can be defined as 

`n_{ev} - ch(w)`, where `ch(w)` is the charge of `w` and `ev` is the 

evaluation of `w`, and `n_{ev}` is `\sum_{i<j} min(ev_i, ev_j)`. 

 

EXAMPLES:: 

 

sage: Word([1,2,3]).cocharge() 

0 

sage: Word([3,2,1]).cocharge() 

3 

sage: Word([1,1,2]).cocharge() 

0 

sage: Word([2,1,2]).cocharge() 

1 

 

TESTS:: 

 

sage: Word([]).cocharge() 

0 

""" 

return self.evaluation_partition().weighted_size() - self.charge() 

 

def charge(self, check=True): 

r""" 

Return the charge of ``self``. This is defined as follows. 

 

If `w` is a permutation of length `n`, (in other words, the evaluation 

of `w` is `(1, 1, \dots, 1)`), the statistic charge(`w`) is given by 

`\sum_{i=1}^n c_i(w)` where `c_1(w) = 0` and `c_i(w)` is defined 

recursively by setting `p_i` equal to `1` if `i` appears to the right 

of `i-1` in `w` and `0` otherwise. Then we set `c_i(w) = c_{i-1}(w) + 

p_i`. 

 

EXAMPLES:: 

 

sage: Word([1, 2, 3]).charge() 

3 

sage: Word([3, 5, 1, 4, 2]).charge() == 0 + 1 + 1 + 2 + 2 

True 

 

If `w` is not a permutation, but the evaluation of `w` is a partition, 

the charge of `w` is defined to be the sum of its charge subwords 

(each of which will be a permutation). The first charge subword is 

found by starting at the end of `w` and moving left until the first 

`1` is found. This is marked, and we continue to move to the left 

until the first `2` is found, wrapping around from the beginning of 

the word back to the end, if necessary. We mark this `2`, and 

continue on until we have marked the largest letter in `w`. The 

marked letters, with relative order preserved, form the first charge 

subword of `w`. This subword is removed, and the next charge subword 

is found in the same manner from the remaining letters. In the 

following example, `w1, w2, w3` are the charge subwords of `w`. 

 

EXAMPLES:: 

 

sage: w = Word([5,2,3,4,4,1,1,1,2,2,3]) 

sage: w1 = Word([5, 2, 4, 1, 3]) 

sage: w2 = Word([3, 4, 1, 2]) 

sage: w3 = Word([1, 2]) 

sage: w.charge() == w1.charge() + w2.charge() + w3.charge() 

True 

 

Finally, if `w` does not have partition content, we apply the 

Lascoux-Schützenberger standardization operators `s_i` in such a 

manner as to obtain a word with partition content. (The word we obtain 

is independent of the choice of operators.) The charge is then 

defined to be the charge of this word:: 

 

sage: Word([3,3,2,1,1]).charge() 

0 

sage: Word([1,2,3,1,2]).charge() 

2 

 

Note that this differs from the definition of charge given in 

Macdonald's book. The difference amounts to a choice of 

reading a word from left-to-right or right-to-left. The choice in 

Sage was made to agree with the definition of a reading word of a 

tableau in Sage, and seems to be the more common convention in the 

literature. 

 

REFERENCES: 

 

[1] Ian Macdonald, *Symmetric Functions and Hall Polynomials* second 

edition, 1995, Oxford University Press 

 

[2] A. Lascoux, L. Lapointe, and J. Morse. *Tableau atoms and a new 

Macdonald positivity conjecture.* Duke Math Journal, **116 (1)**, 

2003. :arxiv:`math/0008073` 

 

[3] A. Lascoux, B. Leclerc, and J.Y. Thibon. *The Plactic Monoid*. 

Survey article available at 

[http://www-igm.univ-mlv.fr/~jyt/ARTICLES/plactic.ps] 

 

TESTS:: 

 

sage: Word([1,1,2,2,3]).charge() 

4 

sage: Word([3,1,1,2,2]).charge() 

3 

sage: Word([2,1,1,2,3]).charge() 

2 

sage: Word([2,1,1,3,2]).charge() 

2 

sage: Word([3,2,1,1,2]).charge() 

1 

sage: Word([2,2,1,1,3]).charge() 

1 

sage: Word([3,2,2,1,1]).charge() 

0 

sage: Word([]).charge() 

0 

""" 

if check: 

ev_dict = self.evaluation_dict() 

ordered_alphabet = sorted(ev_dict, 

key=self.parent().sortkey_letters) 

evaluation = [ev_dict[a] for a in ordered_alphabet] 

from sage.combinat.partition import Partitions 

if evaluation not in Partitions(): 

return self._to_partition_content().charge() 

res = 0 

w = self.to_integer_list() 

while len(w) != 0: 

i =len(w) - 1 

l = min(w) 

index = 0 

while len(w) != 0 and l <= max(w): 

while w[i] != l: 

i -= 1 

if i < 0: 

i = len(w) - 1 

index += 1 

res += index 

l += 1 

w.pop(i) 

i -= 1 

if i < 0: 

i = len(w) - 1 

index += 1 

return res 

 

def BWT(self): 

r""" 

Return the Burrows-Wheeler Transform (BWT) of ``self``. 

 

The *Burrows-Wheeler transform* of a finite word `w` is obtained 

from `w` by first listing the conjugates of `w` in lexicographic order 

and then concatenating the final letters of the conjugates in this 

order. See [1]. 

 

EXAMPLES:: 

 

sage: Word('abaccaaba').BWT() 

word: cbaabaaca 

sage: Word('abaab').BWT() 

word: bbaaa 

sage: Word('bbabbaca').BWT() 

word: cbbbbaaa 

sage: Word('aabaab').BWT() 

word: bbaaaa 

sage: Word().BWT() 

word: 

sage: Word('a').BWT() 

word: a 

 

REFERENCES: 

 

- [1] M. Burrows, D.J. Wheeler, "A block-sorting lossless data 

compression algorithm", HP Lab Technical Report, 1994, available 

at http://www.hpl.hp.com/techreports/Compaq-DEC/SRC-RR-124.html 

""" 

if self.is_empty(): 

return self 

conjugates = sorted(self._conjugates_list()) 

return self.parent()([x[x.length()-1] for x in conjugates], check=False) 

 

def iterated_left_palindromic_closure(self, f=None): 

r""" 

Return the iterated left (``f``-)palindromic closure of ``self``. 

 

INPUT: 

 

- ``f`` -- involution (default: ``None``) on the alphabet of ``self``. 

It must be callable on letters as well as words (e.g. ``WordMorphism``). 

 

OUTPUT: 

 

word -- the left iterated ``f``-palindromic closure of ``self``. 

 

EXAMPLES:: 

 

sage: Word('123').iterated_left_palindromic_closure() 

word: 3231323 

sage: f = WordMorphism('a->b,b->a') 

sage: Word('ab').iterated_left_palindromic_closure(f=f) 

word: abbaab 

sage: Word('aab').iterated_left_palindromic_closure(f=f) 

word: abbaabbaab 

 

TESTS: 

 

If ``f`` is not an involution:: 

 

sage: f = WordMorphism('a->b,b->b') 

sage: Word('aab').iterated_left_palindromic_closure(f=f) 

Traceback (most recent call last): 

... 

TypeError: self (=a->b, b->b) is not an endomorphism 

 

REFERENCES: 

 

- A. de Luca, A. De Luca, Pseudopalindrome closure operators 

in free monoids, Theoret. Comput. Sci. 362 (2006) 282--300. 

""" 

if f is None: 

return self.reversal().iterated_right_palindromic_closure(f=f) 

else: 

from sage.combinat.words.morphism import WordMorphism 

f = WordMorphism(f) 

return f(self).reversal().iterated_right_palindromic_closure(f=f) 

 

def count(self, letter): 

r""" 

Count the number of occurrences of ``letter`` in ``self``. 

 

EXAMPLES:: 

 

sage: Word('abbabaab').count('a') 

4 

""" 

return Integer(sum(1 for a in self if a == letter)) 

 

def balance(self): 

r""" 

Return the balance of ``self``. 

 

The balance of a word is the smallest number `q` such that ``self`` is 

`q`-balanced [1]. 

 

A finite or infinite word `w` is said to be `q`-*balanced* if for 

any two factors `u`, `v` of `w` of the same length, the difference 

between the number of `x`'s in each of `u` and `v` is at most `q` 

for all letters `x` in the alphabet of `w`. A `1`-balanced word is 

simply said to be balanced. See Chapter 2 of [2]. 

 

OUTPUT: 

 

integer 

 

EXAMPLES:: 

 

sage: Word('1111111').balance() 

0 

sage: Word('001010101011').balance() 

2 

sage: Word('0101010101').balance() 

1 

 

:: 

 

sage: w = Word('11112222') 

sage: w.is_balanced(2) 

False 

sage: w.is_balanced(3) 

False 

sage: w.is_balanced(4) 

True 

sage: w.is_balanced(5) 

True 

sage: w.balance() 

4 

 

TESTS:: 

 

sage: Word('1111122222').balance() 

5 

sage: Word('').balance() 

0 

sage: Word('1').balance() 

0 

sage: Word('12').balance() 

1 

sage: Word('1112').balance() 

1 

 

REFERENCES: 

 

- [1] I. Fagnot, L. Vuillon, Generalized balances in Sturmian words, 

Discrete Applied Mathematics 121 (2002), 83--101. 

- [2] M. Lothaire, Algebraic Combinatorics On Words, vol. 90 of 

Encyclopedia of Mathematics and its Applications, Cambridge 

University Press, U.K., 2002. 

""" 

alphabet = self.letters() 

best = 0 

for i in range(1, self.length()): 

start = iter(self) 

end = iter(self) 

abelian = dict(zip(alphabet, [0]*len(alphabet))) 

for _ in range(i): 

abelian[next(end)] += 1 

abel_max = abelian.copy() 

abel_min = abelian.copy() 

for _ in range(self.length() - i): 

lost = next(start) 

gain = next(end) 

abelian[gain] += 1 

abelian[lost] -= 1 

abel_max[gain] = max(abel_max[gain], abelian[gain]) 

abel_min[lost] = min(abel_min[lost], abelian[lost]) 

best = max(best, max(abel_max[a] - abel_min[a] for a in alphabet)) 

return best 

 

def is_balanced(self, q=1): 

r""" 

Return ``True`` if ``self`` is ``q``-balanced, and ``False`` otherwise. 

 

A finite or infinite word `w` is said to be `q`-*balanced* if for 

any two factors `u`, `v` of `w` of the same length, the difference 

between the number of `x`'s in each of `u` and `v` is at most `q` 

for all letters `x` in the alphabet of `w`. A `1`-balanced word is 

simply said to be balanced. See for instance [1] and Chapter 2 of 

[2]. 

 

INPUT: 

 

- ``q`` -- integer (default: ``1``), the balance level 

 

OUTPUT: 

 

boolean -- the result 

 

EXAMPLES:: 

 

sage: Word('1213121').is_balanced() 

True 

sage: Word('1122').is_balanced() 

False 

sage: Word('121333121').is_balanced() 

False 

sage: Word('121333121').is_balanced(2) 

False 

sage: Word('121333121').is_balanced(3) 

True 

sage: Word('121122121').is_balanced() 

False 

sage: Word('121122121').is_balanced(2) 

True 

 

TESTS:: 

 

sage: Word('121122121').is_balanced(-1) 

Traceback (most recent call last): 

... 

TypeError: the balance level must be a positive integer 

sage: Word('121122121').is_balanced(0) 

Traceback (most recent call last): 

... 

TypeError: the balance level must be a positive integer 

sage: Word('121122121').is_balanced('a') 

Traceback (most recent call last): 

... 

TypeError: the balance level must be a positive integer 

 

REFERENCES: 

 

- [1] J. Cassaigne, S. Ferenczi, L.Q. Zamboni, Imbalances in 

Arnoux-Rauzy sequences, Ann. Inst. Fourier (Grenoble) 50 (2000) 

1265--1276. 

- [2] M. Lothaire, Algebraic Combinatorics On Words, vol. 90 of 

Encyclopedia of Mathematics and its Applications, Cambridge 

University Press, U.K., 2002. 

""" 

if not isinstance(q, (int, Integer)) or q <= 0: 

raise TypeError("the balance level must be a positive integer") 

alphabet = self.letters() 

for i in range(2, self.length()): 

empty_sets = [set() for _ in range(len(alphabet))] 

tab = dict(zip(alphabet, empty_sets)) 

for fact in self.factor_iterator(i): 

evaluation_dict = fact.evaluation_dict() 

for a in alphabet: 

tab[a].add(evaluation_dict.get(a, 0)) 

for t in tab.values(): 

if len(t) > q+1: 

return False 

return True 

 

def abelian_vectors(self, n): 

r""" 

Return the abelian vectors of factors of length ``n`` of ``self``. 

 

The vectors are defined w.r.t. the order of the alphabet of the 

parent. 

 

OUTPUT: 

 

a set of tuples 

 

EXAMPLES:: 

 

sage: W = Words([0,1,2]) 

sage: w = W([0,1,1,0,1,2,0,2,0,2]) 

sage: w.abelian_vectors(3) 

{(1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1)} 

sage: w[:5].abelian_vectors(3) 

{(1, 2, 0)} 

sage: w[5:].abelian_vectors(3) 

{(1, 0, 2), (2, 0, 1)} 

 

:: 

 

sage: w = words.FibonacciWord()[:100] 

sage: sorted(w.abelian_vectors(0)) 

[(0, 0)] 

sage: sorted(w.abelian_vectors(1)) 

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

sage: sorted(w.abelian_vectors(7)) 

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

 

The word must be defined with a parent on a finite alphabet:: 

 

sage: from itertools import count 

sage: w = Word(count(), alphabet=NN) 

sage: w[:2].abelian_vectors(2) 

Traceback (most recent call last): 

... 

TypeError: The alphabet of the parent is infinite; define the 

word with a parent on a finite alphabet 

 

TESTS:: 

 

sage: W = Words([0, 1]) 

sage: w = W([0,0,0]) 

sage: sorted(w.abelian_vectors(3)) 

[(3, 0)] 

sage: w = W([0,0,0,1]) 

sage: sorted(w.abelian_vectors(3)) 

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

sage: w = W([0,0,0,1,1]) 

sage: sorted(w.abelian_vectors(3)) 

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

sage: w = W([0,0,0,1,1,1]) 

sage: sorted(w.abelian_vectors(3)) 

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

 

:: 

 

sage: w = Word([0,1,0], alphabet=[0,1]) 

sage: w.abelian_complexity(3) 

1 

sage: w.abelian_complexity(4) 

0 

 

""" 

alphabet = self.parent().alphabet() 

size = alphabet.cardinality() 

if size == float('inf'): 

raise TypeError("The alphabet of the parent is infinite; define" 

" the word with a parent on a finite alphabet") 

S = set() 

if n > self.length(): 

return S 

rank = dict((letter,i) for i,letter in enumerate(alphabet)) 

start = iter(self) 

end = iter(self) 

abelian = [0] * size 

for _ in range(n): 

abelian[rank[next(end)]] += 1 

S.add(tuple(abelian)) 

for letter in end: 

abelian[rank[letter]] += 1 

abelian[rank[next(start)]] -= 1 

S.add(tuple(abelian)) 

return S 

 

def abelian_complexity(self, n): 

r""" 

Return the number of abelian vectors of factors of length ``n`` of ``self``. 

 

EXAMPLES:: 

 

sage: w = words.FibonacciWord()[:100] 

sage: [w.abelian_complexity(i) for i in range(20)] 

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

 

:: 

 

sage: w = words.ThueMorseWord()[:100] 

sage: [w.abelian_complexity(i) for i in range(20)] 

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

 

""" 

return len(self.abelian_vectors(n)) 

 

def sturmian_desubstitute_as_possible(self): 

r""" 

Sturmian-desubstitute the word ``self`` as much as possible. 

 

The finite word ``self`` must be defined on a two-letter 

alphabet or use at most two letters. 

 

It can be Sturmian desubstituted if one letter appears 

isolated: the Sturmian desubstitution consists in removing one 

letter per run of the non-isolated letter. The accelerated 

Sturmian desubstitution consists in removing a run equal to 

the length of the shortest inner run from any run of the 

non-isolated letter (including possible leading and trailing 

runs even if they have shorter length). The (accelerated) 

Sturmian desubstitution is done as much as possible. A word is 

a factor of a Sturmian word if, and only if, the result is the 

empty word. 

 

OUTPUT: 

 

a finite word defined on a two-letter alphabet 

 

EXAMPLES:: 

 

sage: u = Word('10111101101110111',alphabet='01') ; u 

word: 10111101101110111 

sage: v = u.sturmian_desubstitute_as_possible() ; v 

word: 01100101 

sage: v == v.sturmian_desubstitute_as_possible() 

True 

 

sage: Word('azaazaaazaaazaazaaaz', alphabet='az').sturmian_desubstitute_as_possible() 

word: 

 

 

TESTS:: 

 

sage: w = Word('azazaza', alphabet='aze') 

sage: w.sturmian_desubstitute_as_possible() 

word: 

sage: Word('aze').sturmian_desubstitute_as_possible() 

Traceback (most recent call last): 

... 

TypeError: your word must be defined on a binary alphabet or use at most two different letters 

sage: Word('azaaazaazaazaaazaaza', alphabet='az').sturmian_desubstitute_as_possible() 

word: 

sage: Word('azaaazaazaazaaazaaaza', alphabet='az').sturmian_desubstitute_as_possible() 

word: azzaa 

 

Boundary effects:: 

 

sage: Word('', alphabet='az').sturmian_desubstitute_as_possible() 

word: 

sage: Word('azzzzz', alphabet='az').sturmian_desubstitute_as_possible() 

word: 

sage: Word('zzzzza', alphabet='az').sturmian_desubstitute_as_possible() 

word: 

sage: Word('aaaaazaaaaaaaaa', alphabet='az').sturmian_desubstitute_as_possible() 

word: 

sage: Word('aaaaaaaaaaaaaa', alphabet='az').sturmian_desubstitute_as_possible() 

word: 

 

Boundary effects without alphabet:: 

 

sage: Word('').sturmian_desubstitute_as_possible() 

word: 

sage: Word('azzzzz').sturmian_desubstitute_as_possible() 

word: 

sage: Word('zzzzza').sturmian_desubstitute_as_possible() 

word: 

sage: Word('aaaaazaaaaaaaaa').sturmian_desubstitute_as_possible() 

word: 

sage: Word('aaaaaaaaaaaaaa').sturmian_desubstitute_as_possible() 

word: 

 

Idempotence:: 

 

sage: r = words.RandomWord(randint(1,15)).sturmian_desubstitute_as_possible() ; r == r.sturmian_desubstitute_as_possible() 

True 

 

AUTHOR: 

 

- Thierry Monteil 

""" 

if self.is_empty(): 

return self 

W = self.parent() 

if W.alphabet().cardinality()== 2: 

alphabet = W.alphabet() 

else: 

alphabet = self.letters() 

if len(alphabet) > 2: 

raise TypeError('your word must be defined on a binary alphabet or use at most two different letters') 

elif len(alphabet) < 2: 

return W() 

word_from_letter = {l:W([l],datatype="list",check=False) for l in alphabet} 

is_prefix = True 

current_run_length = 0 

prefix_length = 0 

prefix_letter = self[0] 

is_isolated = {alphabet[0]:True,alphabet[1]:True} 

minimal_run = {alphabet[0]:Infinity,alphabet[1]:Infinity} 

maximal_run = {alphabet[0]:0,alphabet[1]:0} 

runs = {alphabet[0]:[],alphabet[1]:[]} 

for i in self: 

if is_prefix: 

if i == prefix_letter: 

prefix_length += 1 

if prefix_length > 1: 

is_isolated[i] = False 

else: 

is_prefix = False 

current_run_length = 1 

previous_letter = i 

else: 

if i == previous_letter: 

current_run_length += 1 

if current_run_length > 1: 

is_isolated[i] = False 

else: 

runs[previous_letter].append(current_run_length) 

minimal_run[previous_letter] = min(minimal_run[previous_letter],current_run_length) 

maximal_run[previous_letter] = max(maximal_run[previous_letter],current_run_length) 

current_run_length = 1 

previous_letter = i 

# at this point, previous_letter is the suffix letter and current_run_length is the suffix length 

if not (is_isolated[alphabet[0]] or is_isolated[alphabet[1]]): 

return self 

elif is_isolated[alphabet[0]] and is_isolated[alphabet[1]]: 

return W() 

else: 

if is_isolated[alphabet[0]]: 

l_isolated = alphabet[0] #the isolated letter 

l_running = alphabet[1] #the running letter (non-isolated) 

else: 

l_isolated = alphabet[1] 

l_running = alphabet[0] 

w_isolated = word_from_letter[l_isolated] #the word associated to the isolated letter 

w_running = word_from_letter[l_running] #the word associated to the running letter 

min_run = minimal_run[l_running] 

if (prefix_letter == l_isolated) or (prefix_length <= min_run): 

desubstitued_word = W() 

else: 

desubstitued_word = w_running ** (prefix_length - min_run) 

for i in runs[l_running]: 

desubstitued_word = desubstitued_word + w_isolated + w_running ** (i - min_run) 

if (current_run_length > 0): 

desubstitued_word = desubstitued_word + w_isolated 

if (previous_letter == l_running) and (current_run_length > min_run): 

desubstitued_word = desubstitued_word + w_running ** (current_run_length - min_run) 

return desubstitued_word.sturmian_desubstitute_as_possible() 

 

 

def is_sturmian_factor(self): 

r""" 

Tell whether ``self`` is a factor of a Sturmian word. 

 

The finite word ``self`` must be defined on a two-letter alphabet. 

 

Equivalently, tells whether ``self`` is balanced. The 

advantage over the ``is_balanced`` method is that this one runs in 

linear time whereas ``is_balanced`` runs in quadratic time. 

 

OUTPUT: 

 

boolean -- the result 

 

EXAMPLES:: 

 

sage: w = Word('0111011011011101101',alphabet='01') 

sage: w.is_sturmian_factor() 

True 

 

:: 

 

sage: words.LowerMechanicalWord(random(),alphabet='01')[:100].is_sturmian_factor() 

True 

sage: words.CharacteristicSturmianWord(random())[:100].is_sturmian_factor() 

True 

 

:: 

 

sage: w = Word('aabb',alphabet='ab') 

sage: w.is_sturmian_factor() 

False 

 

sage: s1 = WordMorphism('a->ab,b->b') 

sage: s2 = WordMorphism('a->ba,b->b') 

sage: s3 = WordMorphism('a->a,b->ba') 

sage: s4 = WordMorphism('a->a,b->ab') 

sage: W = Words('ab') 

sage: w = W('ab') 

sage: for i in range(8): w = choice([s1,s2,s3,s4])(w) 

sage: w 

word: abaaabaaabaabaaabaaabaabaaabaabaaabaaaba... 

sage: w.is_sturmian_factor() 

True 

 

Famous words:: 

 

sage: words.FibonacciWord()[:100].is_sturmian_factor() 

True 

sage: words.ThueMorseWord()[:1000].is_sturmian_factor() 

False 

sage: words.KolakoskiWord()[:1000].is_sturmian_factor() 

False 

 

REFERENCES: 

 

.. [Arn2002] \P. Arnoux, Sturmian sequences, in Substitutions in Dynamics, 

N. Pytheas Fogg (Ed.), Arithmetics, and Combinatorics (Lecture 

Notes in Mathematics, Vol. 1794), 2002. 

.. [Ser1985] \C. Series. The geometry of Markoff numbers. The Mathematical 

Intelligencer, 7(3):20--29, 1985. 

.. [SU2009] \J. Smillie and C. Ulcigrai. Symbolic coding for linear 

trajectories in the regular octagon, :arxiv:`0905.0871`, 2009. 

 

AUTHOR: 

 

- Thierry Monteil 

""" 

return self.sturmian_desubstitute_as_possible().is_empty() 

 

 

def is_tangent(self): 

r""" 

Tell whether ``self`` is a tangent word. 

 

The finite word ``self`` must be defined on a two-letter alphabet. 

 

A binary word is said to be *tangent* if it can appear in 

infinitely many cutting sequences of a smooth curve, where each 

cutting sequence is observed on a progressively smaller grid. 

 

This class of words strictly contains the class of `1`-balanced 

words, and is strictly contained in the class of `2`-balanced words. 

 

This method runs in linear time. 

 

OUTPUT: 

 

boolean -- the result 

 

EXAMPLES:: 

 

sage: w = Word('01110110110111011101',alphabet='01') 

sage: w.is_tangent() 

True 

 

Some tangent words may not be balanced:: 

 

sage: Word('aabb',alphabet='ab').is_balanced() 

False 

sage: Word('aabb',alphabet='ab').is_tangent() 

True 

 

Some `2`-balanced words may not be tangent:: 

 

sage: Word('aaabb',alphabet='ab').is_tangent() 

False 

sage: Word('aaabb',alphabet='ab').is_balanced(2) 

True 

 

Famous words:: 

 

sage: words.FibonacciWord()[:100].is_tangent() 

True 

sage: words.ThueMorseWord()[:1000].is_tangent() 

True 

sage: words.KolakoskiWord()[:1000].is_tangent() 

False 

 

REFERENCES: 

 

.. [Mon2010] \T. Monteil, The asymptotic language of smooth curves, talk 

at LaCIM2010. 

 

AUTHOR: 

 

- Thierry Monteil 

""" 

if (self.parent().alphabet().cardinality() != 2): 

raise TypeError('your word must be defined on a binary alphabet') 

[a,b] = self.parent().alphabet() 

mini = 0 

maxi = 0 

height = 0 

for i in self.sturmian_desubstitute_as_possible(): 

if i == a: 

height = height + 1 

maxi = max(maxi , height) 

if i == b: 

height = height - 1 

mini = min(mini , height) 

return (maxi - mini <= 2) 

 

 

# TODO. 

# 1. Those three swap functions should use the cmp of python. 

# 2. The actual code should then be copied as is in the Word_over_Alphabet 

# and continue to use the parent cmp 

# 3. Once Word can define Words over alphabet, the examples 

# should be updated appropriately. 

 

def swap(self, i, j=None): 

r""" 

Return the word `w` with entries at positions ``i`` and 

``j`` swapped. By default, ``j = i+1``. 

 

EXAMPLES:: 

 

sage: Word([1,2,3]).swap(0,2) 

word: 321 

sage: Word([1,2,3]).swap(1) 

word: 132 

sage: Word("abba").swap(1,-1) 

word: aabb 

""" 

if j is None: 

j = i+1 

new = list(self) 

(new[i], new[j]) = (new[j], new[i]) 

from sage.combinat.words.word import Word 

return Word(new) 

 

def swap_increase(self, i): 

r""" 

Return the word with positions ``i`` and ``i+1`` exchanged 

if ``self[i] > self[i+1]``. Otherwise, it returns ``self``. 

 

EXAMPLES:: 

 

sage: w = Word([1,3,2]) 

sage: w.swap_increase(1) 

word: 123 

sage: w.swap_increase(0) 

word: 132 

sage: w.swap_increase(0) is w 

True 

sage: Words("ab")("abba").swap_increase(0) 

word: abba 

sage: Words("ba")("abba").swap_increase(0) 

word: baba 

""" 

key = self._parent.sortkey_letters 

if key(self[i]) > key(self[i + 1]): 

return self.swap(i) 

else: 

return self 

 

def swap_decrease(self, i): 

r""" 

Return the word with positions ``i`` and ``i+1`` exchanged 

if ``self[i] < self[i+1]``. Otherwise, it returns ``self``. 

 

EXAMPLES:: 

 

sage: w = Word([1,3,2]) 

sage: w.swap_decrease(0) 

word: 312 

sage: w.swap_decrease(1) 

word: 132 

sage: w.swap_decrease(1) is w 

True 

sage: Words("ab")("abba").swap_decrease(0) 

word: baba 

sage: Words("ba")("abba").swap_decrease(0) 

word: abba 

""" 

key = self._parent.sortkey_letters 

if key(self[i]) < key(self[i + 1]): 

return self.swap(i) 

else: 

return self 

 

def abelian_vector(self, alphabet=None): 

r""" 

Return the abelian vector of ``self`` counting the occurrences of each letter. 

 

The vector is defined w.r.t. the order of the alphabet of the 

parent. See also :meth:`evaluation_dict`. 

 

INPUT: 

 

- ``self`` -- word having a parent on a finite alphabet 

- ``alphabet`` -- *DEPRECATED* 

 

OUTPUT: 

 

a list 

 

EXAMPLES:: 

 

sage: W = Words('ab') 

sage: W('aaabbbbb').abelian_vector() 

[3, 5] 

sage: W('a').abelian_vector() 

[1, 0] 

sage: W().abelian_vector() 

[0, 0] 

 

The argument ``alphabet`` is deprecated:: 

 

sage: Word('aabaa').abelian_vector('abc') 

doctest:...: DeprecationWarning: The argument alphabet of 

methods abelian_vector and parikh_vector is deprecated and will 

be removed in a future version of Sage. In order to fix this, 

you must define your word on a parent with a finite alphabet. 

See http://trac.sagemath.org/17058 for details. 

[4, 1, 0] 

 

You may fix the above deprecated use of the ``alphabet`` argument this way:: 

 

sage: W = Words('abc') 

sage: W('aabaa').abelian_vector() 

[4, 1, 0] 

 

TESTS:: 

 

sage: W = Words() 

sage: W('aabaa').abelian_vector() 

Traceback (most recent call last): 

... 

TypeError: The alphabet of the parent is infinite; define the 

word with a parent on a finite alphabet or use 

evaluation_dict() instead 

""" 

if alphabet is None: 

if self.parent().alphabet().cardinality() is Infinity: 

raise TypeError("The alphabet of the parent is infinite; define " 

"the word with a parent on a finite alphabet or use " 

"evaluation_dict() instead") 

alphabet = self.parent().alphabet() 

else: 

from sage.misc.superseded import deprecation 

deprecation(17058, "The argument alphabet of methods abelian_vector " 

"and parikh_vector is deprecated and will be " 

"removed in a future version of Sage. In order to " 

"fix this, you must define your word on a parent " 

"with a finite alphabet.") 

 

ev_dict = self.evaluation_dict() 

return [ev_dict.get(a,0) for a in alphabet] 

 

parikh_vector = deprecated_function_alias(17058, abelian_vector) 

evaluation = abelian_vector 

 

def robinson_schensted(self): 

""" 

Return the semistandard tableau and standard tableau pair 

obtained by running the Robinson-Schensted algorithm on ``self``. 

 

This can also be done by running 

:func:`~sage.combinat.rsk.RSK` on ``self``. 

 

EXAMPLES:: 

 

sage: Word([1,1,3,1,2,3,1]).robinson_schensted() 

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

""" 

from sage.combinat.rsk import RSK 

return RSK(self) 

 

def _rsk_iter(self): 

r""" 

Return an iterator for :func:`~sage.combinat.rsk.RSK`. 

 

Yields pairs `(i, w_i)` for a word `w = w_1 w_2 \cdots w_k`. 

 

EXAMPLES:: 

 

sage: for x in Word([1,1,3,1,2,3,1])._rsk_iter(): x 

... 

(1, 1) 

(2, 1) 

(3, 3) 

(4, 1) 

(5, 2) 

(6, 3) 

(7, 1) 

""" 

return zip(range(1, len(self) + 1), self) 

 

def shuffle(self, other, overlap=0): 

r""" 

Return the combinatorial class representing the shuffle product 

between words ``self`` and ``other``. This consists of all words of length 

``self.length()+other.length()`` that have both ``self`` and ``other`` as 

subwords. 

 

If ``overlap`` is non-zero, then the combinatorial class representing 

the shuffle product with overlaps is returned. The calculation of 

the shift in each overlap is done relative to the order of the 

alphabet. For example, `a` shifted by `a` is `b` in the alphabet 

`[a, b, c]` and `0` shifted by `1` in `[0, 1, 2, 3]` is `2`. 

 

INPUT: 

 

- ``other`` -- finite word 

- ``overlap`` -- (default: ``0``) integer or ``True`` 

 

OUTPUT: 

 

combinatorial class of shuffle product of ``self`` and ``other`` 

 

EXAMPLES:: 

 

sage: ab = Word("ab") 

sage: cd = Word("cd") 

sage: sp = ab.shuffle(cd); sp 

Shuffle product of word: ab and word: cd 

sage: sp.cardinality() 

6 

sage: sp.list() 

[word: abcd, word: acbd, word: acdb, word: cabd, word: cadb, word: cdab] 

sage: w = Word([0,1]) 

sage: u = Word([2,3]) 

sage: w.shuffle(w) 

Shuffle product of word: 01 and word: 01 

sage: u.shuffle(u) 

Shuffle product of word: 23 and word: 23 

sage: w.shuffle(u) 

Shuffle product of word: 01 and word: 23 

sage: w.shuffle(u,2) 

Overlapping shuffle product of word: 01 and word: 23 with 2 overlaps 

""" 

if overlap == 0: 

from sage.combinat.words.shuffle_product import ShuffleProduct_w1w2 

return ShuffleProduct_w1w2(self, other) 

else: 

if any(a not in ZZ for a in self) or any(a not in ZZ for a in other): 

raise ValueError("for a nonzero overlap, words must contain integers as letters") 

if overlap is True: 

from sage.combinat.words.shuffle_product import ShuffleProduct_overlapping 

return ShuffleProduct_overlapping(self, other) 

elif isinstance(overlap, (int,Integer)): 

from sage.combinat.words.shuffle_product import ShuffleProduct_overlapping_r 

return ShuffleProduct_overlapping_r(self, other, overlap) 

raise ValueError('overlapping must be True or an integer') 

 

def shifted_shuffle(self, other, shift=None): 

r""" 

Return the combinatorial class representing the shifted shuffle 

product between words ``self`` and ``other``. This is the same as the 

shuffle product of ``self`` with the word obtained from ``other`` by 

incrementing its values (i.e. its letters) by the given ``shift``. 

 

INPUT: 

 

- ``other`` -- finite word over the integers 

- ``shift`` -- integer or ``None`` (default: ``None``) added to each letter of 

``other``. When ``shift`` is ``None``, it is replaced by ``self.length()`` 

 

OUTPUT: 

 

combinatorial class of shifted shuffle products of ``self`` and ``other`` 

 

EXAMPLES:: 

 

sage: w = Word([0,1,1]) 

sage: sp = w.shifted_shuffle(w); sp 

Shuffle product of word: 011 and word: 344 

sage: sp = w.shifted_shuffle(w, 2); sp 

Shuffle product of word: 011 and word: 233 

sage: sp.cardinality() 

20 

sage: WordOptions(identifier='') 

sage: sp.list() 

[011233, 012133, 012313, 012331, 021133, 021313, 021331, 023113, 023131, 023311, 201133, 201313, 201331, 203113, 203131, 203311, 230113, 230131, 230311, 233011] 

sage: WordOptions(identifier='word: ') 

sage: y = Word('aba') 

sage: y.shifted_shuffle(w,2) 

Traceback (most recent call last): 

... 

ValueError: for shifted shuffle, words must only contain integers as letters 

""" 

if any(a not in ZZ for a in self) or any(a not in ZZ for a in other): 

raise ValueError("for shifted shuffle, words must only contain integers as letters") 

if shift is None: 

from sage.combinat.words.shuffle_product import ShuffleProduct_shifted 

return ShuffleProduct_shifted(self, other) 

else: 

return self.shuffle(self._parent([x + shift for x in other], check=False)) 

 

###################################################################### 

# XXX TODO: The description is inconsistent w.r.t. "W" and "alphabet". 

###################################################################### 

def delta_inv(self, W=None, s=None): 

r""" 

Lift ``self`` via the delta operator to obtain a word containing the 

letters in alphabet (default is ``[0, 1]``). The letters used in the 

construction start with ``s`` (default is ``alphabet[0]``) and cycle 

through alphabet. 

 

INPUT: 

 

- ``alphabet`` -- an iterable 

- ``s`` -- an object in the iterable 

 

EXAMPLES:: 

 

sage: W = Words([1, 2]) 

sage: W([2, 2, 1, 1]).delta_inv() 

word: 112212 

sage: W([1, 1, 1, 1]).delta_inv(Words('123')) 

word: 1231 

sage: W([2, 2, 1, 1, 2]).delta_inv(s=2) 

word: 22112122 

""" 

alphabet = [1, 2] if W is None else W.alphabet() 

cycle_alphabet = cycle(alphabet) 

if self.is_empty(): 

return Words(alphabet)() 

if s is None: 

s = next(cycle_alphabet) 

else: 

if s not in alphabet: 

raise ValueError("starting letter not in alphabet") 

t = next(cycle_alphabet) 

while t != s: 

t = next(cycle_alphabet) 

w = [] 

for i in self: 

w.extend([s] * i) 

s = next(cycle_alphabet) 

return Words(alphabet)(w) 

 

def delta(self): 

r""" 

Return the image of ``self`` under the delta morphism. This is the 

word composed of the length of consecutive runs of the same letter 

in a given word. 

 

EXAMPLES:: 

 

sage: W = Words('0123456789') 

sage: W('22112122').delta() 

word: 22112 

sage: W('555008').delta() 

word: 321 

sage: W().delta() 

word: 

sage: Word('aabbabaa').delta() 

word: 22112 

 

""" 

if self.is_empty(): 

return Words()([]) 

ss = self[0] 

c = 0 

v = list() 

max_c = 0 

for s in self: 

if s == ss: 

c += 1 

if c > max_c: 

max_c = c 

else: 

v.append(c) 

ss = s 

c = 1 

v.append(c) 

return Words(list(range(1, 1 + max_c)))(v) 

 

# TODO. Decide whether delta_derivate* really need W.alphabet().last().... 

# RENAME: Should "derivate" be derivative?! 

 

def delta_derivate(self, W=None): 

r""" 

Return the derivative under delta for ``self``. 

 

EXAMPLES:: 

 

sage: W = Words('12') 

sage: W('12211').delta_derivate() 

word: 22 

sage: W('1').delta_derivate(Words([1])) 

word: 1 

sage: W('2112').delta_derivate() 

word: 2 

sage: W('2211').delta_derivate() 

word: 22 

sage: W('112').delta_derivate() 

word: 2 

sage: W('11222').delta_derivate(Words([1, 2, 3])) 

word: 3 

""" 

d = self.delta() 

if len(d) == 0: 

return d 

if W is None: 

W = d.parent() 

if d[0] != W.alphabet().last(): 

d = d[1:] 

if d[-1] != W.alphabet().last(): 

d = d[:-1] 

return d 

 

def delta_derivate_left(self, W=None): 

r""" 

Return the derivative under delta for ``self``. 

 

EXAMPLES:: 

 

sage: W = Words('12') 

sage: W('12211').delta_derivate_left() 

word: 22 

sage: W('1').delta_derivate_left(Words([1])) 

word: 1 

sage: W('2112').delta_derivate_left() 

word: 21 

sage: W('2211').delta_derivate_left() 

word: 22 

sage: W('112').delta_derivate_left() 

word: 21 

sage: W('11222').delta_derivate_left(Words([1, 2, 3])) 

word: 3 

""" 

d = self.delta() 

if len(d) == 0: 

return d 

if W is None: 

W = d.parent() 

if d[0] != W.alphabet().last(): 

d = d[1:] 

return d 

 

def delta_derivate_right(self, W=None): 

r""" 

Return the right derivative under delta for ``self``. 

 

EXAMPLES:: 

 

sage: W = Words('12') 

sage: W('12211').delta_derivate_right() 

word: 122 

sage: W('1').delta_derivate_right(Words([1])) 

word: 1 

sage: W('2112').delta_derivate_right() 

word: 12 

sage: W('2211').delta_derivate_right() 

word: 22 

sage: W('112').delta_derivate_right() 

word: 2 

sage: W('11222').delta_derivate_right(Words([1, 2, 3])) 

word: 23 

""" 

d = self.delta() 

if len(d) == 0: 

return d 

if W is None: 

W = d.parent() 

if d[-1] != W.alphabet().last(): 

d = d[:-1] 

return d 

 

def phi(self): 

r""" 

Apply the phi function to ``self`` and return the result. This is 

the word obtained by taking the first letter of the words obtained 

by iterating delta on ``self``. 

 

OUTPUT: 

 

a word -- the result of the phi function 

 

EXAMPLES:: 

 

sage: W = Words([1, 2]) 

sage: W([2,2,1,1,2,1,2,2,1,2,2,1,1,2]).phi() 

word: 222222 

sage: W([2,1,2,2,1,2,2,1,2,1]).phi() 

word: 212113 

sage: W().phi() 

word: 

sage: Word([2,1,2,2,1,2,2,1,2,1]).phi() 

word: 212113 

sage: Word([2,3,1,1,2,1,2,3,1,2,2,3,1,2]).phi() 

word: 21215 

sage: Word("aabbabaabaabba").phi() 

word: a22222 

sage: w = Word([2,3,1,1,2,1,2,3,1,2,2,3,1,2]) 

 

REFERENCES: 

 

- S. Brlek, A. Ladouceur, A note on differentiable palindromes, 

Theoret. Comput. Sci. 302 (2003) 167--178. 

- S. Brlek, S. Dulucq, A. Ladouceur, L. Vuillon, Combinatorial 

properties of smooth infinite words, Theoret. Comput. Sci. 352 

(2006) 306--317. 

""" 

if self.is_empty(): 

return self 

v = [self[0]] 

m = self.delta() 

while m.length() > 1: 

v.append(m[0]) 

m = m.delta() 

v.append(m[0]) 

return Words()(v) 

 

def phi_inv(self, W=None): 

r""" 

Apply the inverse of the phi function to ``self``. 

 

INPUT: 

 

- ``self`` -- a word over the integers 

- ``W`` -- a parent object of words defined over integers 

 

OUTPUT: 

 

a word -- the inverse of the phi function 

 

EXAMPLES:: 

 

sage: W = Words([1, 2]) 

sage: W([2, 2, 2, 2, 1, 2]).phi_inv() 

word: 22112122 

sage: W([2, 2, 2]).phi_inv(Words([2, 3])) 

word: 2233 

""" 

if W is None: 

W = self.parent() 

if self.is_empty(): 

return W() 

v = self.parent()((self[-1],), check=False) 

for i in range(self.length()-2, -1, -1): 

v = v.delta_inv(W, self[i]) 

return v 

 

def _phi_inv_tab(self, tab): 

r""" 

Specialized version of ``phi_inv()`` for long or incremental words. 

 

TESTS:: 

 

sage: Words([1, 2])([1, 1, 2, 2])._phi_inv_tab([2]) 

word: 12211 

""" 

res = self.delta_inv(s=tab[0]) 

res = res[1:] 

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

res = res.delta_inv(s=tab[i]) 

return res 

 

def is_smooth_prefix(self): 

r""" 

Return ``True`` if ``self`` is the prefix of a smooth word, and ``False`` 

otherwise. 

 

Let `A_k = \{1, \ldots ,k\}`, `k \geq 2`. An infinite word `w` in 

`A_k^\omega` is said to be *smooth* if and only if for all positive 

integers `m`, `\Delta^m(w)` is in `A_k^\omega`, where `\Delta(w)` is 

the word obtained from `w` by composing the length of consecutive 

runs of the same letter in `w`. See for instance [1] and [2]. 

 

INPUT: 

 

- ``self`` -- must be a word over the integers to get something other 

than ``False`` 

 

OUTPUT: 

 

boolean -- whether ``self`` is a smooth prefix or not 

 

EXAMPLES:: 

 

sage: W = Words([1, 2]) 

sage: W([1, 1, 2, 2, 1, 2, 1, 1]).is_smooth_prefix() 

True 

sage: W([1, 2, 1, 2, 1, 2]).is_smooth_prefix() 

False 

 

REFERENCES: 

 

- [1] S. Brlek, A. Ladouceur, A note on differentiable palindromes, 

Theoret. Comput. Sci. 302 (2003) 167--178. 

- [2] S. Brlek, S. Dulucq, A. Ladouceur, L. Vuillon, Combinatorial 

properties of smooth infinite words, Theoret. Comput. Sci. 352 

(2006) 306--317. 

""" 

m = self 

W = self.parent() 

while m.length() > 1: 

m = m.delta_derivate_right() 

if not all(a in W.alphabet() for a in m.letters()): 

return False 

return True 

 

def letters(self): 

r""" 

Return the list of letters that appear in this word, listed in the 

order of first appearance. 

 

EXAMPLES:: 

 

sage: Word([0,1,1,0,1,0,0,1]).letters() 

[0, 1] 

sage: Word("cacao").letters() 

['c', 'a', 'o'] 

 

TESTS:: 

 

sage: Word().letters() 

[] 

""" 

seen = set() 

res = [] 

for x in self: 

if x not in seen: 

res.append(x) 

seen.add(x) 

return res 

 

def standard_factorization(self): 

r""" 

Return the standard factorization of ``self``. 

 

The *standard factorization* of a word `w` of length greater than 

`1` is the factorization `w = uv` where `v` is the longest proper 

suffix of `w` that is a Lyndon word. 

 

Note that if `w` is a Lyndon word of length greater than `1` with 

standard factorization `w = uv`, then `u` and `v` are also Lyndon 

words and `u < v`. 

 

See for instance [1], [2] and [3]. 

 

INPUT: 

 

- ``self`` -- finite word of length greater than `1` 

 

OUTPUT: 

 

`2`-tuple `(u, v)` 

 

EXAMPLES:: 

 

sage: Words('01')('0010110011').standard_factorization() 

(word: 001011, word: 0011) 

sage: Words('123')('1223312').standard_factorization() 

(word: 12233, word: 12) 

sage: Word([3,2,1]).standard_factorization() 

(word: 32, word: 1) 

 

:: 

 

sage: w = Word('0010110011',alphabet='01') 

sage: w.standard_factorization() 

(word: 001011, word: 0011) 

sage: w = Word('0010110011',alphabet='10') 

sage: w.standard_factorization() 

(word: 001011001, word: 1) 

sage: w = Word('1223312',alphabet='123') 

sage: w.standard_factorization() 

(word: 12233, word: 12) 

 

TESTS:: 

 

sage: w = Word() 

sage: w.standard_factorization() 

Traceback (most recent call last): 

... 

ValueError: Standard factorization not defined on words of 

length less than 2 

sage: w = Word('a') 

sage: w.standard_factorization() 

Traceback (most recent call last): 

... 

ValueError: Standard factorization not defined on words of 

length less than 2 

 

REFERENCES: 

 

- [1] K.-T. Chen, R.H. Fox, R.C. Lyndon, Free differential calculus, 

IV. The quotient groups of the lower central series, Ann. of Math. 

68 (1958) 81--95. 

- [2] J.-P. Duval, Factorizing words over an ordered alphabet, 

J. Algorithms 4 (1983) 363--381. 

- [3] M. Lothaire, Algebraic Combinatorics On Words, vol. 90 of 

Encyclopedia of Mathematics and its Applications, Cambridge 

University Press, U.K., 2002. 

""" 

selflen = self.length() 

if selflen < 2: 

raise ValueError("Standard factorization not defined on" 

" words of length less than 2") 

for l in range(1, selflen): 

suff = self[l:] 

if suff.is_lyndon(): 

return self[:l], suff 

 

def apply_permutation_to_positions(self, permutation): 

r""" 

Return the word obtained by permuting the positions of the letters 

in ``self`` according to the permutation ``permutation``. 

 

EXAMPLES:: 

 

sage: w = Words('abcd')('abcd') 

sage: w.apply_permutation_to_positions([2,1,4,3]) 

word: badc 

sage: u = Words('dabc')('abcd') 

sage: u.apply_permutation_to_positions([2,1,4,3]) 

word: badc 

sage: w.apply_permutation_to_positions(Permutation([2,1,4,3])) 

word: badc 

sage: w.apply_permutation_to_positions(PermutationGroupElement([2,1,4,3])) 

word: badc 

sage: Word([1,2,3,4]).apply_permutation_to_positions([3,4,2,1]) 

word: 3421 

""" 

from sage.combinat.permutation import Permutation 

from sage.groups.perm_gps.permgroup_element import PermutationGroupElement 

if not isinstance(permutation, Permutation): 

if isinstance(permutation, PermutationGroupElement): 

permutation = Permutation(permutation.domain()) 

else: 

permutation = Permutation(permutation) 

return self.parent()(permutation.action(self), check=False) 

 

def apply_permutation_to_letters(self, permutation): 

r""" 

Return the word obtained by applying the permutation 

``permutation`` of the alphabet of ``self`` to each letter of 

``self``. 

 

EXAMPLES:: 

 

sage: w = Words('abcd')('abcd') 

sage: p = [2,1,4,3] 

sage: w.apply_permutation_to_letters(p) 

word: badc 

sage: u = Words('dabc')('abcd') 

sage: u.apply_permutation_to_letters(p) 

word: dcba 

sage: w.apply_permutation_to_letters(Permutation(p)) 

word: badc 

sage: w.apply_permutation_to_letters(PermutationGroupElement(p)) 

word: badc 

""" 

from sage.combinat.permutation import Permutation 

from sage.groups.perm_gps.permgroup_element import PermutationGroupElement 

if not isinstance(permutation, Permutation): 

if isinstance(permutation, PermutationGroupElement): 

permutation = Permutation(permutation.domain()) 

else: 

permutation = Permutation(permutation) 

alphabet = self.parent().alphabet() 

morphism = dict(zip(alphabet, permutation.action(alphabet))) 

return self.apply_morphism(morphism) 

 

def colored_vector(self, x=0, y=0, width='default', height=1, cmap='hsv', thickness=1, label=None): 

r""" 

Return a vector (Graphics object) illustrating ``self``. Each letter 

is represented by a coloured rectangle. 

 

If the parent of ``self`` is a class of words over a finite alphabet, 

then each letter in the alphabet is assigned a unique colour, and 

this colour will be the same every time this method is called. This 

is especially useful when plotting and comparing words defined on 

the same alphabet. 

 

If the alphabet is infinite, then the letters appearing in the word 

are used as the alphabet. 

 

INPUT: 

 

- ``x`` -- (default: ``0``) bottom left x-coordinate of the vector 

- ``y`` -- (default: ``0``) bottom left y-coordinate of the vector 

- ``width`` -- (default: ``'default'``) width of the vector. By default, 

the width is the length of ``self``. 

- ``height`` -- (default: ``1``) height of the vector 

- ``thickness`` -- (default: ``1``) thickness of the contour 

- ``cmap`` -- (default: ``'hsv'``) color map; for available color map names 

type: ``import matplotlib.cm; list(matplotlib.cm.datad)`` 

- ``label`` -- string (default: ``None``) a label to add on the colored vector 

 

OUTPUT: 

 

Graphics 

 

EXAMPLES:: 

 

sage: Word(range(20)).colored_vector() 

Graphics object consisting of 21 graphics primitives 

sage: Word(range(100)).colored_vector(0,0,10,1) 

Graphics object consisting of 101 graphics primitives 

sage: Words(range(100))(range(10)).colored_vector() 

Graphics object consisting of 11 graphics primitives 

sage: w = Word('abbabaab') 

sage: w.colored_vector() 

Graphics object consisting of 9 graphics primitives 

sage: w.colored_vector(cmap='autumn') 

Graphics object consisting of 9 graphics primitives 

sage: Word(range(20)).colored_vector(label='Rainbow') 

Graphics object consisting of 23 graphics primitives 

 

When two words are defined under the same parent, same letters are 

mapped to same colors:: 

 

sage: W = Words(range(20)) 

sage: w = W(range(20)) 

sage: y = W(range(10,20)) 

sage: y.colored_vector(y=1, x=10) + w.colored_vector() 

Graphics object consisting of 32 graphics primitives 

 

TESTS: 

 

The empty word:: 

 

sage: Word().colored_vector() 

Graphics object consisting of 1 graphics primitive 

sage: Word().colored_vector(label='empty') 

Graphics object consisting of 3 graphics primitives 

 

Unknown cmap:: 

 

sage: Word(range(100)).colored_vector(cmap='jolies') 

Traceback (most recent call last): 

... 

RuntimeError: Color map jolies not known 

sage: Word(range(100)).colored_vector(cmap='__doc__') 

Traceback (most recent call last): 

... 

RuntimeError: Color map __doc__ not known 

""" 

#Recognize the color map 

import matplotlib.cm as cm 

from matplotlib.colors import LinearSegmentedColormap as C 

key_error = False 

try: 

mpl_cmap = cm.__dict__[cmap] 

except KeyError: 

key_error = True 

 

if key_error or not isinstance(mpl_cmap, C): 

possibilities = ', '.join([str(x) for x in cm.__dict__.keys() if \ 

isinstance(cm.__dict__[x], C)]) 

import sage.misc.misc 

sage.misc.misc.verbose("The possible color maps include: %s"%possibilities, level=0) 

raise RuntimeError("Color map %s not known"%cmap) 

 

#Drawing the colored vector... 

from sage.plot.plot import polygon,line,text 

 

#The default width of the vector 

if width == 'default': 

width = self.length() 

 

#The black frame of the vector 

ymax = y + height 

L = [(x,y), (x+width,y), (x+width,ymax), (x,ymax), (x,y)] 

rep = line(L, rgbcolor=(0,0,0), thickness=thickness) 

 

#The label 

if not label is None: 

hl = height/2.0 # height of the label rectangle 

ymax2 = ymax + hl 

rep += text(str(label), (x+width/2.0, ymax + hl/2.0), rgbcolor=(1,0,0)) 

L = [(x,ymax), (x+width,ymax), (x+width,ymax2), (x,ymax2), (x,ymax)] 

rep += line(L, rgbcolor=(0,0,0), thickness=thickness) 

 

#base : the width of each rectangle 

base = width / float(self.length()) if not self.is_empty() else None 

 

#A colored rectangle for each letter 

dim = self.parent().alphabet().cardinality() 

if dim is Infinity: 

ordered_alphabet = sorted(self.letters(), 

key=self.parent().sortkey_letters) 

dim = float(len(ordered_alphabet)) 

else: 

ordered_alphabet = self.parent().alphabet() 

dim = float(self.parent().alphabet().cardinality()) 

letter_to_integer_dict = dict((a,i) for (i,a) in 

enumerate(ordered_alphabet)) 

xp = x 

for a in self: 

i = letter_to_integer_dict[a] 

xq = xp + base 

L = [(xp,y), (xq,y), (xq,ymax), (xp,ymax) ] 

rgbcolor = mpl_cmap( i / dim ) [:3] 

rep += polygon(L, rgbcolor = rgbcolor) 

xp = xq 

rep.axes(False) 

return rep 

 

def is_square(self): 

r""" 

Return ``True`` if ``self`` is a square, and ``False`` otherwise. 

 

EXAMPLES:: 

 

sage: Word([1,0,0,1]).is_square() 

False 

sage: Word('1212').is_square() 

True 

sage: Word('1213').is_square() 

False 

sage: Word('12123').is_square() 

False 

sage: Word().is_square() 

True 

""" 

if self.length() % 2 != 0: 

return False 

else: 

l = self.length() // 2 

return self[:l] == self[l:] 

 

def is_square_free(self): 

r""" 

Return ``True`` if ``self`` does not contain squares, and ``False`` 

otherwise. 

 

EXAMPLES:: 

 

sage: Word('12312').is_square_free() 

True 

sage: Word('31212').is_square_free() 

False 

sage: Word().is_square_free() 

True 

 

TESTS: 

 

We make sure that :trac:`8490` is fixed:: 

 

sage: Word('11').is_square_free() 

False 

sage: Word('211').is_square_free() 

False 

sage: Word('3211').is_square_free() 

False 

""" 

L = self.length() 

if L < 2: 

return True 

for start in range(0, L-1): 

for end in range(start+2, L+1, 2): 

if self[start:end].is_square(): 

return False 

return True 

 

def is_cube(self): 

r""" 

Return ``True`` if ``self`` is a cube, and ``False`` otherwise. 

 

EXAMPLES:: 

 

sage: Word('012012012').is_cube() 

True 

sage: Word('01010101').is_cube() 

False 

sage: Word().is_cube() 

True 

sage: Word('012012').is_cube() 

False 

""" 

if self.length() % 3 != 0: 

return False 

l = self.length() // 3 

return self[:l] == self[l:2*l] == self[2*l:] 

 

def is_cube_free(self): 

r""" 

Return ``True`` if ``self`` does not contain cubes, and ``False`` otherwise. 

 

EXAMPLES:: 

 

sage: Word('12312').is_cube_free() 

True 

sage: Word('32221').is_cube_free() 

False 

sage: Word().is_cube_free() 

True 

 

TESTS: 

 

We make sure that :trac:`8490` is fixed:: 

 

sage: Word('111').is_cube_free() 

False 

sage: Word('2111').is_cube_free() 

False 

sage: Word('32111').is_cube_free() 

False 

""" 

L = self.length() 

if L < 3: 

return True 

for start in range(0, L - 2): 

for end in range(start+3, L+1, 3): 

if self[start:end].is_cube(): 

return False 

return True 

 

def to_monoid_element(self): 

""" 

Return ``self`` as an element of the free monoid with the same alphabet 

as ``self``. 

 

EXAMPLES:: 

 

sage: w = Word('aabb') 

sage: w.to_monoid_element() 

a^2*b^2 

sage: W = Words('abc') 

sage: w = W(w) 

sage: w.to_monoid_element() 

a^2*b^2 

 

TESTS: 

 

Check that ``w == w.to_monoid_element().to_word()``:: 

 

sage: all(w.to_monoid_element().to_word() == w for i in range(6) for w in Words('abc', i)) 

True 

""" 

from sage.monoids.free_monoid import FreeMonoid 

try: 

l = list(self.parent().alphabet()) 

except AttributeError: 

l = self.letters() 

M = FreeMonoid(len(l), l) 

return M(self) 

 

def is_christoffel(self): 

r""" 

Return ``True`` if ``self`` is a Christoffel word, and ``False`` otherwise. 

 

The *Christoffel word* of slope `p/q` is obtained from the Cayley 

graph of `\ZZ/(p+q)\ZZ` with generator `q` as follows. If `u 

\rightarrow v` is an edge in the Cayley graph, then, `v = u + p 

\mod{p+q}`. Let `a`,`b` be the alphabet of `w`. Label the edge 

`u \rightarrow v` by `a` if `u < v` and `b` otherwise. The Christoffel 

word is the word obtained by reading the edge labels along the cycle 

beginning from `0`. 

 

Equivalently, `w` is a Christoffel word iff `w` is a symmetric 

non-empty word and `w[1:n-1]` is a palindrome. 

 

See for instance [1]_ and [2]_. 

 

INPUT: 

 

- ``self`` -- word 

 

OUTPUT: 

 

boolean -- ``True`` if ``self`` is a Christoffel word, 

``False`` otherwise. 

 

EXAMPLES:: 

 

sage: Word('00100101').is_christoffel() 

True 

sage: Word('aab').is_christoffel() 

True 

sage: Word().is_christoffel() 

False 

sage: Word('123123123').is_christoffel() 

False 

sage: Word('00100').is_christoffel() 

False 

sage: Word('0').is_christoffel() 

True 

 

TESTS:: 

 

sage: words.LowerChristoffelWord(5,4).is_christoffel() 

True 

sage: words.UpperChristoffelWord(5,4).is_christoffel() 

True 

sage: Word('aaaaaaaaa').is_christoffel() 

False 

 

REFERENCES: 

 

.. [1] Jean Berstel. Sturmian and episturmian words (a survey of 

some recent results). In S. Bozapalidis and G. Rahonis, editors, 

CAI 2007,volume 4728 of Lecture Notes in Computer Science, 

pages 23-47. Springer-Verlag, 2007. 

.. [2] \J. Berstel, A. Lauve, C. R., F. Saliola, Combinatorics on 

words: Christoffel words and repetitions in words, CRM Monograph 

Series, 27. American Mathematical Society, Providence, RI, 2009. 

xii+147 pp. ISBN: 978-0-8218-4480-9 

 

""" 

if len(self) == 0 or len(self.letters()) > 2 or (self.is_palindrome() and len(self) > 1): 

return False 

elif self.is_symmetric() and self[1:len(self) - 1].is_palindrome(): 

return True 

else: 

return False 

 

 

####################################################################### 

 

class CallableFromListOfWords(tuple): 

r""" 

A class to create a callable from a list of words. The concatenation of 

a list of words is obtained by creating a word from this callable. 

""" 

def __new__(cls, words): 

r""" 

TESTS:: 

 

sage: from sage.combinat.words.finite_word import CallableFromListOfWords 

sage: w,u,x = Word([1,2,3]),Word([4,5]),Word([6,7,8]) 

sage: f = CallableFromListOfWords([w,u,x]); f 

(word: 123, word: 45, word: 678) 

sage: f == loads(dumps(f)) 

True 

""" 

l = [] 

for w in words: 

from .word_infinite_datatypes import WordDatatype_callable 

if isinstance(w, WordDatatype_callable) and \ 

isinstance(w._func, CallableFromListOfWords): 

l.extend(w._func) 

else: 

l.append(w) 

return tuple.__new__(cls, l) 

 

def __call__(self, i): 

r""" 

Return the character at position ``i``. 

 

TESTS:: 

 

sage: from sage.combinat.words.finite_word import CallableFromListOfWords 

sage: w,u,x = Word([1,2,3]),Word([4,5]),Word([6,7,8]) 

sage: f = CallableFromListOfWords([w,u,x]) 

sage: [f(i) for i in range(8)] 

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

""" 

j = i 

for c in self: 

if (j - c.length() < 0): 

return c[j] 

j -= c.length() 

raise IndexError("index (=%s) out of range" % i) 

 

class Factorization(list): 

r""" 

A list subclass having a nicer representation for factorization of words. 

 

TESTS:: 

 

sage: f = sage.combinat.words.finite_word.Factorization() 

sage: f == loads(dumps(f)) 

True 

""" 

def __repr__(self): 

r""" 

Return a string representation of the object. 

 

TESTS:: 

 

sage: sage.combinat.words.finite_word.Factorization() 

() 

sage: sage.combinat.words.finite_word.Factorization([Word('ab'), Word('ba')]) 

(ab, ba) 

""" 

return '(%s)' % ', '.join(w.string_rep() for w in self) 

 

####################################################################### 

 

def evaluation_dict(w): 

r""" 

Return a dictionary keyed by the letters occurring in ``w`` with 

values the number of occurrences of the letter. 

 

INPUT: 

 

- ``w`` -- a word 

 

TESTS:: 

 

sage: from sage.combinat.words.finite_word import evaluation_dict 

sage: evaluation_dict([2,1,4,2,3,4,2]) 

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

sage: evaluation_dict('badbcdb') 

{'a': 1, 'b': 3, 'c': 1, 'd': 2} 

sage: evaluation_dict([]) 

{} 

 

:: 

 

sage: evaluation_dict('1213121') # keys appear in random order 

{'1': 4, '2': 2, '3': 1} 

 

""" 

d = defaultdict(int) 

for a in w: 

d[a] += 1 

return dict(d)