Skip to content

Commit 5da2277

Browse files
Use StringIO to format polynomials
Polynomials have variable length and repeated Python built-in += operator can behave in a quadratic way for large strings.
1 parent f449b14 commit 5da2277

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

src/sage/rings/polynomial/polynomial_element.pyx

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ from cpython.number cimport PyNumber_TrueDivide, PyNumber_Check
6565
import operator
6666
import copy
6767
import re
68+
from io import StringIO
6869

6970
from sage.cpython.wrapperdescr cimport wrapperdescr_fastcall
7071
import sage.rings.rational
@@ -2649,7 +2650,8 @@ cdef class Polynomial(CommutativePolynomial):
26492650
# want their coefficient printed with its O() term
26502651
if self._is_gen and not isinstance(self._parent._base, pAdicGeneric):
26512652
return name
2652-
s = " "
2653+
sbuf = StringIO()
2654+
sbuf.write(" ")
26532655
m = self.degree() + 1
26542656
atomic_repr = self._parent.base_ring()._repr_option('element_is_atomic')
26552657
coeffs = self.list(copy=False)
@@ -2665,7 +2667,7 @@ cdef class Polynomial(CommutativePolynomial):
26652667
is_nonzero = True
26662668
if is_nonzero:
26672669
if n != m-1:
2668-
s += " + "
2670+
sbuf.write(" + ")
26692671
x = y = repr(x)
26702672
if y.find("-") == 0:
26712673
y = y[1:]
@@ -2677,7 +2679,9 @@ cdef class Polynomial(CommutativePolynomial):
26772679
var = "*%s"%name
26782680
else:
26792681
var = ""
2680-
s += "%s%s"%(x,var)
2682+
sbuf.write(x)
2683+
sbuf.write(var)
2684+
s = sbuf.getvalue()
26812685
s = s.replace(" + -", " - ")
26822686
s = re.sub(r' 1(\.0+)?\*',' ', s)
26832687
s = re.sub(r' -1(\.0+)?\*',' -', s)

0 commit comments

Comments
 (0)