Skip to content

Commit c8fd3dc

Browse files
author
Release Manager
committed
gh-38366: Check input of composition Fix #14862 URL: #38366 Reported by: Martin Rubey Reviewer(s): Martin Rubey
2 parents ed68bff + c15aed8 commit c8fd3dc

File tree

1 file changed

+38
-6
lines changed

1 file changed

+38
-6
lines changed

src/sage/combinat/composition.py

+38-6
Original file line numberDiff line numberDiff line change
@@ -155,10 +155,25 @@ def __classcall_private__(cls, co=None, descents=None, code=None, from_subset=No
155155
[1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0]
156156
sage: Composition(code=_)
157157
[4, 1, 2, 3, 5]
158+
159+
TESTS:
160+
161+
Let us check that :issue:`14862` is solved::
162+
163+
sage: C = Compositions()
164+
sage: C([3,-1,1])
165+
Traceback (most recent call last):
166+
...
167+
ValueError: not a composition
168+
sage: C("strawberry")
169+
Traceback (most recent call last):
170+
...
171+
ValueError: not a composition
158172
"""
159173
if descents is not None:
160174
if isinstance(descents, tuple):
161-
return Compositions().from_descents(descents[0], nps=descents[1])
175+
return Compositions().from_descents(descents[0],
176+
nps=descents[1])
162177
else:
163178
return Compositions().from_descents(descents)
164179
elif code is not None:
@@ -167,8 +182,22 @@ def __classcall_private__(cls, co=None, descents=None, code=None, from_subset=No
167182
return Compositions().from_subset(*from_subset)
168183
elif isinstance(co, Composition):
169184
return co
170-
else:
171-
return Compositions()(list(co))
185+
186+
return Compositions()(co)
187+
188+
def __init__(self, parent, lst):
189+
"""
190+
Initialize ``self``.
191+
192+
EXAMPLES::
193+
194+
sage: C = Composition([3,1,2])
195+
sage: TestSuite(C).run()
196+
"""
197+
lst = [Integer(u) for u in lst]
198+
if not all(u >= 0 for u in lst):
199+
raise ValueError("elements must be nonnegative integers")
200+
CombinatorialElement.__init__(self, parent, lst)
172201

173202
def _ascii_art_(self):
174203
"""
@@ -1755,8 +1784,10 @@ def _element_constructor_(self, lst) -> Composition:
17551784
sage: P(Partition([5,2,1]))
17561785
[5, 2, 1]
17571786
"""
1758-
if isinstance(lst, (Composition, Partition)):
1759-
lst = list(lst)
1787+
# input can be an iterator, and one has to use it twice
1788+
lst = list(lst)
1789+
if any(not isinstance(x, (int, Integer)) or x < 0 for x in lst):
1790+
raise ValueError('not a composition')
17601791
elt = self.element_class(self, lst)
17611792
if elt not in self:
17621793
raise ValueError("%s not in %s" % (elt, self))
@@ -1860,7 +1891,8 @@ def from_subset(self, S, n) -> Composition:
18601891
return self.element_class(self, [n])
18611892

18621893
if n <= d[-1]:
1863-
raise ValueError("S (=%s) is not a subset of {1, ..., %s}" % (d, n - 1))
1894+
raise ValueError("S (=%s) is not a subset of {1, ..., %s}"
1895+
% (d, n - 1))
18641896
else:
18651897
d.append(n)
18661898

0 commit comments

Comments
 (0)