Skip to content

Commit

Permalink
Implement iteration over some polynomial rings
Browse files Browse the repository at this point in the history
  • Loading branch information
user202729 committed Jan 28, 2025
1 parent dc99dc8 commit a9a3660
Showing 1 changed file with 70 additions and 0 deletions.
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
from sage.rings.infinity import Infinity
return Infinity

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

0 comments on commit a9a3660

Please sign in to comment.