Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement iteration over some polynomial rings #39399

Draft
wants to merge 9 commits into
base: develop
Choose a base branch
from
70 changes: 70 additions & 0 deletions src/sage/rings/polynomial/polynomial_ring.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@
from sage.rings.ring import Ring, CommutativeRing
from sage.structure.element import RingElement
import sage.rings.rational_field as rational_field
from sage.rings.infinity import Infinity
from sage.rings.rational_field import QQ
from sage.rings.integer_ring import ZZ
from sage.rings.integer import Integer
Expand Down Expand Up @@ -1033,6 +1034,75 @@ def __hash__(self):
h = self._cached_hash = hash((self.base_ring(),self.variable_name()))
return h

def __iter__(self):
r"""
Return iterator over the elements of this polynomial ring.

EXAMPLES::

sage: from itertools import islice
sage: R.<x> = GF(3)[]
sage: list(islice(iter(R), 10))
[0, 1, 2, x, x + 1, x + 2, 2*x, 2*x + 1, 2*x + 2, x^2]

TESTS::

sage: R.<x> = Integers(1)[]
sage: [*R]
[0]
sage: R.<x> = QQ[]
sage: list(islice(iter(R), 10))
Traceback (most recent call last):
...
NotImplementedError: iteration over infinite base ring not yet implemented
"""
# adapted from sage.modules.free_module.FreeModule_generic.__iter__
R = self.base_ring()
if R.cardinality() == Infinity:
raise NotImplementedError("iteration over infinite base ring not yet implemented")
iters = []
zero = R.zero()
v = []
n = 0
yield self.zero()
if R.is_zero():
return
while True:
if n == len(iters):
iters.append(iter(R))
v.append(next(iters[n]))
assert v[n] == zero, ("first element of iteration must be zero otherwise result "
"of this and free module __iter__ will be incorrect")
try:
v[n] = next(iters[n])
yield self(v)
n = 0
except StopIteration:
iters[n] = iter(R)
v[n] = next(iters[n])
assert v[n] == zero
n += 1

def cardinality(self):
"""
Return the cardinality of the polynomial ring.

OUTPUT: either an integer or ``+Infinity``

EXAMPLES::

sage: R.<x> = ZZ[]
sage: R.cardinality()
+Infinity
sage: R.<x> = Integers(1)[]
sage: R.cardinality()
1
"""
if self.base_ring().is_zero():
return 1
user202729 marked this conversation as resolved.
Show resolved Hide resolved
from sage.rings.infinity import Infinity
return Infinity

def _repr_(self):
try:
return self._cached_repr
Expand Down
Loading