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

small cleanup in monoids #37435

Merged
merged 2 commits into from
Mar 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions src/sage/monoids/automatic_semigroup.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Automatic Semigroups

Expand Down Expand Up @@ -418,7 +417,7 @@ def _repr_(self):
else:
of = ""

return "%s%s with %s generators" % (typ, of, len(self._generators))
return f"{typ}{of} with {len(self._generators)} generators"

def repr_element_method(self, style="ambient"):
"""
Expand Down Expand Up @@ -514,7 +513,7 @@ def retract(self, ambient_element, check=True):
if element not in self._elements_set:
cache = self._retract.cache
del cache[((ambient_element,), ())]
raise ValueError("%s not in %s" % (ambient_element, self))
raise ValueError(f"{ambient_element} not in {self}")
return element

@cached_method
Expand Down
11 changes: 6 additions & 5 deletions src/sage/monoids/free_abelian_monoid.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,15 @@
sage: x.list()
[7, 2, 0, 1, 1]
"""
#*****************************************************************************
# ****************************************************************************
# Copyright (C) 2005 David Kohel <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
# https://www.gnu.org/licenses/
# ****************************************************************************

from sage.misc.cachefunc import cached_method
from sage.structure.category_object import normalize_names
Expand Down Expand Up @@ -141,7 +141,7 @@ def FreeAbelianMonoid(index_set=None, names=None, **kwds):
sage: FreeAbelianMonoid(names='x,y')
Free abelian monoid on 2 generators (x, y)
"""
if isinstance(index_set, str): # Swap args (this works if names is None as well)
if isinstance(index_set, str): # Swap args (this works if names is None as well)
names, index_set = index_set, names

if index_set is None and names is not None:
Expand Down Expand Up @@ -179,6 +179,7 @@ def is_FreeAbelianMonoid(x):
"""
return isinstance(x, FreeAbelianMonoid_class)


class FreeAbelianMonoid_class(Parent):
"""
Free abelian monoid on `n` generators.
Expand All @@ -204,7 +205,7 @@ def __init__(self, n, names):

def __repr__(self):
n = self.__ngens
return "Free abelian monoid on %s generators %s" % (n,self.gens())
return f"Free abelian monoid on {n} generators {self.gens()}"

def __call__(self, x):
"""
Expand Down
2 changes: 1 addition & 1 deletion src/sage/monoids/free_abelian_monoid_element.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ cdef class FreeAbelianMonoidElement(MonoidElement):

def __pow__(self, n, modulus):
"""
Raises self to the power of ``n``.
Raise ``self`` to the power of ``n``.

AUTHORS:

Expand Down
2 changes: 1 addition & 1 deletion src/sage/monoids/free_monoid.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ def __init__(self, n, names=None):
Monoid_class.__init__(self, names)

def _repr_(self):
return "Free monoid on %s generators %s" % (self.__ngens, self.gens())
return f"Free monoid on {self.__ngens} generators {self.gens()}"

def _element_constructor_(self, x, check=True):
"""
Expand Down
36 changes: 16 additions & 20 deletions src/sage/monoids/free_monoid_element.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
pairs of integers.
"""

#*****************************************************************************
# ****************************************************************************
# Copyright (C) 2005 David Kohel <[email protected]>
#
# Distributed under the terms of the GNU General Public License (GPL)
Expand All @@ -22,7 +22,7 @@
# is available at:
#
# https://www.gnu.org/licenses/
#*****************************************************************************
# ****************************************************************************

from sage.rings.integer import Integer
from sage.structure.element import MonoidElement
Expand Down Expand Up @@ -123,12 +123,12 @@ def _repr_(self):
if e == 1:
s += "%s" % g
else:
s += "%s^%s" % (g,e)
s += f"{g}^{e}"
if len(s) == 0:
s = "1"
return s

def _latex_(self):
def _latex_(self) -> str:
r"""
Return latex representation of self.

Expand Down Expand Up @@ -159,9 +159,9 @@ def _latex_(self):
g = x[int(v[i][0])]
e = v[i][1]
if e == 1:
s += "%s " % (g,)
s += f"{g} "
else:
s += "%s^{%s}" % (g, e)
s += f"{g}^{{{e}}}"
fchapoton marked this conversation as resolved.
Show resolved Hide resolved
s = s.rstrip(" ") # strip the trailing whitespace caused by adding a space after each element name
if len(s) == 0:
s = "1"
Expand Down Expand Up @@ -212,7 +212,7 @@ def __call__(self, *x, **kwds):
raise ValueError("must specify as many values as generators in parent")

# I don't start with 0, because I don't want to preclude evaluation with
#arbitrary objects (e.g. matrices) because of funny coercion.
# arbitrary objects (e.g. matrices) because of funny coercion.
one = P.one()
result = None
for var_index, exponent in self._element_list:
Expand Down Expand Up @@ -262,7 +262,7 @@ def _mul_(self, y):
z._element_list = x_elt + y_elt
else:
m = (y_elt[0][0], x_elt[k][1]+y_elt[0][1])
z._element_list = x_elt[:k] + [ m ] + y_elt[1:]
z._element_list = x_elt[:k] + [m] + y_elt[1:]
return z

def __invert__(self):
Expand All @@ -278,7 +278,7 @@ def __invert__(self):
"""
raise NotImplementedError

def __len__(self):
def __len__(self) -> int:
"""
Return the degree of the monoid element ``self``, where each
generator of the free monoid is given degree `1`.
Expand All @@ -296,12 +296,9 @@ def __len__(self):
sage: len(a[0]**2 * a[1])
3
"""
s = 0
for x in self._element_list:
s += x[1]
return s
return sum(x[1] for x in self._element_list)

def _richcmp_(self, other, op):
def _richcmp_(self, other, op) -> bool:
"""
Compare two free monoid elements with the same parents.

Expand Down Expand Up @@ -334,8 +331,7 @@ def _richcmp_(self, other, op):

def _acted_upon_(self, x, self_on_left):
"""
Currently, returns the action of the integer 1 on this
element.
Return the action of the integer 1 on this element.

EXAMPLES::

Expand Down Expand Up @@ -373,11 +369,11 @@ def to_word(self, alph=None):
gens = self.parent().gens()
if alph is None:
alph = gens
alph = [str(_) for _ in alph]
W = Words(alph)
return W(sum([ [alph[gens.index(i[0])]] * i[1] for i in list(self) ], []))
alph = [str(c) for c in alph]
W = Words(alph, infinite=False)
return W(sum([[alph[gens.index(i[0])]] * i[1] for i in self], []))

def to_list(self, indices=False):
def to_list(self, indices=False) -> list:
r"""
Return ``self`` as a list of generators.

Expand Down
8 changes: 4 additions & 4 deletions src/sage/monoids/hecke_monoid.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
# -*- coding: utf-8 -*-
"""
Hecke Monoids
"""
#*****************************************************************************
# ****************************************************************************
# Copyright (C) 2015 Nicolas M. Thiéry <nthiery at users.sf.net>
#
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
#*****************************************************************************
# https://www.gnu.org/licenses/
# ****************************************************************************
from sage.misc.cachefunc import cached_function
from sage.sets.finite_set_maps import FiniteSetMaps


@cached_function
def HeckeMonoid(W):
r"""
Expand Down
22 changes: 11 additions & 11 deletions src/sage/monoids/indexed_free_monoid.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@

scalar_mult = P._print_options['scalar_mult']

exp = lambda v: '^{}'.format(v) if v != 1 else ''
exp = lambda v: f'^{v}' if v != 1 else ''
return scalar_mult.join(P._repr_generator(g) + exp(v) for g,v in monomial)

def _ascii_art_(self):
Expand Down Expand Up @@ -180,7 +180,7 @@
if scalar_mult == "*":
scalar_mult = " "

exp = lambda v: '^{{{}}}'.format(v) if v != 1 else ''
exp = lambda v: f'^{{{v}}}' if v != 1 else ''
return scalar_mult.join(P._latex_generator(g) + exp(v) for g,v in monomial)

def __iter__(self):
Expand Down Expand Up @@ -287,7 +287,7 @@
sage: (a*c^3).support()
[0, 2]
"""
supp = set(key for key, exp in self._sorted_items() if exp != 0)
supp = {key for key, exp in self._sorted_items() if exp != 0}
return sorted(supp)

def leading_support(self):
Expand Down Expand Up @@ -544,9 +544,9 @@
1
"""
if not isinstance(n, (int, Integer)):
raise TypeError("Argument n (= {}) must be an integer".format(n))
raise TypeError(f"Argument n (= {n}) must be an integer")

Check warning on line 547 in src/sage/monoids/indexed_free_monoid.py

View check run for this annotation

Codecov / codecov/patch

src/sage/monoids/indexed_free_monoid.py#L547

Added line #L547 was not covered by tests
if n < 0:
raise ValueError("Argument n (= {}) must be positive".format(n))
raise ValueError(f"Argument n (= {n}) must be positive")

Check warning on line 549 in src/sage/monoids/indexed_free_monoid.py

View check run for this annotation

Codecov / codecov/patch

src/sage/monoids/indexed_free_monoid.py#L549

Added line #L549 was not covered by tests
if n == 1:
return self
if n == 0:
Expand Down Expand Up @@ -733,7 +733,7 @@
if x is None:
return self.one()
if x in self._indices:
raise TypeError("unable to convert {!r}, use gen() instead".format(x))
raise TypeError(f"unable to convert {x!r}, use gen() instead")
return self.element_class(self, x)

def _an_element_(self):
Expand Down Expand Up @@ -844,7 +844,7 @@
sage: FreeMonoid(index_set=ZZ)
Free monoid indexed by Integer Ring
"""
return "Free monoid indexed by {}".format(self._indices)
return f"Free monoid indexed by {self._indices}"

Element = IndexedFreeMonoidElement

Expand Down Expand Up @@ -884,7 +884,7 @@
IndexError: 0 is not in the index set
"""
if x not in self._indices:
raise IndexError("{} is not in the index set".format(x))
raise IndexError(f"{x} is not in the index set")
try:
return self.element_class(self, ((self._indices(x),1),))
except (TypeError, NotImplementedError): # Backup (e.g., if it is a string)
Expand Down Expand Up @@ -924,7 +924,7 @@
sage: FreeAbelianMonoid(index_set=ZZ)
Free abelian monoid indexed by Integer Ring
"""
return "Free abelian monoid indexed by {}".format(self._indices)
return f"Free abelian monoid indexed by {self._indices}"

def _element_constructor_(self, x=None):
"""
Expand All @@ -951,7 +951,7 @@
1
"""
if isinstance(x, (list, tuple)):
d = dict()
d = {}
for k, v in x:
if k in d:
d[k] += v
Expand Down Expand Up @@ -1000,7 +1000,7 @@
IndexError: 0 is not in the index set
"""
if x not in self._indices:
raise IndexError("{} is not in the index set".format(x))
raise IndexError(f"{x} is not in the index set")
try:
return self.element_class(self, {self._indices(x): 1})
except (TypeError, NotImplementedError): # Backup (e.g., if it is a string)
Expand Down
6 changes: 4 additions & 2 deletions src/sage/monoids/monoid.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
from sage.structure.parent import Parent
from sage.misc.cachefunc import cached_method

def is_Monoid(x):

def is_Monoid(x) -> bool:
r"""
Returns True if ``x`` is of type ``Monoid_class``.
Return ``True`` if ``x`` is of type ``Monoid_class``.

EXAMPLES::

Expand All @@ -27,6 +28,7 @@ def is_Monoid(x):
"""
return isinstance(x, Monoid_class)


class Monoid_class(Parent):
def __init__(self, names):
r"""
Expand Down
Loading
Loading