Skip to content
This repository has been archived by the owner on Jan 30, 2023. It is now read-only.

Commit

Permalink
Merge branch 'u/dkrenn/product_cantor_pairing' of trac.sagemath.org:s…
Browse files Browse the repository at this point in the history
…age into t/19048/asy/an_element

* 'u/dkrenn/product_cantor_pairing' of trac.sagemath.org:sage:
  minor changes to code: spacings, PEP8, remove comment
  Trac #19319: alternative implementation
  remove unneccesary try/except block
  deal with product(empty, infinite)
  • Loading branch information
dkrenn committed Oct 1, 2015
2 parents e81d77d + fde8e6d commit f0b1172
Showing 1 changed file with 30 additions and 32 deletions.
62 changes: 30 additions & 32 deletions src/sage/misc/mrange.py
Original file line number Diff line number Diff line change
Expand Up @@ -711,32 +711,32 @@ def product_cantor_pairing(A, B):
A loads item number 0
B loads item number 0
(0, 0)
A loads item number 1
B loads item number 1
(0, 1)
A loads item number 1
(1, 0)
(1, 1)
sage: for p in product_cantor_pairing(it('A', 3), it('B', 2)):
....: print p
A loads item number 0
B loads item number 0
(0, 0)
A loads item number 1
B loads item number 1
(0, 1)
A loads item number 1
(1, 0)
(1, 1)
A loads item number 2
(1, 1)
(2, 0)
(2, 1)
sage: for p in product_cantor_pairing(it('A', 2), it('B', 4)):
....: print p
A loads item number 0
B loads item number 0
(0, 0)
A loads item number 1
B loads item number 1
(0, 1)
A loads item number 1
(1, 0)
B loads item number 2
(0, 2)
Expand All @@ -745,39 +745,37 @@ def product_cantor_pairing(A, B):
(0, 3)
(1, 2)
(1, 3)
"""
# when writing this code I thought the solution would be shorter...

class iter_as_list(list):
def __init__(self, iterable):
self.it = iter(iterable)
self.newdata = True
def __getitem__(self, i):
self.newdata = False
try:
while len(self) <= i:
self.append(next(self.it))
self.newdata = True
except StopIteration:
raise
return list.__getitem__(self, i)
::
sage: from itertools import count
sage: list(product_cantor_pairing([], count()))
[]
sage: list(product_cantor_pairing(count(), []))
[]
"""
from itertools import count
A = iter_as_list(A)
B = iter_as_list(B)
from sage.rings.infinity import infinity

A = iter(A)
B = iter(B)
max_A = infinity
max_B = infinity
cache_A = []
cache_B = []
for s in count():
for i in range(s+1):
stopped = False
if s <= max_A:
try:
a = A[i]
cache_A.append(next(A))
except StopIteration:
stopped = True
max_A = s - 1
if s <= max_B:
try:
b = B[s-i]
cache_B.append(next(B))
except StopIteration:
stopped = True
if stopped:
continue
yield a, b
if not A.newdata and not B.newdata and s >= len(A) + len(B):
max_B = s - 1
if s > max_A + max_B or max_A < 0 or max_B < 0:
return

for i in range(max(0, s-max_B), min(s, max_A) + 1):
yield cache_A[i], cache_B[s-i]

0 comments on commit f0b1172

Please sign in to comment.