Skip to content

Commit

Permalink
gh-38323: some fixes for ruff code C41 (about loops and iteration)
Browse files Browse the repository at this point in the history
    
a few minor code fixes in various places, about a better use of loops

https://docs.astral.sh/ruff/rules/#flake8-comprehensions-c4

### 📝 Checklist

- [x] The title is concise and informative.
- [x] The description explains in detail what this PR is about.
    
URL: #38323
Reported by: Frédéric Chapoton
Reviewer(s): Frédéric Chapoton, Matthias Köppe
  • Loading branch information
Release Manager committed Aug 9, 2024
2 parents 5be4da7 + ceb9913 commit 8d9da51
Show file tree
Hide file tree
Showing 12 changed files with 46 additions and 47 deletions.
6 changes: 3 additions & 3 deletions src/sage/combinat/specht_module.py
Original file line number Diff line number Diff line change
Expand Up @@ -920,9 +920,9 @@ def intrinsic_arrangement(self, base_ring=None):
G = self._semigroup

def t(i, j):
ret = [i for i in range(1, SGA.n+1)]
ret[i-1] = j
ret[j-1] = i
ret = list(range(1, SGA.n + 1))
ret[i - 1] = j
ret[j - 1] = i
return SGA(G(ret))

# Construct the hyperplanes
Expand Down
6 changes: 3 additions & 3 deletions src/sage/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,9 +429,9 @@ def cython_aliases(required_modules=None, optional_modules=None):
else:
continue
aliases["ECL_CFLAGS"] = list(filter(lambda s: not s.startswith('-I'), ecl_cflags))
aliases["ECL_INCDIR"] = list(map(lambda s: s[2:], filter(lambda s: s.startswith('-I'), ecl_cflags)))
aliases["ECL_LIBDIR"] = list(map(lambda s: s[2:], filter(lambda s: s.startswith('-L'), ecl_libs)))
aliases["ECL_LIBRARIES"] = list(map(lambda s: s[2:], filter(lambda s: s.startswith('-l'), ecl_libs)))
aliases["ECL_INCDIR"] = [s[2:] for s in filter(lambda s: s.startswith('-I'), ecl_cflags)]
aliases["ECL_LIBDIR"] = [s[2:] for s in filter(lambda s: s.startswith('-L'), ecl_libs)]
aliases["ECL_LIBRARIES"] = [s[2:] for s in filter(lambda s: s.startswith('-l'), ecl_libs)]
aliases["ECL_LIBEXTRA"] = list(filter(lambda s: not s.startswith(('-l', '-L')), ecl_libs))
continue
else:
Expand Down
11 changes: 5 additions & 6 deletions src/sage/geometry/hyperplane_arrangement/arrangement.py
Original file line number Diff line number Diff line change
Expand Up @@ -1808,7 +1808,7 @@ def face_vector(self):
return v

@cached_method
def _parallel_hyperplanes(self):
def _parallel_hyperplanes(self) -> tuple:
"""
Return the hyperplanes grouped into parallel sets.
Expand Down Expand Up @@ -1845,18 +1845,17 @@ def _parallel_hyperplanes(self):
(Hyperplane t0 + 0*t1 - t2 + 0, (1, 0, -1), 0)))
"""
V = self.parent().ambient_space()
parallels = dict()
parallels = {}
for hyperplane in self:
through_origin = V([list(hyperplane.A()), 0]).primitive(signed=False)
parallel_planes = parallels.get(through_origin, [])
A = through_origin.A()
b = hyperplane.b() * (A / hyperplane.A())
parallel_planes.append([b, (hyperplane, A, b)])
parallels[through_origin] = parallel_planes
parallels = [tuple(tuple(hyperplane[1]
for hyperplane in sorted(parallels[key])))
for key in parallels.keys()]
return tuple(sorted(parallels))
parallels = sorted(tuple(hyperplane[1] for hyperplane in sorted(value))
for key, value in parallels.items())
return tuple(parallels)

def vertices(self, exclude_sandwiched=False):
"""
Expand Down
6 changes: 3 additions & 3 deletions src/sage/graphs/generators/smallgraphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2951,7 +2951,7 @@ def GritsenkoGraph():
(33, 49), (33, 51), (33, 57), (33, 61)]
# use the union of the orbits of a on the edges
return Graph(reduce(lambda x, y: x + y,
map(lambda o: a.orbit(o, action='OnSets'), edges)),
(a.orbit(o, action='OnSets') for o in edges)),
format='list_of_edges',
name="Gritsenko strongly regular graph")

Expand Down Expand Up @@ -4734,7 +4734,7 @@ def _EllipticLinesProjectivePlaneScheme(k):
gp = libgap.Action(g, libgap.Orbit(g, l, libgap.OnLines), libgap.OnLines)
orbitals = gp.Orbits(list(product(gp.Orbit(1), gp.Orbit(1))),
libgap.OnTuples)
mats = map(lambda o: [(int(x[0]) - 1, int(x[1]) - 1) for x in o], orbitals)
mats = ([(int(x[0]) - 1, int(x[1]) - 1) for x in o] for o in orbitals)
return [matrix((q * (q - 1)) // 2, lambda i, j: 1 if (i, j) in x else 0)
for x in mats]

Expand Down Expand Up @@ -4934,7 +4934,7 @@ def JankoKharaghaniTonchevGraph():
301, 304, 308, 309, 310, 312, 313, 314, 316, 317, 318)
Gamma = Graph(multiedges=False, name='Janko-Kharaghani-Tonchev')
for i, b in ((1, B1), (163, B163)):
for j in map(lambda x: x[0], st.OrbitsDomain(b)):
for j in (x[0] for x in st.OrbitsDomain(b)):
Gamma.add_edges(map(tuple, G.Orbit(libgap.Set([i, j]), libgap.OnSets)))
Gamma.relabel(range(Gamma.order()))
return Gamma
Expand Down
2 changes: 1 addition & 1 deletion src/sage/graphs/schnyder.py
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,7 @@ def _compute_coordinates(g, x):
for v in g.vertices(sort=False):
if v not in [t1.label, t2.label, t3.label]:
# Computing coordinates for v
r = list((0, 0, 0))
r = [0, 0, 0]

for i in [0, 1, 2]:
# Computing size of region i:
Expand Down
4 changes: 2 additions & 2 deletions src/sage/knots/link.py
Original file line number Diff line number Diff line change
Expand Up @@ -4033,7 +4033,7 @@ def _knotinfo_matching_list(self):
Sn = KnotInfoSeries(cr, is_knot, False)
la = Sa.lower_list(oriented=True, comp=co, det=det, homfly=Hp)
ln = Sn.lower_list(oriented=True, comp=co, det=det, homfly=Hp)
l = sorted(list(set(la + ln)))
l = sorted(set(la + ln))

br = self.braid()
br_ind = br.strands()
Expand Down Expand Up @@ -4452,7 +4452,7 @@ def answer_list(l):

if not l[0].is_knot():
S = l[0].series(oriented=True)
if set(list(S)) == set(l):
if set(S) == set(l):
return answer_unori(S)

raise NotImplementedError('this link cannot be uniquely determined%s' % non_unique_hint)
Expand Down
27 changes: 14 additions & 13 deletions src/sage/matroids/matroids_plot_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,11 +168,13 @@ def it(M, B1, nB1, lps):
# loop over L1,L2,L3
cc = interval*j
pts[i[j-1]] = (cc*pt1[0]+(1-cc)*pt2[0], cc*pt1[1]+(1-cc)*pt2[1])
trilines = [list(set(x)) for x in lines if len(x) >= 3]
curvedlines = [list(set(list(x)).difference(set(lps)))
for x in M.flats(2) if set(list(x)) not in trilines if
len(list(x)) >= 3]
nontripts = [i for i in nB1 if i not in pts.keys()]
trilines = [set(x) for x in lines if len(x) >= 3]
set_lps = set(lps)
curvedlines = [list(sx.difference(set_lps))
for x in M.flats(2) if (sx := set(x)) not in trilines
and len(list(x)) >= 3]
nontripts = [i for i in nB1 if i not in pts]
trilines = [list(s) for s in trilines]
return pts, trilines, nontripts, curvedlines


Expand Down Expand Up @@ -206,12 +208,12 @@ def trigrid(tripts):
This method does NOT do any checks.
"""
pairs = [[0, 1], [1, 2], [0, 2]]
cpt = list((float(tripts[0][0]+tripts[1][0]+tripts[2][0])/3,
float(tripts[0][1]+tripts[1][1]+tripts[2][1])/3))
cpt = [float(tripts[0][0] + tripts[1][0] + tripts[2][0]) / 3,
float(tripts[0][1] + tripts[1][1] + tripts[2][1]) / 3]
grid = [cpt]
for p in pairs:
pt = list((float(tripts[p[0]][0]+tripts[p[1]][0]+cpt[0])/3,
float(tripts[p[0]][1]+tripts[p[1]][1]+cpt[1])/3))
for p, q in pairs:
pt = [float(tripts[p][0] + tripts[q][0] + cpt[0]) / 3,
float(tripts[p][1] + tripts[q][1] + cpt[1]) / 3]
grid.append(pt)
return grid

Expand Down Expand Up @@ -852,9 +854,8 @@ def geomrep(M1, B1=None, lineorders1=None, pd=None, sp=False):
trilines.extend(curvedlines)
else:
pts2 = M._cached_info['plot_positions']
trilines = [list(set(list(x)).difference(L | P))
for x in M1.flats(2)
if len(list(x)) >= 3]
trilines = [list(set(x).difference(L | P))
for x in M1.flats(2) if len(list(x)) >= 3]
pl = [list(x) for x in pts2.values()]
lims = tracklims([None, None, None, None], [pt[0] for pt in pl],
[pt[1] for pt in pl])
Expand Down
4 changes: 2 additions & 2 deletions src/sage/rings/lazy_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,7 @@ def coefficients(self, n=None):
return lazy_list(coeffs)

# flatten out the generator in the multivariate case
return lazy_list(chain.from_iterable(map(lambda coeff: coeff.coefficients(), coeffs)))
return lazy_list(chain.from_iterable((coeff.coefficients() for coeff in coeffs)))

if isinstance(self, LazyPowerSeries) and self.parent()._arity == 1:
from sage.misc.superseded import deprecation
Expand All @@ -486,7 +486,7 @@ def coefficients(self, n=None):
return list(islice(coeffs, n))

# flatten out the generator in the multivariate case
return list(islice(chain.from_iterable(map(lambda coeff: coeff.coefficients(), coeffs)), n))
return list(islice(chain.from_iterable((coeff.coefficients() for coeff in coeffs)), n))

def map_coefficients(self, f):
r"""
Expand Down
5 changes: 2 additions & 3 deletions src/sage/rings/number_field/galois_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,9 +573,8 @@ def _elts(self):
"""
if self._gc_numbering:
# PARI computes all the elements of self anyway, so we might as well store them
return sorted([self(x, check=False) for x in self._pari_data[5]])
else:
return sorted(list(self.iteration()))
return sorted(self(x, check=False) for x in self._pari_data[5])
return sorted(self.iteration())

@lazy_attribute
def _gens(self):
Expand Down
2 changes: 1 addition & 1 deletion src/sage/rings/valuation/augmented_valuation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1508,7 +1508,7 @@ def lift_to_key(self, F, check=True):
coefficients[-2] %= self.phi()
tau = self.value_group().index(self._base_valuation.value_group())
vf = self._mu * tau * F.degree()
ret = self.domain().change_ring(self.domain())([c for c in coefficients])(self.phi()**tau)
ret = self.domain().change_ring(self.domain())(coefficients)(self.phi()**tau)
ret = self.simplify(ret, error=vf, force=True)
ret = ret.map_coefficients(_lift_to_maximal_precision)
assert (ret == self.phi()) == (F == F.parent().gen())
Expand Down
18 changes: 9 additions & 9 deletions src/sage/tensor/modules/comp.py
Original file line number Diff line number Diff line change
Expand Up @@ -1599,7 +1599,7 @@ def __add__(self, other):
if nproc != 1:
# Parallel computation
lol = lambda lst, sz: [lst[i:i+sz] for i in range(0, len(lst), sz)]
ind_list = [ind for ind in other._comp]
ind_list = list(other._comp)
ind_step = max(1, int(len(ind_list)/nproc/2))
local_list = lol(ind_list, ind_step)
# list of input parameters
Expand Down Expand Up @@ -1822,7 +1822,7 @@ def __mul__(self, other):
if nproc != 1:
# Parallel computation
lol = lambda lst, sz: [lst[i:i+sz] for i in range(0, len(lst), sz)]
ind_list = [ind for ind in result.non_redundant_index_generator()]
ind_list = list(result.non_redundant_index_generator())
ind_step = max(1, int(len(ind_list)/nproc))
local_list = lol(ind_list, ind_step)
# list of input parameters:
Expand Down Expand Up @@ -2344,7 +2344,7 @@ def compprod(a, b):
# parallel computation
nproc = Parallelism().get('tensor')
lol = lambda lst, sz: [lst[i:i+sz] for i in range(0, len(lst), sz)]
ind_list = [ind for ind in res.non_redundant_index_generator()]
ind_list = list(res.non_redundant_index_generator())
ind_step = max(1, int(len(ind_list)/nproc/2))
local_list = lol(ind_list, ind_step)

Expand Down Expand Up @@ -3526,7 +3526,7 @@ def __add__(self, other):
# Parallel computation
lol = lambda lst, sz: [lst[i:i+sz] for i in
range(0, len(lst), sz)]
ind_list = [ind for ind in other._comp]
ind_list = list(other._comp)
ind_step = max(1, int(len(ind_list)/nproc/2))
local_list = lol(ind_list, ind_step)
# list of input parameters
Expand Down Expand Up @@ -3580,7 +3580,7 @@ def paral_sum(a, b, local_list_ind):
if nproc != 1:
# Parallel computation
lol = lambda lst, sz: [lst[i:i+sz] for i in range(0, len(lst), sz)]
ind_list = [ind for ind in result.non_redundant_index_generator()]
ind_list = list(result.non_redundant_index_generator())
ind_step = max(1, int(len(ind_list)/nproc/2))
local_list = lol(ind_list, ind_step)
# definition of the list of input parameters
Expand Down Expand Up @@ -3683,7 +3683,7 @@ def __mul__(self, other):
if nproc != 1:
# Parallel computation
lol = lambda lst, sz: [lst[i:i+sz] for i in range(0, len(lst), sz)]
ind_list = [ind for ind in self._comp]
ind_list = list(self._comp)
ind_step = max(1, int(len(ind_list)/nproc))
local_list = lol(ind_list, ind_step)
# list of input parameters:
Expand Down Expand Up @@ -4003,7 +4003,7 @@ def non_redundant_index_generator(self):
if ind[isym[k-1]] == imax:
return
ind[pos] = ind[isym[k-1]] + 1
if not any([pos in isym for isym in sym]) and not any([pos in isym for isym in antisym]):
if not any(pos in isym for isym in sym) and not any(pos in isym for isym in antisym):
sym.append([pos]) # treat non-symmetrized indices as being symmetrized with themselves
while True:
yield tuple(ind)
Expand Down Expand Up @@ -5038,7 +5038,7 @@ def __add__(self, other):
# parallel sum
lol = lambda lst, sz: [lst[i:i+sz] for i
in range(0, len(lst), sz)]
ind_list = [ind for ind in other._comp]
ind_list = list(other._comp)
ind_step = max(1, int(len(ind_list)/nproc/2))
local_list = lol(ind_list, ind_step)
# definition of the list of input parameters
Expand Down Expand Up @@ -5329,7 +5329,7 @@ def __add__(self, other):
if nproc != 1:
# Parallel computation
lol = lambda lst, sz: [lst[i:i+sz] for i in range(0, len(lst), sz)]
ind_list = [ind for ind in other._comp]
ind_list = list(other._comp)
ind_step = max(1, int(len(ind_list)/nproc/2))
local_list = lol(ind_list, ind_step)
# list of input parameters
Expand Down
2 changes: 1 addition & 1 deletion src/sage/tensor/modules/free_module_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1108,7 +1108,7 @@ class :class:`~sage.tensor.modules.comp.Components`
if nproc != 1:
# Parallel computation
lol = lambda lst, sz: [lst[i:i+sz] for i in range(0, len(lst), sz)]
ind_list = [ind for ind in new_comp.non_redundant_index_generator()]
ind_list = list(new_comp.non_redundant_index_generator())
ind_step = max(1, int(len(ind_list)/nproc/2))
local_list = lol(ind_list, ind_step)
# list of input parameters
Expand Down

0 comments on commit 8d9da51

Please sign in to comment.