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

r""" 

Subsets 

 

The set of subsets of a finite set. The set can be given as a list or a Set 

or else as an integer `n` which encodes the set `\{1,2,...,n\}`. 

See :class:`Subsets` for more information and examples. 

 

AUTHORS: 

 

- Mike Hansen: initial version 

 

- Florent Hivert (2009/02/06): doc improvements + new methods 

""" 

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

# Copyright (C) 2007 Mike Hansen <mhansen@gmail.com>, 

# 2014 Vincent Delecroix <20100.delecroix@gmail.com>, 

# 

# Distributed under the terms of the GNU General Public License (GPL) 

# 

# This code is distributed in the hope that it will be useful, 

# but WITHOUT ANY WARRANTY; without even the implied warranty of 

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 

# General Public License for more details. 

# 

# The full text of the GPL is available at: 

# 

# http://www.gnu.org/licenses/ 

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

from __future__ import print_function, absolute_import 

 

import six 

from six.moves import range 

import sage.misc.prandom as rnd 

import itertools 

 

from sage.categories.sets_cat import EmptySetError, Sets 

from sage.categories.enumerated_sets import EnumeratedSets 

from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets 

 

from sage.structure.parent import Parent 

from sage.structure.element import Element 

 

from sage.sets.set import Set, Set_object_enumerated 

from sage.arith.all import binomial 

from sage.rings.integer_ring import ZZ 

from sage.rings.integer import Integer 

from . import combination 

 

ZZ_0 = ZZ.zero() 

 

def Subsets(s, k=None, submultiset=False): 

""" 

Return the combinatorial class of the subsets of the finite set 

``s``. The set can be given as a list, Set or any iterable 

convertible to a set. Alternatively, a non-negative integer `n` 

can be provided in place of ``s``; in this case, the result is 

the combinatorial class of the subsets of the set 

`\{1,2,\dots,n\}` (i.e. of the Sage ``range(1,n+1)``). 

 

A second optional parameter ``k`` can be given. In this case, 

``Subsets`` returns the combinatorial class of subsets of ``s`` 

of size ``k``. 

 

.. WARNING:: 

 

The subsets are returned as Sets. Do not assume that 

these Sets are ordered; they often are not! 

(E.g., ``Subsets(10).list()[619]`` returns 

``{10, 4, 5, 6, 7}`` on my system.) 

See :class:`SubsetsSorted` for a similar class which 

returns the subsets as sorted tuples. 

 

Finally the option ``submultiset`` allows one to deal with sets with 

repeated elements, usually called multisets. The method then 

returns the class of all multisets in which every element is 

contained at most as often as it is contained in ``s``. These 

multisets are encoded as lists. 

 

EXAMPLES:: 

 

sage: S = Subsets([1, 2, 3]); S 

Subsets of {1, 2, 3} 

sage: S.cardinality() 

8 

sage: S.first() 

{} 

sage: S.last() 

{1, 2, 3} 

sage: S.random_element() # random 

{2} 

sage: S.list() 

[{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}] 

 

Here is the same example where the set is given as an integer:: 

 

sage: S = Subsets(3) 

sage: S.list() 

[{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}] 

 

We demonstrate various the effect of the various options:: 

 

sage: S = Subsets(3, 2); S 

Subsets of {1, 2, 3} of size 2 

sage: S.list() 

[{1, 2}, {1, 3}, {2, 3}] 

 

sage: S = Subsets([1, 2, 2], submultiset=True); S 

SubMultiset of [1, 2, 2] 

sage: S.list() 

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

 

sage: S = Subsets([1, 2, 2, 3], 3, submultiset=True); S 

SubMultiset of [1, 2, 2, 3] of size 3 

sage: S.list() 

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

 

sage: S = Subsets(['a','b','a','b'], 2, submultiset=True); S.list() 

[['a', 'a'], ['a', 'b'], ['b', 'b']] 

 

 

And it is possible to play with subsets of subsets:: 

 

sage: S = Subsets(3) 

sage: S2 = Subsets(S); S2 

Subsets of Subsets of {1, 2, 3} 

sage: S2.cardinality() 

256 

sage: it = iter(S2) 

sage: [next(it) for _ in range(8)] 

[{}, {{}}, {{1}}, {{2}}, {{3}}, {{1, 2}}, {{1, 3}}, {{2, 3}}] 

sage: S2.random_element() # random 

{{2}, {1, 2, 3}, {}} 

sage: [S2.unrank(k) for k in range(256)] == S2.list() 

True 

 

sage: S3 = Subsets(S2) 

sage: S3.cardinality() 

115792089237316195423570985008687907853269984665640564039457584007913129639936 

sage: S3.unrank(14123091480) 

{{{1, 3}, {1, 2, 3}, {2}, {1}}, 

{{2}, {1, 2, 3}, {}, {1, 2}}, 

{}, 

{{2}, {1, 2, 3}, {}, {3}, {1, 2}}, 

{{1, 2, 3}, {}, {1}}, {{2}, {2, 3}, {}, {1, 2}}} 

 

sage: T = Subsets(S2, 10) 

sage: T.cardinality() 

278826214642518400 

sage: T.unrank(1441231049) 

{{{3}, {1, 2}, {}, {2, 3}, {1}, {1, 3}, ..., {{2, 3}, {}}, {{}}} 

""" 

if k is not None: 

k = Integer(k) 

 

if isinstance(s, (int, Integer)): 

if s < 0: 

raise ValueError("s must be non-negative") 

from sage.sets.integer_range import IntegerRange 

s = IntegerRange(1,s+1) 

 

# if len(Set(s)) != len(s): 

# multi = True 

 

if k is None: 

if submultiset: 

return SubMultiset_s(s) 

else: 

return Subsets_s(s) 

else: 

if submultiset: 

return SubMultiset_sk(s, k) 

else: 

return Subsets_sk(s, k) 

 

class Subsets_s(Parent): 

r""" 

Subsets of a given set. 

 

EXAMPLES:: 

 

sage: S = Subsets(4); S 

Subsets of {1, 2, 3, 4} 

sage: S.cardinality() 

16 

sage: Subsets(4).list() 

[{}, {1}, {2}, {3}, {4}, 

{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}, 

{1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}, 

{1, 2, 3, 4}] 

 

sage: S = Subsets(Subsets(Subsets(GF(3)))); S 

Subsets of Subsets of Subsets of Finite Field of size 3 

sage: S.cardinality() 

115792089237316195423570985008687907853269984665640564039457584007913129639936 

sage: S.unrank(3149254230) 

{{{1, 2}, {0, 1, 2}, {0, 2}, {0, 1}}, 

{{1, 2}, {}, {0, 2}, {1}, {0, 1, 2}, {2}}, 

{{1, 2}, {0}}, {{1, 2}, {0, 1}, {0, 1, 2}, {1}}, 

{{0, 2}, {1}}} 

""" 

# TODO: Set_object_enumerated does not inherit from Element... so we set 

# directly element_class as Set_object_enumerated 

# (see also below the failed test in __init__) 

element_class = Set_object_enumerated 

 

def __init__(self, s): 

""" 

TESTS:: 

 

sage: s = Subsets(Set([1])) 

sage: e = s.first() 

sage: isinstance(e, s.element_class) 

True 

 

In the following "_test_elements" is temporarily disabled 

until :class:`sage.sets.set.Set_object_enumerated` objects 

pass the category tests:: 

 

sage: S = Subsets([1,2,3]) 

sage: TestSuite(S).run(skip=["_test_elements"]) 

 

sage: S = sage.sets.set.Set_object_enumerated([1,2]) 

sage: TestSuite(S).run() # todo: not implemented 

""" 

Parent.__init__(self, category=EnumeratedSets().Finite()) 

if s not in EnumeratedSets(): 

from sage.misc.misc import uniq 

from sage.sets.finite_enumerated_set import FiniteEnumeratedSet 

s = list(s) 

us = uniq(s) 

if len(us) == len(s): 

s = FiniteEnumeratedSet(s) 

else: 

s = FiniteEnumeratedSet(us) 

self._s = s 

 

@property 

def _ls(self): 

r""" 

The list of elements of the underlying set. 

 

We try as much as possible to *not* use it. 

 

TESTS:: 

 

sage: S = Subsets([1,2,3,4]) 

sage: S._ls 

[1, 2, 3, 4] 

""" 

return self._s.list() 

 

def underlying_set(self): 

r""" 

Return the set of elements. 

 

EXAMPLES:: 

 

sage: Subsets(GF(13)).underlying_set() 

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} 

""" 

return self.element_class(self._s) 

 

def __eq__(self, other): 

r""" 

Equality test 

 

TESTS:: 

 

sage: Subsets([0,1,2]) == Subsets([1,2,3]) 

False 

sage: Subsets([0,1,2]) == Subsets([0,1,2]) 

True 

sage: Subsets([0,1,2]) == Subsets([0,1,2],2) 

False 

""" 

if self.__class__ != other.__class__: 

return False 

return self._s == other._s 

 

def __ne__(self, other): 

r""" 

Difference test 

 

TESTS:: 

 

sage: Subsets([0,1,2]) != Subsets([1,2,3]) 

True 

sage: Subsets([0,1,2]) != Subsets([0,1,2]) 

False 

sage: Subsets([0,1,2]) != Subsets([0,1,2],2) 

True 

""" 

return not self == other 

 

def _repr_(self): 

""" 

TESTS:: 

 

sage: repr(Subsets([1,2,3])) #indirect doctest 

'Subsets of {1, 2, 3}' 

""" 

return "Subsets of {}".format(self._s) 

 

def __contains__(self, value): 

""" 

TESTS:: 

 

sage: S = Subsets([1,2,3]) 

sage: Set([1,2]) in S 

True 

sage: Set([1,4]) in S 

False 

sage: Set([]) in S 

True 

sage: 2 in S 

False 

""" 

if value not in Sets(): 

return False 

return all(v in self._s for v in value) 

 

def cardinality(self): 

r""" 

Return the number of subsets of the set ``s``. 

 

This is given by `2^{|s|}`. 

 

EXAMPLES:: 

 

sage: Subsets(Set([1,2,3])).cardinality() 

8 

sage: Subsets([1,2,3,3]).cardinality() 

8 

sage: Subsets(3).cardinality() 

8 

""" 

return Integer(1) << self._s.cardinality() 

 

__len__ = cardinality 

 

def first(self): 

""" 

Returns the first subset of ``s``. Since we aren't restricted to 

subsets of a certain size, this is always the empty set. 

 

EXAMPLES:: 

 

sage: Subsets([1,2,3]).first() 

{} 

sage: Subsets(3).first() 

{} 

""" 

return self.element_class([]) 

 

def last(self): 

""" 

Return the last subset of ``s``. Since we aren't restricted to 

subsets of a certain size, this is always the set ``s`` itself. 

 

EXAMPLES:: 

 

sage: Subsets([1,2,3]).last() 

{1, 2, 3} 

sage: Subsets(3).last() 

{1, 2, 3} 

""" 

return self.element_class(self._s) 

 

def __iter__(self): 

""" 

Iterate through the subsets of ``s``. 

 

EXAMPLES:: 

 

sage: [sub for sub in Subsets(Set([1,2,3]))] 

[{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}] 

sage: [sub for sub in Subsets(3)] 

[{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}] 

sage: [sub for sub in Subsets([1,2,3,3])] 

[{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}] 

 

""" 

k = ZZ_0 

while k <= self._s.cardinality(): 

for ss in Subsets_sk(self._s, k)._fast_iterator(): 

yield self.element_class(ss) 

k += 1 

 

def random_element(self): 

""" 

Return a random element of the class of subsets of ``s`` (in other 

words, a random subset of ``s``). 

 

EXAMPLES:: 

 

sage: Subsets(3).random_element() # random 

{2} 

sage: Subsets([4,5,6]).random_element() # random 

{5} 

 

sage: S = Subsets(Subsets(Subsets([0,1,2]))) 

sage: S.cardinality() 

115792089237316195423570985008687907853269984665640564039457584007913129639936 

sage: s = S.random_element() 

sage: s # random 

{{{1, 2}, {2}, {0}, {1}}, {{1, 2}, {0, 1, 2}, {0, 2}, {0}, {0, 1}}, ..., {{1, 2}, {2}, {1}}, {{2}, {0, 2}, {}, {1}}} 

sage: s in S 

True 

""" 

k = ZZ.random_element(0, self.cardinality()) 

return self.unrank(k) 

 

def rank(self, sub): 

""" 

Return the rank of ``sub`` as a subset of ``s``. 

 

EXAMPLES:: 

 

sage: Subsets(3).rank([]) 

0 

sage: Subsets(3).rank([1,2]) 

4 

sage: Subsets(3).rank([1,2,3]) 

7 

sage: Subsets(3).rank([2,3,4]) 

Traceback (most recent call last): 

... 

ValueError: {2, 3, 4} is not a subset of {1, 2, 3} 

""" 

if sub not in Sets(): 

ssub = Set(sub) 

if len(sub) != len(ssub): 

raise ValueError("repeated elements in {}".format(sub)) 

sub = ssub 

 

try: 

index_list = sorted(self._s.rank(x) for x in sub) 

except (ValueError,IndexError): 

raise ValueError("{} is not a subset of {}".format( 

Set(sub), self._s)) 

 

n = self._s.cardinality() 

r = sum(binomial(n,i) for i in range(len(index_list))) 

return r + combination.rank(index_list,n) 

 

def unrank(self, r): 

""" 

Return the subset of ``s`` that has rank ``k``. 

 

EXAMPLES:: 

 

sage: Subsets(3).unrank(0) 

{} 

sage: Subsets([2,4,5]).unrank(1) 

{2} 

sage: Subsets([1,2,3]).unrank(257) 

Traceback (most recent call last): 

... 

IndexError: index out of range 

 

""" 

r = Integer(r) 

if r >= self.cardinality() or r < 0: 

raise IndexError("index out of range") 

else: 

k = ZZ_0 

n = self._s.cardinality() 

bin = Integer(1) 

while r >= bin: 

r -= bin 

k += 1 

bin = binomial(n,k) 

return self.element_class([self._s.unrank(i) for i in combination.from_rank(r, n, k)]) 

 

def __call__(self, el): 

r""" 

Workaround for returning non elements. 

 

See the extensive documentation in 

:meth:`sage.sets.finite_enumerated_set.FiniteEnumeratedSet.__call__`. 

 

TESTS:: 

 

sage: Subsets(['a','b','c'])(['a','b']) # indirect doctest 

{'a', 'b'} 

""" 

if not isinstance(el, Element): 

return self._element_constructor_(el) 

else: 

return Parent.__call__(self, el) 

 

def _element_constructor_(self,X): 

""" 

TESTS:: 

 

sage: S3 = Subsets(3); S3([1,2]) #indirect doctest 

{1, 2} 

sage: S3([0,1,2]) 

Traceback (most recent call last): 

... 

ValueError: {0, 1, 2} not in Subsets of {1, 2, 3} 

""" 

e = self.element_class(X) 

if e not in self: 

raise ValueError("{} not in {}".format(e,self)) 

return e 

 

def an_element(self): 

""" 

Returns an example of subset. 

 

EXAMPLES:: 

 

sage: Subsets(0).an_element() 

{} 

sage: Subsets(3).an_element() 

{1, 2} 

sage: Subsets([2,4,5]).an_element() 

{2, 4} 

""" 

return self.unrank(self.cardinality() // 2) 

 

class Subsets_sk(Subsets_s): 

r""" 

Subsets of fixed size of a set. 

 

EXAMPLES:: 

 

sage: S = Subsets([0,1,2,5,7], 3); S 

Subsets of {0, 1, 2, 5, 7} of size 3 

sage: S.cardinality() 

10 

sage: S.first(), S.last() 

({0, 1, 2}, {2, 5, 7}) 

sage: S.random_element() # random 

{0, 5, 7} 

sage: S([0,2,7]) 

{0, 2, 7} 

sage: S([0,3,5]) 

Traceback (most recent call last): 

... 

ValueError: {0, 3, 5} not in Subsets of {0, 1, 2, 5, 7} of size 3 

sage: S([0]) 

Traceback (most recent call last): 

... 

ValueError: {0} not in Subsets of {0, 1, 2, 5, 7} of size 3 

""" 

def __init__(self, s, k): 

""" 

TESTS:: 

 

sage: s = Subsets(Set([1])) 

sage: e = s.first() 

sage: isinstance(e, s.element_class) 

True 

 

In the following "_test_elements" is temporarily disabled 

until :class:`sage.sets.set.Set_object_enumerated` objects 

pass the category tests:: 

 

sage: S = Subsets(3,2) 

sage: TestSuite(S).run(skip=["_test_elements"]) 

""" 

Subsets_s.__init__(self, s) 

self._k = Integer(k) 

if self._k < 0: 

raise ValueError("the integer k (={}) should be non-negative".format(k)) 

 

def _repr_(self): 

""" 

TESTS:: 

 

sage: repr(Subsets(3,2)) #indirect doctest 

'Subsets of {1, 2, 3} of size 2' 

""" 

return Subsets_s._repr_(self) + " of size {}".format(self._k) 

 

def __contains__(self, value): 

""" 

TESTS:: 

 

sage: S = Subsets([1,2,3], 2) 

sage: Set([1,2]) in S 

True 

sage: Set([1,4]) in S 

False 

sage: Set([]) in S 

False 

""" 

return len(value) == self._k and Subsets_s.__contains__(self,value) 

 

def __eq__(self, other): 

r""" 

Equality test 

 

TESTS:: 

 

sage: Subsets(5,3) == Subsets(5,3) 

True 

sage: Subsets(4,2) == Subsets(5,2) or Subsets(4,2) == Subsets(4,3) 

False 

""" 

if self.__class__ != other.__class__: 

return False 

return self._s == other._s and self._k == other._k 

 

def __ne__(self, other): 

r""" 

Difference test 

 

TESTS:: 

 

sage: Subsets(5,3) != Subsets(5,3) 

False 

sage: Subsets(4,2) != Subsets(5,2) and Subsets(4,2) != Subsets(4,3) 

True 

""" 

return not self == other 

 

def cardinality(self): 

""" 

EXAMPLES:: 

 

sage: Subsets(Set([1,2,3]), 2).cardinality() 

3 

sage: Subsets([1,2,3,3], 2).cardinality() 

3 

sage: Subsets([1,2,3], 1).cardinality() 

3 

sage: Subsets([1,2,3], 3).cardinality() 

1 

sage: Subsets([1,2,3], 0).cardinality() 

1 

sage: Subsets([1,2,3], 4).cardinality() 

0 

sage: Subsets(3,2).cardinality() 

3 

sage: Subsets(3,4).cardinality() 

0 

""" 

if self._k > self._s.cardinality(): 

return ZZ_0 

return binomial(self._s.cardinality(), self._k) 

 

__len__ = cardinality 

 

def first(self): 

""" 

Returns the first subset of s of size k. 

 

EXAMPLES:: 

 

sage: Subsets(Set([1,2,3]), 2).first() 

{1, 2} 

sage: Subsets([1,2,3,3], 2).first() 

{1, 2} 

sage: Subsets(3,2).first() 

{1, 2} 

sage: Subsets(3,4).first() 

Traceback (most recent call last): 

... 

EmptySetError 

""" 

if self._k < 0 or self._k > self._s.cardinality(): 

raise EmptySetError 

else: 

return self.element_class(list(itertools.islice(self._s, self._k))) 

 

def last(self): 

""" 

Returns the last subset of s of size k. 

 

EXAMPLES:: 

 

sage: Subsets(Set([1,2,3]), 2).last() 

{2, 3} 

sage: Subsets([1,2,3,3], 2).last() 

{2, 3} 

sage: Subsets(3,2).last() 

{2, 3} 

sage: Subsets(3,4).last() 

Traceback (most recent call last): 

... 

EmptySetError 

""" 

if self._k > self._s.cardinality(): 

raise EmptySetError 

else: 

return self.element_class([i for i in itertools.islice(reversed(self._s),self._k)]) 

 

def _fast_iterator(self): 

r""" 

Iterate through the subsets of size k if s. 

 

Beware that this function yield tuples and not sets. If you need sets 

use __iter__ 

 

EXAMPLES:: 

 

sage: list(Subsets(range(3), 2)._fast_iterator()) 

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

""" 

return itertools.combinations(self._s, self._k) 

 

def __iter__(self): 

""" 

Iterates through the subsets of s of size k. 

 

EXAMPLES:: 

 

sage: Subsets(Set([1,2,3]), 2).list() 

[{1, 2}, {1, 3}, {2, 3}] 

sage: Subsets([1,2,3,3], 2).list() 

[{1, 2}, {1, 3}, {2, 3}] 

sage: Subsets(3,2).list() 

[{1, 2}, {1, 3}, {2, 3}] 

sage: Subsets(3,3).list() 

[{1, 2, 3}] 

""" 

for x in self._fast_iterator(): 

yield self.element_class(x) 

 

def random_element(self): 

""" 

Return a random element of the class of subsets of ``s`` of size 

``k`` (in other words, a random subset of ``s`` of size ``k``). 

 

EXAMPLES:: 

 

sage: Subsets(3, 2).random_element() 

{1, 2} 

sage: Subsets(3,4).random_element() 

Traceback (most recent call last): 

... 

EmptySetError 

""" 

lset = self._ls 

 

if self._k > len(lset): 

raise EmptySetError 

else: 

return self.element_class(rnd.sample(lset, self._k)) 

 

def rank(self, sub): 

""" 

Return the rank of ``sub`` as a subset of ``s`` of size ``k``. 

 

EXAMPLES:: 

 

sage: Subsets(3,2).rank([1,2]) 

0 

sage: Subsets([2,3,4],2).rank([3,4]) 

2 

sage: Subsets([2,3,4],2).rank([2]) 

Traceback (most recent call last): 

... 

ValueError: {2} is not a subset of length 2 of {2, 3, 4} 

sage: Subsets([2,3,4],4).rank([2,3,4,5]) 

Traceback (most recent call last): 

... 

ValueError: {2, 3, 4, 5} is not a subset of length 4 of {2, 3, 4} 

""" 

sub = Set(sub) 

n = self._s.cardinality() 

 

if self._k != sub.cardinality() or self._k > n: 

raise ValueError("{} is not a subset of length {} of {}".format( 

sub, self._k, self._s)) 

 

try: 

index_list = sorted(self._s.rank(x) for x in sub) 

except ValueError: 

raise ValueError("{} is not a subset of length {} of {}".format( 

sub, self._k, self._s)) 

 

return combination.rank(index_list, n) 

 

def unrank(self, r): 

""" 

Return the subset of ``s`` of size ``k`` that has rank ``r``. 

 

EXAMPLES:: 

 

sage: Subsets(3,2).unrank(0) 

{1, 2} 

sage: Subsets([2,4,5],2).unrank(0) 

{2, 4} 

sage: Subsets([1,2,8],3).unrank(42) 

Traceback (most recent call last): 

... 

IndexError: index out of range 

""" 

lset = self._ls 

n = len(lset) 

 

if self._k > n or r >= self.cardinality() or r < 0: 

raise IndexError("index out of range") 

else: 

return self.element_class([lset[i] for i in combination.from_rank(r, n, self._k)]) 

 

def an_element(self): 

""" 

Returns an example of subset. 

 

EXAMPLES:: 

 

sage: Subsets(0,0).an_element() 

{} 

sage: Subsets(3,2).an_element() 

{1, 3} 

sage: Subsets([2,4,5],2).an_element() 

{2, 5} 

""" 

return self.unrank(self.cardinality() // 2) 

 

def dict_to_list(d): 

r""" 

Return a list whose elements are the elements of i of d repeated with 

multiplicity d[i]. 

 

EXAMPLES:: 

 

sage: from sage.combinat.subset import dict_to_list 

sage: dict_to_list({'a':1, 'b':3}) 

['a', 'b', 'b', 'b'] 

""" 

l = [] 

for i,j in six.iteritems(d): 

l.extend([i]*j) 

return l 

 

def list_to_dict(l): 

r""" 

Return a dictionary whose keys are the elements of l and values are the 

multiplicity they appear in l. 

 

EXAMPLES:: 

 

sage: from sage.combinat.subset import list_to_dict 

sage: list_to_dict(['a', 'b', 'b', 'b']) 

{'a': 1, 'b': 3} 

""" 

d = {} 

for elt in l: 

if elt not in d: 

d[elt] = 0 

d[elt] += 1 

return d 

 

class SubMultiset_s(Parent): 

""" 

The combinatorial class of the sub multisets of ``s``. 

 

EXAMPLES:: 

 

sage: S = Subsets([1,2,2,3], submultiset=True) 

sage: S.cardinality() 

12 

sage: S.list() 

[[], 

[1], 

[2], 

[3], 

[1, 2], 

[1, 3], 

[2, 2], 

[2, 3], 

[1, 2, 2], 

[1, 2, 3], 

[2, 2, 3], 

[1, 2, 2, 3]] 

sage: S.first() 

[] 

sage: S.last() 

[1, 2, 2, 3] 

""" 

# TODO: list does not inherit from Element... so we set 

# directly element_class as list 

element_class = list 

 

def __init__(self, s): 

""" 

Constructs the combinatorial class of the sub multisets of s. 

 

EXAMPLES:: 

 

sage: S = Subsets([1,2,2,3], submultiset=True) 

sage: Subsets([1,2,3,3], submultiset=True).cardinality() 

12 

sage: TestSuite(S).run() 

""" 

Parent.__init__(self, category=FiniteEnumeratedSets()) 

 

self._d = s 

if not isinstance(s, dict): 

self._d = list_to_dict(s) 

 

def _repr_(self): 

""" 

TESTS:: 

 

sage: S = Subsets([1, 2, 2, 3], submultiset=True); S #indirect doctest 

SubMultiset of [1, 2, 2, 3] 

""" 

return "SubMultiset of {}".format(dict_to_list(self._d)) 

 

def __eq__(self, other): 

r""" 

TESTS:: 

 

sage: Subsets([1,2,2,3], submultiset=True) == Subsets([1,2,2,3], submultiset=True) 

True 

sage: Subsets([1,2,2,3], submultiset=True) == Subsets([1,2,3,3], submultiset=True) 

False 

""" 

if self.__class__ != other.__class__: 

return False 

return self._d == other._d 

 

def __ne__(self, other): 

r""" 

TESTS:: 

 

sage: Subsets([1,2,2,3], submultiset=True) != Subsets([1,2,2,3], submultiset=True) 

False 

sage: Subsets([1,2,2,3], submultiset=True) != Subsets([1,2,3,3], submultiset=True) 

True 

""" 

return not self == other 

 

def __contains__(self, s): 

""" 

TESTS:: 

 

sage: S = Subsets([1,2,2,3], submultiset=True) 

sage: [] in S 

True 

sage: [1, 2, 2] in S 

True 

sage: all(i in S for i in S) 

True 

sage: [1, 2, 2, 2] in S 

False 

sage: [1, 3, 2, 2] in S 

True 

sage: [4] in S 

False 

""" 

dd = {} 

for elt in s: 

if elt in dd: 

dd[elt] += 1 

if dd[elt] > self._d[elt]: 

return False 

elif elt not in self._d: 

return False 

else: 

dd[elt] = 1 

return True 

 

def cardinality(self): 

r""" 

Return the cardinality of self 

 

EXAMPLES:: 

 

sage: S = Subsets([1,1,2,3],submultiset=True) 

sage: S.cardinality() 

12 

sage: len(S.list()) 

12 

 

sage: S = Subsets([1,1,2,2,3],submultiset=True) 

sage: S.cardinality() 

18 

sage: len(S.list()) 

18 

 

sage: S = Subsets([1,1,1,2,2,3],submultiset=True) 

sage: S.cardinality() 

24 

sage: len(S.list()) 

24 

""" 

from sage.all import prod 

return Integer(prod(k+1 for k in self._d.values())) 

 

def random_element(self): 

r""" 

Return a random element of self with uniform law 

 

EXAMPLES:: 

 

sage: S = Subsets([1,1,2,3], submultiset=True) 

sage: S.random_element() 

[2] 

""" 

l = [] 

for i in self._d: 

l.extend([i]*rnd.randint(0,self._d[i])) 

return l 

 

def generating_serie(self,variable='x'): 

r""" 

Return the serie (here a polynom) associated to the counting of the 

element of self weighted by the number of element they contain. 

 

EXAMPLES:: 

 

sage: Subsets([1,1],submultiset=True).generating_serie() 

x^2 + x + 1 

sage: Subsets([1,1,2,3],submultiset=True).generating_serie() 

x^4 + 3*x^3 + 4*x^2 + 3*x + 1 

sage: Subsets([1,1,1,2,2,3,3,4],submultiset=True).generating_serie() 

x^8 + 4*x^7 + 9*x^6 + 14*x^5 + 16*x^4 + 14*x^3 + 9*x^2 + 4*x + 1 

 

sage: S = Subsets([1,1,1,2,2,3,3,4],submultiset=True) 

sage: S.cardinality() 

72 

sage: sum(S.generating_serie()) 

72 

""" 

from sage.all import prod 

R = ZZ[variable] 

return prod(R([1]*(n+1)) for n in self._d.values()) 

 

def __iter__(self): 

""" 

Iterates through the subsets of ``self``. Note that each subset is 

represented by a list of its elements rather than a set since we can 

have multiplicities (no multiset data structure yet in sage). 

 

EXAMPLES:: 

 

sage: S = Subsets([1,2,2,3], submultiset=True) 

sage: S.list() 

[[], 

[1], 

[2], 

[3], 

[1, 2], 

[1, 3], 

[2, 2], 

[2, 3], 

[1, 2, 2], 

[1, 2, 3], 

[2, 2, 3], 

[1, 2, 2, 3]] 

 

""" 

for k in range(sum(self._d.values())+1): 

for s in SubMultiset_sk(self._d, k): 

yield s 

 

def __call__(self, el): 

r""" 

Workaround for returning non elements. 

 

See the extensive documentation in 

:meth:`sage.sets.finite_enumerated_set.FiniteEnumeratedSet.__call__`. 

 

TESTS:: 

 

sage: Subsets(['a','b','b','c'], submultiset=True)(['a','b']) # indirect doctest 

['a', 'b'] 

""" 

if not isinstance(el, Element): 

return self._element_constructor_(el) 

else: 

return Parent.__call__(self, el) 

 

def _element_constructor_(self,X): 

""" 

TESTS:: 

 

sage: S = Subsets(['a','b','b','c'], submultiset=True) 

sage: S(['d']) 

Traceback (most recent call last): 

... 

ValueError: ['d'] not in SubMultiset of ['a', 'c', 'b', 'b'] 

""" 

e = self.element_class(X) 

if e not in self: 

raise ValueError("{} not in {}".format(e,self)) 

return e 

 

 

 

class SubMultiset_sk(SubMultiset_s): 

""" 

The combinatorial class of the subsets of size k of a multiset s. Note 

that each subset is represented by a list of the elements rather than a 

set since we can have multiplicities (no multiset data structure yet in 

sage). 

 

EXAMPLES:: 

 

sage: S = Subsets([1,2,3,3],2,submultiset=True) 

sage: S._k 

2 

sage: S.cardinality() 

4 

sage: S.first() 

[1, 2] 

sage: S.last() 

[3, 3] 

sage: [sub for sub in S] 

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

""" 

def __init__(self, s, k): 

""" 

TESTS:: 

 

sage: S = Subsets([1,2,3,3],2,submultiset=True) 

sage: [sub for sub in S] 

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

sage: TestSuite(S).run() 

""" 

SubMultiset_s.__init__(self, s) 

self._l = dict_to_list(self._d) 

self._k = k 

 

def __eq__(self, other): 

r""" 

TESTS:: 

 

sage: Subsets([1,2,2,3], submultiset=True) == Subsets([1,2,2,3], submultiset=True) 

True 

sage: Subsets([1,2,2,3], submultiset=True) == Subsets([1,2,3,3], submultiset=True) 

False 

""" 

if self.__class__ != other.__class__: 

return False 

return self._d == other._d and self._k == other._k 

 

def generating_serie(self,variable='x'): 

r""" 

Return the serie (this case a polynom) associated to the counting of the 

element of self weighted by the number of element they contains 

 

EXAMPLES:: 

 

sage: x = ZZ['x'].gen() 

sage: l = [1,1,1,1,2,2,3] 

sage: for k in range(len(l)): 

....: S = Subsets(l,k,submultiset=True) 

....: print(S.generating_serie('x') == S.cardinality()*x**k) 

True 

True 

True 

True 

True 

True 

True 

""" 

x = ZZ[variable].gen() 

P = SubMultiset_s.generating_serie(self) 

return P[self._k] * (x**self._k) 

 

def cardinality(self): 

r""" 

Return the cardinality of self 

 

EXAMPLES:: 

 

sage: S = Subsets([1,2,2,3,3,3],4,submultiset=True) 

sage: S.cardinality() 

5 

sage: len(list(S)) 

5 

 

sage: S = Subsets([1,2,2,3,3,3],3,submultiset=True) 

sage: S.cardinality() 

6 

sage: len(list(S)) 

6 

""" 

return Integer(sum(1 for _ in self)) 

 

def _repr_(self): 

""" 

TESTS:: 

 

sage: S = Subsets([1, 2, 2, 3], 3, submultiset=True) 

sage: repr(S) #indirect doctest 

'SubMultiset of [1, 2, 2, 3] of size 3' 

""" 

return "{} of size {}".format(SubMultiset_s._repr_(self), self._k) 

 

def __contains__(self, s): 

""" 

TESTS:: 

 

sage: S = Subsets([1,2,2,3], 2, submultiset=True) 

sage: [] in S 

False 

sage: [1, 2, 2] in S 

False 

sage: all(i in S for i in S) 

True 

sage: [2, 2] in S 

True 

sage: [1, 3] in S 

True 

sage: [4] in S 

False 

sage: [3, 3] in S 

False 

""" 

return len(s) == self._k and SubMultiset_s.__contains__(self, s) 

 

def random_element(self): 

r""" 

Return a random submultiset of given length 

 

EXAMPLES:: 

 

sage: Subsets(7,3).random_element() 

{1, 4, 7} 

sage: Subsets(7,5).random_element() 

{1, 3, 4, 5, 7} 

""" 

return rnd.sample(self._l, self._k) 

 

def __iter__(self): 

""" 

Iterates through the subsets of size ``self._k`` of the multiset 

``self._s``. Note that each subset is represented by a list of the 

elements rather than a set since we can have multiplicities (no 

multiset data structure yet in sage). 

 

EXAMPLES:: 

 

sage: S = Subsets([1,2,2,3],2, submultiset=True) 

sage: S.list() 

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

""" 

from sage.combinat.integer_vector import IntegerVectors 

elts = list(self._d) 

for iv in IntegerVectors(self._k, len(self._d), outer=self._d.values()): 

yield sum([[elts[i]] * iv[i] for i in range(len(iv))], []) 

 

class SubsetsSorted(Subsets_s): 

""" 

Lightweight class of all subsets of some set `S`, with each 

subset being encoded as a sorted tuple. 

 

Used to model indices of algebras given by subsets (so we don't 

have to explicitly build all `2^n` subsets in memory). 

For example, :class:`CliffordAlgebra`. 

""" 

element_class = tuple 

 

def __contains__(self, value): 

""" 

TESTS:: 

 

sage: from sage.combinat.subset import SubsetsSorted 

sage: S = SubsetsSorted(range(3)) 

sage: Set([1,2]) in S 

True 

sage: Set([1,4]) in S 

False 

sage: Set([]) in S 

True 

sage: (0,2) in S 

True 

sage: 2 in S 

False 

""" 

if not isinstance(value, (list, tuple)) and value not in Sets(): 

return False 

return all(v in self._s for v in value) 

 

def __iter__(self): 

""" 

Iterate over ``self``. 

 

EXAMPLES:: 

 

sage: from sage.combinat.subset import SubsetsSorted 

sage: S = SubsetsSorted(range(3)) 

sage: [s for s in S] 

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

""" 

k = ZZ_0 

while k <= self._s.cardinality(): 

for ss in Subsets_sk(self._s, k)._fast_iterator(): 

yield self.element_class(sorted(ss)) 

k += 1 

 

def first(self): 

""" 

Return the first element of ``self``. 

 

EXAMPLES:: 

 

sage: from sage.combinat.subset import SubsetsSorted 

sage: S = SubsetsSorted(range(3)) 

sage: S.first() 

() 

""" 

return self.element_class([]) 

 

def last(self): 

""" 

Return the last element of ``self``. 

 

EXAMPLES:: 

 

sage: from sage.combinat.subset import SubsetsSorted 

sage: S = SubsetsSorted(range(3)) 

sage: S.last() 

(0, 1, 2) 

""" 

return tuple(sorted(self._s)) 

 

def random_element(self): 

""" 

Return a random element of ``self``. 

 

EXAMPLES:: 

 

sage: from sage.combinat.subset import SubsetsSorted 

sage: S = SubsetsSorted(range(3)) 

sage: isinstance(S.random_element(), tuple) 

True 

""" 

return tuple(sorted(Subsets_s.random_element(self))) 

 

def unrank(self, r): 

""" 

Return the subset which has rank ``r``. 

 

EXAMPLES:: 

 

sage: from sage.combinat.subset import SubsetsSorted 

sage: S = SubsetsSorted(range(3)) 

sage: S.unrank(4) 

(0, 1) 

""" 

r = Integer(r) 

if r >= self.cardinality() or r < 0: 

raise IndexError("index out of range") 

 

k = ZZ_0 

n = self._s.cardinality() 

binom = ZZ.one() 

while r >= binom: 

r -= binom 

k += 1 

binom = binomial(n,k) 

C = combination.from_rank(r, n, k) 

return self.element_class(sorted([self._s.unrank(i) for i in C])) 

 

def _an_element_(self): 

""" 

Return an element of ``self``. 

 

EXAMPLES:: 

 

sage: from sage.combinat.subset import SubsetsSorted 

sage: S = SubsetsSorted(range(3)) 

sage: S.an_element() 

(0, 1) 

""" 

return self.element_class(sorted(Subsets_s._an_element_(self))) 

 

def _element_constructor_(self, x): 

""" 

Construct an element of ``self``. 

 

EXAMPLES:: 

 

sage: from sage.combinat.subset import SubsetsSorted 

sage: S = SubsetsSorted(range(3)) 

sage: [s for s in S] 

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

""" 

return self.element_class(sorted(set(x)))