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

""" 

Multidimensional enumeration 

 

AUTHORS: 

 

- Joel B. Mohler (2006-10-12) 

 

- William Stein (2006-07-19) 

 

- Jon Hanke 

""" 

 

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

# Copyright (C) 2006 William Stein <wstein@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 sage.misc.all import prod 

 

 

def _len(L): 

""" 

Determines the length of ``L``. 

 

Uses either ``cardinality`` or ``__len__`` as appropriate. 

 

EXAMPLES:: 

 

sage: from sage.misc.mrange import _len 

sage: _len(ZZ) 

+Infinity 

sage: _len(range(4)) 

4 

sage: _len(4) 

Traceback (most recent call last): 

... 

TypeError: object of type 'sage.rings.integer.Integer' has no len() 

""" 

try: 

return L.cardinality() 

except AttributeError: 

return len(L) 

 

def _is_finite(L, fallback=True): 

""" 

Determines whether ``L`` is finite. 

 

If ``L`` implements none of ``is_finite``, ``cardinality`` or 

``__len__``, we assume by default that it is finite for speed 

reasons. This choice can be overridden by passing in 

``fallback``. 

 

EXAMPLES:: 

 

sage: from sage.misc.mrange import _is_finite 

sage: _is_finite(ZZ) 

False 

sage: _is_finite(range(4)) 

True 

sage: _is_finite([]) 

True 

sage: from six.moves import range 

sage: _is_finite(range(10^8)) 

True 

sage: from itertools import product 

sage: _is_finite(product([1],[1])) # does not provide is_finite() or __len__() 

True 

 

""" 

try: 

return L.is_finite() 

except AttributeError: 

pass 

except ValueError: 

# L doesn't know how to determine whether it's finite 

return fallback 

 

try: 

n = _len(L) 

except (TypeError, AttributeError, NotImplementedError): 

# We usually assume L is finite for speed reasons 

return fallback 

 

from sage.rings.infinity import infinity 

if n is infinity: 

return False 

return True 

 

def _xmrange_iter( iter_list, typ=list ): 

""" 

This implements the logic for mrange_iter and xmrange_iter. 

 

Note that with typ==list, we will be returning a new copy each 

iteration. This makes it OK to modified the returned list. This 

functionality is relied on in the polynomial iterators. Here's a 

doc-test to prove this:: 

 

sage: iter = sage.misc.mrange._xmrange_iter( [[1,2],[1,3]] ) 

sage: l1 = next(iter) 

sage: l2 = next(iter) 

sage: l1 is l2 

False 

 

However, if you would like to re-use the list object:: 

 

sage: iter = sage.misc.mrange._xmrange_iter( [[1,2],[1,3]], lambda x: x ) 

sage: l1 = next(iter) 

sage: l2 = next(iter) 

sage: l1 is l2 # eeek, this is freaky! 

True 

 

We check that :trac:`14285` has been resolved:: 

 

sage: iter = sage.misc.mrange._xmrange_iter([ZZ,[]]) 

sage: next(iter) 

Traceback (most recent call last): 

... 

StopIteration 

 

""" 

if len(iter_list) == 0: 

yield typ() 

return 

# If any iterator in the list is infinite we need to be more careful 

if any(not _is_finite(L) for L in iter_list): 

for L in iter_list: 

try: 

n = _len(L) 

except TypeError: 

continue 

if n == 0: 

return 

curr_iters = [iter(i) for i in iter_list] 

curr_elt = [next(i) for i in curr_iters[:-1]] + [None] 

place = len(iter_list) - 1 

while True: 

try: 

while True: 

curr_elt[place] = next(curr_iters[place]) 

if place < len(iter_list) - 1: 

place += 1 

curr_iters[place] = iter(iter_list[place]) 

continue 

else: 

yield typ(curr_elt) 

except StopIteration: 

place -= 1 

if place == -1: 

return 

 

def mrange_iter(iter_list, typ=list): 

""" 

Return the multirange list derived from the given list of 

iterators. 

 

This is the list version of xmrange_iter. Use xmrange_iter for 

the iterator. 

 

More precisely, return the iterator over all objects of type typ of 

n-tuples of Python ints with entries between 0 and the integers in 

the sizes list. The iterator is empty if sizes is empty or contains 

any non-positive integer. 

 

INPUT: 

 

 

- ``iter_list`` - a finite iterable of finite iterables 

 

- ``typ`` - (default: list) a type or class; more 

generally, something that can be called with a list as input. 

 

 

OUTPUT: a list 

 

EXAMPLES:: 

 

sage: mrange_iter([range(3),[0,2]]) 

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

sage: mrange_iter([['Monty','Flying'],['Python','Circus']], tuple) 

[('Monty', 'Python'), ('Monty', 'Circus'), ('Flying', 'Python'), ('Flying', 'Circus')] 

sage: mrange_iter([[2,3,5,7],[1,2]], sum) 

[3, 4, 4, 5, 6, 7, 8, 9] 

 

Examples that illustrate empty multi-ranges:: 

 

sage: mrange_iter([range(5),range(3),range(0)]) 

[] 

sage: from six.moves import range 

sage: mrange_iter([range(5),range(3),range(-2)]) 

[] 

 

This example is not empty, and should not be. See :trac:`6561`. 

 

:: 

 

sage: mrange_iter([]) 

[[]] 

 

AUTHORS: 

 

- Joel B. Mohler 

""" 

return list(_xmrange_iter(iter_list, typ)) 

 

class xmrange_iter: 

""" 

Return the multirange iterate derived from the given iterators and 

type. 

 

.. note:: 

 

This basically gives you the Cartesian product of sets. 

 

More precisely, return the iterator over all objects of type typ of 

n-tuples of Python ints with entries between 0 and the integers in 

the sizes list. The iterator is empty if sizes is empty or contains 

any non-positive integer. 

 

Use mrange_iter for the non-iterator form. 

 

INPUT: 

 

 

- ``iter_list`` - a list of objects usable as iterators (possibly 

lists) 

 

- ``typ`` - (default: list) a type or class; more generally, 

something that can be called with a list as input. 

 

 

OUTPUT: a generator 

 

EXAMPLES: We create multi-range iterators, print them and also 

iterate through a tuple version. :: 

 

sage: z = xmrange_iter([list(range(3)),list(range(2))], tuple);z 

xmrange_iter([[0, 1, 2], [0, 1]], <... 'tuple'>) 

sage: for a in z: 

....: print(a) 

(0, 0) 

(0, 1) 

(1, 0) 

(1, 1) 

(2, 0) 

(2, 1) 

 

We illustrate a few more iterations. 

 

:: 

 

sage: list(xmrange_iter([range(3),range(2)])) 

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

sage: list(xmrange_iter([range(3),range(2)], tuple)) 

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

 

Here we compute the sum of each element of the multi-range 

iterator:: 

 

sage: list(xmrange_iter([range(3),range(2)], sum)) 

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

 

Next we compute the product:: 

 

sage: list(xmrange_iter([range(3),range(2)], prod)) 

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

 

Examples that illustrate empty multi-ranges. 

 

:: 

 

sage: list(xmrange_iter([range(5),range(3),range(-2)])) 

[] 

sage: list(xmrange_iter([range(5),range(3),range(0)])) 

[] 

 

This example is not empty, and should not be. See :trac:`6561`. 

 

:: 

 

sage: list(xmrange_iter([])) 

[[]] 

 

We use a multi-range iterator to iterate through the Cartesian 

product of sets. 

 

:: 

 

sage: X = ['red', 'apple', 389] 

sage: Y = ['orange', 'horse'] 

sage: for i,j in xmrange_iter([X, Y], tuple): 

....: print((i, j)) 

('red', 'orange') 

('red', 'horse') 

('apple', 'orange') 

('apple', 'horse') 

(389, 'orange') 

(389, 'horse') 

 

AUTHORS: 

 

- Joel B. Mohler 

""" 

def __init__(self, iter_list, typ=list): 

self.iter_list = iter_list 

self.typ = typ 

 

def __repr__(self): 

if self.typ == list: 

return 'xmrange_iter(%s)'%self.iter_list 

else: 

return 'xmrange_iter(%s, %s)'%(self.iter_list, self.typ) 

 

def __iter__(self): 

return _xmrange_iter(self.iter_list, self.typ) 

 

def __len__(self): 

""" 

Return the cardinality of this iterator as an int. 

 

Raises a ``TypeError`` if the cardinality does not fit into a Python 

int. 

 

EXAMPLES:: 

 

sage: C = cartesian_product_iterator([range(3),range(4)]) 

sage: len(C) 

12 

sage: len(cartesian_product_iterator([])) 

1 

sage: len(cartesian_product_iterator([ZZ,[]])) 

0 

sage: len(cartesian_product_iterator([ZZ,ZZ])) 

Traceback (most recent call last): 

... 

TypeError: cardinality does not fit into a Python int. 

 

""" 

n = self.cardinality() 

try: 

n = int(n) 

if not isinstance(n, int): # could be a long 

raise TypeError 

except TypeError: 

raise TypeError("cardinality does not fit into a Python int.") 

return n 

 

def cardinality(self): 

""" 

Return the cardinality of this iterator. 

 

EXAMPLES:: 

 

sage: C = cartesian_product_iterator([range(3),range(4)]) 

sage: C.cardinality() 

12 

sage: C = cartesian_product_iterator([ZZ,QQ]) 

sage: C.cardinality() 

+Infinity 

sage: C = cartesian_product_iterator([ZZ,[]]) 

sage: C.cardinality() 

0 

""" 

from sage.rings.integer import Integer 

from sage.rings.infinity import infinity 

ans = Integer(1) 

found_infinity = False 

for L in self.iter_list: 

try: 

n = L.cardinality() 

except AttributeError: 

n = Integer(len(L)) 

if n == 0: 

return Integer(0) 

elif n is infinity: 

found_infinity = True 

elif not found_infinity: 

ans *= n 

if found_infinity: 

return infinity 

else: 

return ans 

 

def _xmrange(sizes, typ=list): 

n = len(sizes) 

if n == 0: 

yield typ([]) 

return 

for i in sizes: 

if i <= 0: 

return 

v = [0] * n # make a list of n 0's. 

v[-1] = -1 

ptr_max = n - 1 

ptr = ptr_max 

while True: 

while True: 

if ptr != -1 and v[ptr] + 1 < sizes[ptr]: 

v[ptr] += 1 

ptr = ptr_max 

break 

elif ptr != -1: 

v[ptr] = 0 

ptr -= 1 

else: 

return 

yield typ(v) # make a copy of v! 

 

 

def mrange(sizes, typ=list): 

""" 

Return the multirange list with given sizes and type. 

 

This is the list version of xmrange. Use xmrange for the iterator. 

 

More precisely, return the iterator over all objects of type typ of 

n-tuples of Python ints with entries between 0 and the integers in 

the sizes list. The iterator is empty if sizes is empty or contains 

any non-positive integer. 

 

INPUT: 

 

 

- ``sizes`` - a list of nonnegative integers 

 

- ``typ`` - (default: list) a type or class; more 

generally, something that can be called with a list as input. 

 

 

OUTPUT: a list 

 

EXAMPLES:: 

 

sage: mrange([3,2]) 

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

sage: mrange([3,2], tuple) 

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

sage: mrange([3,2], sum) 

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

 

Examples that illustrate empty multi-ranges:: 

 

sage: mrange([5,3,-2]) 

[] 

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

[] 

 

This example is not empty, and should not be. See :trac:`6561`. 

 

:: 

 

sage: mrange([]) 

[[]] 

 

 

AUTHORS: 

 

- Jon Hanke 

 

- William Stein 

""" 

return list(_xmrange(sizes, typ)) 

 

 

class xmrange: 

""" 

Return the multirange iterate with given sizes and type. 

 

More precisely, return the iterator over all objects of type typ of 

n-tuples of Python ints with entries between 0 and the integers in 

the sizes list. The iterator is empty if sizes is empty or contains 

any non-positive integer. 

 

Use mrange for the non-iterator form. 

 

INPUT: 

 

 

- ``sizes`` - a list of nonnegative integers 

 

- ``typ`` - (default: list) a type or class; more 

generally, something that can be called with a list as input. 

 

 

OUTPUT: a generator 

 

EXAMPLES: We create multi-range iterators, print them and also 

iterate through a tuple version. 

 

:: 

 

sage: z = xmrange([3,2]);z 

xmrange([3, 2]) 

sage: z = xmrange([3,2], tuple);z 

xmrange([3, 2], <... 'tuple'>) 

sage: for a in z: 

....: print(a) 

(0, 0) 

(0, 1) 

(1, 0) 

(1, 1) 

(2, 0) 

(2, 1) 

 

We illustrate a few more iterations. 

 

:: 

 

sage: list(xmrange([3,2])) 

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

sage: list(xmrange([3,2], tuple)) 

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

 

Here we compute the sum of each element of the multi-range 

iterator:: 

 

sage: list(xmrange([3,2], sum)) 

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

 

Next we compute the product:: 

 

sage: list(xmrange([3,2], prod)) 

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

 

Examples that illustrate empty multi-ranges. 

 

:: 

 

sage: list(xmrange([5,3,-2])) 

[] 

sage: list(xmrange([5,3,0])) 

[] 

 

This example is not empty, and should not be. See :trac:`6561`. 

 

:: 

 

sage: list(xmrange([])) 

[[]] 

 

We use a multi-range iterator to iterate through the Cartesian 

product of sets. 

 

:: 

 

sage: X = ['red', 'apple', 389] 

sage: Y = ['orange', 'horse'] 

sage: for i,j in xmrange([len(X), len(Y)]): 

....: print((X[i], Y[j])) 

('red', 'orange') 

('red', 'horse') 

('apple', 'orange') 

('apple', 'horse') 

(389, 'orange') 

(389, 'horse') 

 

AUTHORS: 

 

- Jon Hanke 

 

- William Stein 

""" 

def __init__(self, sizes, typ=list): 

self.sizes = [int(x) for x in sizes] 

self.typ = typ 

 

def __repr__(self): 

if self.typ == list: 

return 'xmrange(%s)'%self.sizes 

else: 

return 'xmrange(%s, %s)'%(self.sizes, self.typ) 

 

def __len__(self): 

sizes = self.sizes 

n = len(sizes) 

if n == 0: 

return 0 

for i in sizes: 

if i <= 0: 

return 0 

return prod(sizes, 1) 

 

def __iter__(self): 

return _xmrange(self.sizes, self.typ) 

 

def cartesian_product_iterator(X): 

""" 

Iterate over the Cartesian product. 

 

INPUT: 

 

 

- ``X`` - list or tuple of lists 

 

 

OUTPUT: iterator over the Cartesian product of the elements of X 

 

EXAMPLES:: 

 

sage: list(cartesian_product_iterator([[1,2], ['a','b']])) 

[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')] 

sage: list(cartesian_product_iterator([])) 

[()] 

""" 

return xmrange_iter(X, tuple) 

 

def cantor_product(*args, **kwds): 

r""" 

Return an iterator over the product of the inputs along the diagonals a la 

:wikipedia:`Cantor pairing <Pairing_function#Cantor_pairing_function>`. 

 

INPUT: 

 

- a certain number of iterables 

 

- ``repeat`` -- an optional integer. If it is provided, the input is 

repeated ``repeat`` times. 

 

Other keyword arguments are passed to 

:class:`sage.combinat.integer_lists.invlex.IntegerListsLex`. 

 

EXAMPLES:: 

 

sage: from sage.misc.mrange import cantor_product 

sage: list(cantor_product([0, 1], repeat=3)) 

[(0, 0, 0), 

(1, 0, 0), 

(0, 1, 0), 

(0, 0, 1), 

(1, 1, 0), 

(1, 0, 1), 

(0, 1, 1), 

(1, 1, 1)] 

sage: list(cantor_product([0, 1], [0, 1, 2, 3])) 

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

 

Infinite iterators are valid input as well:: 

 

sage: from itertools import islice 

sage: list(islice(cantor_product(ZZ, QQ), 14)) 

[(0, 0), 

(1, 0), 

(0, 1), 

(-1, 0), 

(1, 1), 

(0, -1), 

(2, 0), 

(-1, 1), 

(1, -1), 

(0, 1/2), 

(-2, 0), 

(2, 1), 

(-1, -1), 

(1, 1/2)] 

 

TESTS:: 

 

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

sage: sum(1 for _ in C) == 2*4*3 

True 

 

sage: from itertools import count 

sage: list(cantor_product([], count())) 

[] 

sage: list(cantor_product(count(), [], count())) 

[] 

 

sage: list(cantor_product(count(), repeat=0)) 

[()] 

 

sage: next(cantor_product(count(), repeat=-1)) 

Traceback (most recent call last): 

... 

ValueError: repeat argument cannot be negative 

sage: next(cantor_product(count(), toto='hey')) 

Traceback (most recent call last): 

... 

TypeError: __init__() got an unexpected keyword argument 'toto' 

 

:: 

 

sage: list(cantor_product(srange(5), repeat=2, min_slope=1)) 

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

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

 

Check that :trac:`24897` is fixed:: 

 

sage: from sage.misc.mrange import cantor_product 

sage: list(cantor_product([1])) 

[(1,)] 

sage: list(cantor_product([1], repeat=2)) 

[(1, 1)] 

sage: list(cantor_product([1], [1,2])) 

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

sage: list(cantor_product([1,2], [1])) 

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

""" 

from itertools import count 

from sage.combinat.integer_lists import IntegerListsLex 

 

m = len(args) # numer of factors 

lengths = [None] * m # None or length of factors 

data = [[] for _ in range(m)] # the initial slice of each factor 

iterators = [iter(a) for a in args] # the iterators 

repeat = int(kwds.pop('repeat', 1)) 

if repeat == 0: 

yield () 

return 

elif repeat < 0: 

raise ValueError("repeat argument cannot be negative") 

mm = m * repeat 

 

for n in count(0): 

# try to add one more term to each bin 

for i, a in enumerate(iterators): 

if lengths[i] is None: 

try: 

data[i].append(next(a)) 

except StopIteration: 

assert len(data[i]) == n 

if n == 0: 

return 

lengths[i] = n 

 

# iterate through what we have 

ceiling = [n if lengths[i] is None else lengths[i]-1 for i in range(m)] * repeat 

for v in IntegerListsLex(n, length=mm, ceiling=ceiling, **kwds): 

yield tuple(data[i%m][v[i]] for i in range(mm)) 

 

if all(l is not None for l in lengths) and repeat*sum(l-1 for l in lengths) <= n: 

return