Skip to content

some fixes for ruff C4 #39972

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

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion src/sage/algebras/free_algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -1670,7 +1670,7 @@ def merge(self, other):
o_degs = [1] * len(other.vars)
else:
o_degs = list(other.degs)
self_table = {w: d for w, d in zip(self.vars, deg)}
self_table = dict(zip(self.vars, deg))
for v, d in zip(other.vars, o_degs):
if v not in self_vars:
deg.append(d)
Expand Down
2 changes: 1 addition & 1 deletion src/sage/combinat/root_system/ambient_space.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ def __call__(self, v):
# This adds coercion from a list
if isinstance(v, (list, tuple)):
K = self.base_ring()
return self._from_dict(dict((i,K(c)) for i,c in enumerate(v) if c))
return self._from_dict({i: K(c) for i, c in enumerate(v) if c})
else:
return CombinatorialFreeModule.__call__(self, v)

Expand Down
28 changes: 14 additions & 14 deletions src/sage/combinat/root_system/cartan_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -1739,10 +1739,10 @@ def symmetrizer(self):
from sage.matrix.constructor import matrix, diagonal_matrix
m = self.cartan_matrix()
n = m.nrows()
M = matrix(ZZ, n, n*n, sparse=True)
for (i,j) in m.nonzero_positions():
M[i, n * i + j] = m[i,j]
M[j, n * i + j] -= m[j,i]
M = matrix(ZZ, n, n * n, sparse=True)
for i, j in m.nonzero_positions():
M[i, n * i + j] = m[i, j]
M[j, n * i + j] -= m[j, i]
kern = M.integer_kernel()
c = len(self.dynkin_diagram().connected_components(sort=False))
if kern.dimension() < c:
Expand All @@ -1757,7 +1757,7 @@ def symmetrizer(self):
D = sum(kern.basis())
assert diagonal_matrix(D) * m == m.transpose() * diagonal_matrix(D)
I = self.index_set()
return Family( dict( (I[i], D[i]) for i in range(n) ) )
return Family({I[i]: D[i] for i in range(n)})

def index_set_bipartition(self):
r"""
Expand Down Expand Up @@ -2131,7 +2131,7 @@ def row_annihilator(self, m=None):
raise ValueError("the kernel is not 1 dimensional")
assert (all(coef > 0 for coef in annihilator_basis[0]))

return Family(dict((i,annihilator_basis[0][i])for i in self.index_set()))
return Family({i: annihilator_basis[0][i] for i in self.index_set()})

acheck = row_annihilator

Expand Down Expand Up @@ -2205,8 +2205,8 @@ def c(self):
"""
a = self.a()
acheck = self.acheck()
return Family(dict((i, max(ZZ(1), a[i] // acheck[i]))
for i in self.index_set()))
return Family({i: max(ZZ.one(), a[i] // acheck[i])
for i in self.index_set()})

def translation_factors(self):
r"""
Expand Down Expand Up @@ -2372,21 +2372,21 @@ def translation_factors(self):

REFERENCES:

.. [HST09] \F. Hivert, A. Schilling, and N. M. Thiery,
.. [HST09] \F. Hivert, A. Schilling, and N. M. Thiéry,
*Hecke group algebras as quotients of affine Hecke
algebras at level 0*, JCT A, Vol. 116, (2009) p. 844-863
:arxiv:`0804.3781`
"""
a = self.a()
acheck = self.acheck()
if set([1/ZZ(2), 2]).issubset( set(a[i]/acheck[i] for i in self.index_set()) ):
s = set(a[i] / acheck[i] for i in self.index_set())
if ~ZZ(2) in s and 2 in s:
# The test above and the formula below are rather meaningless
# But they detect properly type BC or dual and return the correct value
return Family(dict((i, min(ZZ(1), a[i] / acheck[i]))
for i in self.index_set()))
return Family({i: min(ZZ.one(), a[i] / acheck[i])
for i in self.index_set()})

else:
return self.c()
return self.c()

def _test_dual_classical(self, **options):
r"""
Expand Down
6 changes: 3 additions & 3 deletions src/sage/combinat/root_system/type_folded.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,9 +292,9 @@ def f(i):
return root.leading_coefficient() / coroot.leading_coefficient()
index_set = self._cartan_type.index_set()
min_f = min(f(j) for j in index_set)
return Family(dict( (i, int(f(i) / min_f)) for i in index_set ))
return Family({i: int(f(i) / min_f) for i in index_set})
elif self._cartan_type.is_affine():
c = self._cartan_type.translation_factors()
cmax = max(c)
return Family(dict( (i, int(cmax / c[i]))
for i in self._cartan_type.index_set() ))
return Family({i: int(cmax / c[i])
for i in self._cartan_type.index_set()})
15 changes: 8 additions & 7 deletions src/sage/combinat/root_system/type_reducible.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,12 @@ def __init__(self, types):
"""
self._types = types
self.affine = False
indices = (None,) + tuple( (i, j)
for i in range(len(types))
for j in types[i].index_set() )
indices = (None,) + tuple((i, j)
for i in range(len(types))
for j in types[i].index_set())
self._indices = indices
self._index_relabelling = dict((indices[i], i) for i in range(1, len(indices)))
self._index_relabelling = {indices[i]: i
for i in range(1, len(indices))}

self._spaces = [t.root_system().ambient_space() for t in types]
if all(l is not None for l in self._spaces):
Expand All @@ -130,9 +131,9 @@ def __init__(self, types):
self.tools = root_system.type_reducible
# a direct product of finite Cartan types is again finite;
# idem for simply laced and crystallographic.
super_classes = tuple( cls
for cls in (CartanType_finite, CartanType_simply_laced, CartanType_crystallographic)
if all(isinstance(t, cls) for t in types) )
super_classes = tuple(cls
for cls in (CartanType_finite, CartanType_simply_laced, CartanType_crystallographic)
if all(isinstance(t, cls) for t in types))
self._add_abstract_superclass(super_classes)

def _repr_(self, compact=True): # We should make a consistent choice here
Expand Down
9 changes: 5 additions & 4 deletions src/sage/combinat/root_system/weight_lattice_realizations.py
Original file line number Diff line number Diff line change
Expand Up @@ -596,10 +596,10 @@ def dynkin_diagram_automorphism_of_alcove_morphism(self, f):
# Now, we have d = f w^-1
winv = ~w
assert all(alpha[i].level().is_zero() for i in self.index_set())
rank_simple_roots = dict( (alpha[i],i) for i in self.index_set())
rank_simple_roots = {alpha[i]: i for i in self.index_set()}
permutation = dict()
for i in self.index_set():
root = f(winv.action(alpha[i])) # This is d(alpha_i)
root = f(winv.action(alpha[i])) # This is d(alpha_i)
assert root in rank_simple_roots
permutation[i] = rank_simple_roots[root]
assert set(permutation.values()), set(self.index_set())
Expand Down Expand Up @@ -694,7 +694,8 @@ def _test_reduced_word_of_translation(self, elements=None, **options):
# preserving the alcoves.
if elements is None:
c = self.cartan_type().c()
elements = [ c[i] * Lambda[i] for i in self.cartan_type().classical().index_set() ]
elements = [c[i] * Lambda[i]
for i in self.cartan_type().classical().index_set()]

# When the null root is zero in this root lattice realization,
# the roots correspond to the classical roots. We use that to
Expand All @@ -703,7 +704,7 @@ def _test_reduced_word_of_translation(self, elements=None, **options):
# set to be of the form 0..n
test_automorphism = self.null_root().is_zero() and set(self.index_set()) == set(i for i in range(len(self.index_set())))
# dictionary assigning a simple root to its index
rank_simple_roots = dict( (alpha[i],i) for i in self.index_set() )
rank_simple_roots = {alpha[i]: i for i in self.index_set()}

try:
W = self.weyl_group()
Expand Down
11 changes: 6 additions & 5 deletions src/sage/combinat/similarity_class_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -919,11 +919,11 @@ def number_of_classes(self, invertible=False, q=None):
maximum_degree = max(list_of_degrees)
numerator = prod([prod([primitives(d+1, invertible=invertible, q=q)-i for i in range(list_of_degrees.count(d+1))]) for d in range(maximum_degree)])
tau_list = list(self)
D = dict((i, tau_list.count(i)) for i in tau_list)
D = {i: tau_list.count(i) for i in tau_list}
denominator = prod(factorial(D[primary_type]) for primary_type in D)
return numerator / denominator

def is_semisimple(self):
def is_semisimple(self) -> bool:
"""
Return ``True`` if every primary similarity class type in ``self`` has
all parts equal to ``1``.
Expand All @@ -939,7 +939,7 @@ def is_semisimple(self):
"""
return all(PT.partition().get_part(0) == 1 for PT in self)

def is_regular(self):
def is_regular(self) -> bool:
"""
Return ``True`` if every primary type in ``self`` has partition with one
part.
Expand Down Expand Up @@ -1325,8 +1325,9 @@ def dictionary_from_generator(gen):
high.
"""
L = list(gen)
setofkeys = list(set(item[0] for item in L))
return dict((key, sum(entry[1] for entry in (pair for pair in L if pair[0] == key))) for key in setofkeys)
setofkeys = set(item[0] for item in L)
return {key: sum(pair[1] for pair in L if pair[0] == key)
for key in setofkeys}


def matrix_similarity_classes(n, q=None, invertible=False):
Expand Down
4 changes: 2 additions & 2 deletions src/sage/combinat/symmetric_group_algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -1314,7 +1314,7 @@
and also projective modules)::

sage: SGA = SymmetricGroupAlgebra(QQ, 5)
sage: for la in Partitions(SGA.n):

Check warning on line 1317 in src/sage/combinat/symmetric_group_algebra.py

View workflow job for this annotation

GitHub Actions / Conda (ubuntu, Python 3.11, all)

Warning: slow doctest:

slow doctest:

Check warning on line 1317 in src/sage/combinat/symmetric_group_algebra.py

View workflow job for this annotation

GitHub Actions / Conda (ubuntu, Python 3.12, all)

Warning: slow doctest:

slow doctest:

Check warning on line 1317 in src/sage/combinat/symmetric_group_algebra.py

View workflow job for this annotation

GitHub Actions / Conda (ubuntu, Python 3.12, all, editable)

Warning: slow doctest:

slow doctest:
....: idem = SGA.ladder_idempotent(la)
....: assert idem^2 == idem
....: print(la, SGA.principal_ideal(idem).dimension())
Expand Down Expand Up @@ -2887,7 +2887,7 @@
if n <= 1:
return sgalg.one()

rd = dict((P(h), one) for h in rs)
rd = {P(h): one for h in rs}
return sgalg._from_dict(rd)


Expand Down Expand Up @@ -2971,7 +2971,7 @@
if n <= 1:
return sgalg.one()

cd = dict((P(v), v.sign() * one) for v in cs)
cd = {P(v): v.sign() * one for v in cs}
return sgalg._from_dict(cd)


Expand Down
2 changes: 1 addition & 1 deletion src/sage/crypto/mq/sr.py
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,7 @@ def __init__(self, n=1, r=1, c=1, e=4, star=False, **kwargs):
self._reverse_variables = bool(kwargs.get("reverse_variables", True))

with AllowZeroInversionsContext(self):
sub_byte_lookup = dict([(v, self.sub_byte(v)) for v in self._base])
sub_byte_lookup = {v: self.sub_byte(v) for v in self._base}
self._sub_byte_lookup = sub_byte_lookup

if self._gf2:
Expand Down
8 changes: 3 additions & 5 deletions src/sage/manifolds/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -972,12 +972,10 @@ def _repr_(self):
strv[i] = "(" + sv + ")"

# dictionary to group multiple occurrences of differentiation: d/dxdx -> d/dx^2 etc.
occ = dict((i, strv[i] + "^" + str(diffargs.count(i))
if (diffargs.count(i) > 1) else strv[i])
for i in diffargs)
occ = {i: strv[i] + "^" + str(D) if (D := diffargs.count(i)) > 1
else strv[i] for i in diffargs}

res = "d" + str(numargs) + "(" + str(funcname) + ")/d" + "d".join(
occ.values())
res = f"d{numargs}({funcname})/d" + "d".join(occ.values())

# str representation of the operator
s = self._parent._repr_element_(m[0])
Expand Down
2 changes: 1 addition & 1 deletion src/sage/matroids/chow_ring_ideal.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ def groebner_basis(self, algorithm='', *args, **kwargs):
algorithm = 'constructed'
if algorithm != 'constructed':
return super().groebner_basis(algorithm=algorithm, *args, **kwargs)
flats = sorted(list(self._flats_generator), key=len)
flats = sorted(self._flats_generator, key=len)
ranks = {F: self._matroid.rank(F) for F in flats}
gb = []
R = self.ring()
Expand Down
2 changes: 1 addition & 1 deletion src/sage/misc/package_dir.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@ def iter_importer_modules(importer, prefix=''):
r"""
Yield :class:`ModuleInfo` for all modules of ``importer``.
"""
for name, ispkg in sorted(list(_iter_importer_modules_helper(importer, prefix))):
for name, ispkg in sorted(_iter_importer_modules_helper(importer, prefix)):
# we sort again for consistency of output ordering if importer is not
# a FileFinder (needed in doctest of :func:`sage.misc.dev_tools/load_submodules`)
modname = name.rsplit('.', 1)[-1]
Expand Down
10 changes: 5 additions & 5 deletions src/sage/rings/species.py
Original file line number Diff line number Diff line change
Expand Up @@ -519,9 +519,9 @@ def _element_constructor_(self, G, pi=None, check=True):
else:
raise ValueError("the assignment of sorts to the domain elements must be provided")
elif not isinstance(pi, dict):
pi = {i: v for i, v in enumerate(pi)}
pi = dict(enumerate(pi))
if check:
if not set(pi.keys()).issubset(range(self._arity)):
if not set(pi).issubset(range(self._arity)):
raise ValueError(f"keys of pi (={pi.keys()}) must be in range({self._arity})")
if (sum(len(p) for p in pi.values()) != len(G.domain())
or set(chain.from_iterable(pi.values())) != set(G.domain())):
Expand Down Expand Up @@ -642,7 +642,7 @@ def __contains__(self, x):
G, pi = x
if not isinstance(G, PermutationGroup_generic):
return False
if not set(pi.keys()).issubset(range(self._arity)):
if not set(pi).issubset(range(self._arity)):
return False
if (sum(len(p) for p in pi.values()) != len(G.domain())
or set(chain.from_iterable(pi.values())) != set(G.domain())):
Expand Down Expand Up @@ -1033,7 +1033,7 @@ def _element_constructor_(self, G, pi=None, check=True):
else:
raise ValueError("the assignment of sorts to the domain elements must be provided")
elif not isinstance(pi, dict):
pi = {i: v for i, v in enumerate(pi)}
pi = dict(enumerate(pi))
domain = [e for p in pi.values() for e in p]
if check and len(domain) != len(set(domain)) or set(G.domain()) != set(domain):
raise ValueError(f"values of pi (={pi.values()}) must partition the domain of G (={G.domain()})")
Expand Down Expand Up @@ -2282,7 +2282,7 @@ def _element_constructor_(self, G, pi=None, check=True):
return self._from_dict({self._indices(G, check=check): ZZ.one()})
raise ValueError("the assignment of sorts to the domain elements must be provided")
elif not isinstance(pi, dict):
pi = {i: v for i, v in enumerate(pi)}
pi = dict(enumerate(pi))
return self._from_dict({self._indices(G, pi, check=check): ZZ.one()})

raise ValueError(f"{G} must be an element of the base ring, a permutation group or a pair (X, a) specifying a group action of the symmetric group on pi={pi}")
Expand Down
Loading