Skip to content

Commit

Permalink
sagemathgh-38131: code polishing using list comprehension
Browse files Browse the repository at this point in the history
    
simplify code in various places by using more list comprehension, as
suggested by `ruff --select=PERF4`

### 📝 Checklist

- [x] The title is concise and informative.
- [x] The description explains in detail what this PR is about.
    
URL: sagemath#38131
Reported by: Frédéric Chapoton
Reviewer(s): Matthias Köppe
  • Loading branch information
Release Manager committed Jun 4, 2024
2 parents 3afdd1a + 9da8cb2 commit 607786a
Show file tree
Hide file tree
Showing 25 changed files with 55 additions and 107 deletions.
4 changes: 1 addition & 3 deletions src/sage/calculus/desolvers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1647,11 +1647,9 @@ def Dfun(y, t):

# n-dimensional systems:
else:
desc = []
variabs = dvars[:]
variabs.append(ivar)
for de in des:
desc.append(fast_float(de, *variabs))
desc = [fast_float(de, *variabs) for de in des]

def func(y, t):
v = list(y[:])
Expand Down
12 changes: 3 additions & 9 deletions src/sage/coding/code_bounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -482,17 +482,11 @@ def elias_upper_bound(n,q,d,algorithm=None):
libgap.load_package("guava")
return QQ(libgap.UpperBoundElias(n, d, q))
else:
def ff(n,d,w,q):
def ff(n, d, w, q):
return r*n*d*q**n/((w**2-2*r*n*w+r*n*d)*volume_hamming(n,q,w))

def get_list(n,d,q):
I = []
for i in range(1,int(r*n)+1):
if i**2-2*r*n*i+r*n*d > 0:
I.append(i)
return I
I = get_list(n,d,q)
bnd = min([ff(n,d,w,q) for w in I])
I = (i for i in range(1, int(r*n) + 1) if i**2 - 2*r*n*i + r*n*d > 0)
bnd = min([ff(n, d, w, q) for w in I])
return int(bnd)


Expand Down
5 changes: 2 additions & 3 deletions src/sage/coding/code_constructions.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,13 +285,12 @@ def permutation_action(g, v):
else:
V = v.parent()
n = len(list(v))
gv = []
for i in range(n):
gv.append(v[g(i+1)-1])
gv = [v[g(i + 1) - 1] for i in range(n)]
if v_type_list:
return gv
return V(gv)


def walsh_matrix(m0):
"""
This is the generator matrix of a Walsh code. The matrix of
Expand Down
5 changes: 2 additions & 3 deletions src/sage/coding/linear_rank_metric.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,12 +219,11 @@ def from_matrix_representation(w, base_field=None, basis=None):
sub_field = w.base_ring()
if not base_field:
base_field = sub_field.extension(w.nrows())
v = []
extension, to_big_field, from_big_field = base_field.vector_space(sub_field, basis, map=True)
for i in range(w.ncols()):
v.append(to_big_field(w.column(i)))
v = [to_big_field(w.column(i)) for i in range(w.ncols())]
return vector(v)


def rank_weight(c, sub_field=None, basis=None):
r"""
Return the rank of ``c`` as a matrix over ``sub_field``.
Expand Down
5 changes: 1 addition & 4 deletions src/sage/coding/subfield_subcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,10 +254,7 @@ def parity_check_matrix(self):
H[i*m+k, j] = h_vec[k]

H = H.echelon_form()
delete = []
for i in range(H.nrows()):
if H.row(i) == 0:
delete.append(i)
delete = [i for i in range(H.nrows()) if H.row(i) == 0]
M = H.delete_rows(delete)
M.set_immutable()
return M
Expand Down
8 changes: 3 additions & 5 deletions src/sage/combinat/affine_permutation.py
Original file line number Diff line number Diff line change
Expand Up @@ -656,14 +656,12 @@ def promotion(self):
EXAMPLES::
sage: A = AffinePermutationGroup(['A',7,1])
sage: p=A([3, -1, 0, 6, 5, 4, 10, 9])
sage: p = A([3, -1, 0, 6, 5, 4, 10, 9])
sage: p.promotion()
Type A affine permutation with window [2, 4, 0, 1, 7, 6, 5, 11]
"""
l = []
l.append(self[-1]-self.k)
for i in range(1,self.k+1):
l.append(self[i-1]+1)
l = [self[-1] - self.k]
l.extend(self[i] + 1 for i in range(self.k))
return type(self)(self.parent(), l)

def maximal_cyclic_factor(self, typ='decreasing', side='right', verbose=False):
Expand Down
3 changes: 1 addition & 2 deletions src/sage/combinat/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -1865,8 +1865,7 @@ def from_subset(self, S, n) -> Composition:
d.append(n)

co = [d[0]]
for i in range(len(d) - 1):
co.append(d[i + 1] - d[i])
co.extend(d[i + 1] - d[i] for i in range(len(d) - 1))

return self.element_class(self, co)

Expand Down
5 changes: 2 additions & 3 deletions src/sage/game_theory/normal_form_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -1389,9 +1389,8 @@ def _is_complete(self):
sage: example._is_complete()
False
"""
results = []
for profile in self.utilities.values():
results.append(all(type(i) is not bool for i in profile))
results = (all(not isinstance(i, bool) for i in profile)
for profile in self.utilities.values())
return all(results)

def obtain_nash(self, algorithm=False, maximization=True, solver=None):
Expand Down
5 changes: 1 addition & 4 deletions src/sage/homology/chain_complex.py
Original file line number Diff line number Diff line change
Expand Up @@ -1506,10 +1506,7 @@ def torsion_list(self, max_prime, min_prime=2):
diff_dict[i] = current - lower
if i-D in diff_dict:
diff_dict[i-D] -= current - lower
differences = []
for i in diff_dict:
if diff_dict[i] != 0:
differences.append(i)
differences = [i for i, di in diff_dict.items() if di != 0]
answer.append((p, differences))
return answer

Expand Down
17 changes: 6 additions & 11 deletions src/sage/knots/link.py
Original file line number Diff line number Diff line change
Expand Up @@ -512,9 +512,7 @@ def fundamental_group(self, presentation='wirtinger'):
if presentation == 'braid':
b = self.braid()
F = FreeGroup(b.strands())
rels = []
for x in F.gens():
rels.append(x * b / x)
rels = [x * b / x for x in F.gens()]
return F.quotient(rels)
elif presentation == 'wirtinger':
arcs = self.arcs(presentation='pd')
Expand Down Expand Up @@ -1380,9 +1378,7 @@ def oriented_gauss_code(self):
d = edges_graph.all_simple_cycles()
code = []
for i in d:
l = []
for j in i:
l.append(cross_number[j])
l = [cross_number[j] for j in i]
del l[-1]
code.append(l)
oriented_code = [code, orient]
Expand Down Expand Up @@ -2274,11 +2270,10 @@ def seifert_circles(self):
"""
pd = self.pd_code()
available_segments = set(flatten(pd))
result = []
# detect looped segments. They must be their own seifert circles
for a in available_segments:
if any(C.count(a) > 1 for C in pd):
result.append([a])
# detect looped segments. They must be their own Seifert circles
result = [[a] for a in available_segments
if any(C.count(a) > 1 for C in pd)]

# remove the looped segments from the available
for a in result:
available_segments.remove(a[0])
Expand Down
7 changes: 2 additions & 5 deletions src/sage/matroids/matroids_plot_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -817,11 +817,8 @@ def geomrep(M1, B1=None, lineorders1=None, pd=None, sp=False):
lims = tracklims([None, None, None, None], [pnt[0] for pnt in pl],
[pnt[1] for pnt in pl])
elif M.rank() == 2:
nB1 = list(set(list(M.groundset())) - set(B1))
bline = []
for j in nB1:
if M.is_dependent([j, B1[0], B1[1]]):
bline.append(j)
nB1 = set(M.groundset()) - set(B1)
bline = [j for j in nB1 if M.is_dependent([j, B1[0], B1[1]])]
interval = len(bline)+1
if M._cached_info is not None and \
'plot_positions' in M._cached_info.keys() and \
Expand Down
5 changes: 2 additions & 3 deletions src/sage/modular/btquotients/btquotient.py
Original file line number Diff line number Diff line change
Expand Up @@ -990,9 +990,8 @@ def find_containing_affinoid(self, z):
a = 0
pn = 1
val = z.valuation()
L = []
for ii in range(val):
L.append(0)
L = [0 for _ in range(val)]

L.extend(z.expansion())
for n in range(len(L)):
if L[n] != 0:
Expand Down
3 changes: 1 addition & 2 deletions src/sage/modular/btquotients/pautomorphicform.py
Original file line number Diff line number Diff line change
Expand Up @@ -2482,8 +2482,7 @@ def _element_constructor_(self, data):
tmp.append(newtmp)
F.append(newtmp)
A = data.parent()._Sigma0(Matrix(QQ, 2, 2, [0, ~self.prime(), 1, 0]), check=False)
for ii in range(len(data._F)):
F.append(-(A * tmp[ii]))
F.extend(-(A * tmp[ii]) for ii in range(len(data._F)))
vals = self._make_invariant([self._U(o, normalize=False) for o in F])
return self.element_class(self, vals)
if data == 0:
Expand Down
6 changes: 2 additions & 4 deletions src/sage/modular/cusps_nf.py
Original file line number Diff line number Diff line change
Expand Up @@ -1202,14 +1202,12 @@ def NFCusps_ideal_reps_for_levelN(N, nlists=1):
"""
k = N.number_field()
G = k.class_group()
L = []
for i in range(nlists):
L.append([k.ideal(1)])
L = [[k.ideal(1)] for _ in range(nlists)]
it = k.primes_of_degree_one_iter()
for I in G.list():
check = 0
if not I.is_principal():
Iinv = (I.ideal())**(-1)
Iinv = I.ideal()**(-1)
while check < nlists:
J = next(it)
if (J * Iinv).is_principal() and J.is_coprime(N):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1995,11 +1995,10 @@ class of ``self``.
for r in R:
fp = r.fixed_points()[0]

emb_res = emb(fp/G.lam())
emb_res = emb(fp / G.lam())
emb_res.simplify()
emb_res.exactify()
for j in range(1, emb_res.floor()+1):
L.append(G.T(-j).acton(r))
L.extend(G.T(-j).acton(r) for j in range(1, emb_res.floor() + 1))

return L

Expand Down
6 changes: 2 additions & 4 deletions src/sage/monoids/trace_monoid.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,10 +227,8 @@ def dependence_graph(self):
graph = {}

for i, e in enumerate(elements):
edges = []
for v in graph:
if (e, elements[v]) not in independence:
edges.append((v, i))
edges = [(v, i) for v in graph
if (e, elements[v]) not in independence]
graph[i] = []
for v1, v2 in edges:
graph[v1].append(v2)
Expand Down
4 changes: 1 addition & 3 deletions src/sage/numerical/interactive_simplex_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -3978,9 +3978,7 @@ def random_element(m, n, bound=5, special_probability=0.2):
c = random_vector(ZZ, n, x=-bound, y=0).change_ring(QQ)
x_N = list(PolynomialRing(QQ, "x", m + n + 1, order="neglex").gens())
x_N.pop(0)
x_B = []
for i in range(m):
x_B.append(x_N.pop(randint(0, n + m - i - 1)))
x_B = [x_N.pop(randint(0, n + m - i - 1)) for i in range(m)]
return LPDictionary(A, b, c, randint(-bound, bound), x_B, x_N, "z")

def __eq__(self, other):
Expand Down
4 changes: 1 addition & 3 deletions src/sage/parallel/map_reduce.py
Original file line number Diff line number Diff line change
Expand Up @@ -1505,9 +1505,7 @@ def _get_stats(self):
sage: S.run() # indirect doctest
720*x^6 + 120*x^5 + 24*x^4 + 6*x^3 + 2*x^2 + x + 1
"""
res = []
for i in range(self._nprocess):
res.append(tuple(self._workers[i]._stats))
res = [tuple(self._workers[i]._stats) for i in range(self._nprocess)]
self._stats = res

def print_communication_statistics(self, blocksize=16):
Expand Down
5 changes: 1 addition & 4 deletions src/sage/plot/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -1307,10 +1307,7 @@ def rainbow(n, format='hex'):
- Karl-Dieter Crisman (directly use :func:`hsv_to_rgb` for hues)
"""
R = []

for i in range(n):
R.append(tuple(map(float, hsv_to_rgb(i / n, 1, 1))))
R = [tuple(map(float, hsv_to_rgb(i / n, 1, 1))) for i in range(n)]

if format == 'rgbtuple':
return R
Expand Down
10 changes: 5 additions & 5 deletions src/sage/plot/hyperbolic_polygon.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,17 +137,17 @@ def _is_left(point, edge):

sides = []
wn = 0
for i in range(0, len(vertices)-1):
if _intersects(vertices[i], vertices[i+1], point[1]):
sides.append([vertices[i], vertices[i + 1]])
sides = [[vertices[i], vertices[i + 1]] for i in range(len(vertices) - 1)
if _intersects(vertices[i], vertices[i + 1], point[1])]

if _intersects(vertices[-1], vertices[0], point[1]):
sides.append([vertices[-1], vertices[0]])
for side in sides:
if _is_left(point, side):
if side[1][1] > side[0][1]:
wn = wn + 1
wn += 1
if side[1][1] < side[0][1]:
wn = wn - 1
wn -= 1
return wn


Expand Down
7 changes: 3 additions & 4 deletions src/sage/repl/rich_output/preferences.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,9 @@ def _make_doc(self, doc):
doc = dedent(doc)
doc += '\n\n'
doc += 'Allowed values:\n\n'
values_doc = []
values_doc.append('* ``None`` (default): no preference')
for value in self.allowed_values:
values_doc.append('* {0}'.format(repr(value)))
values_doc = ['* ``None`` (default): no preference']
values_doc.extend('* {0}'.format(repr(value))
for value in self.allowed_values)
return doc + '\n\n'.join(values_doc)

def __repr__(self):
Expand Down
9 changes: 3 additions & 6 deletions src/sage/sat/converters/polybori.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,13 +430,10 @@ def permutations(length, equal_zero):
"""
E = []
for num_negated in range(length + 1):
if (((num_negated % 2) ^ ((length + 1) % 2)) == equal_zero):
if ((num_negated % 2) ^ ((length + 1) % 2)) == equal_zero:
continue
start = []
for i in range(num_negated):
start.append(1)
for i in range(length - num_negated):
start.append(-1)
start = [1 for _ in range(num_negated)]
start.extend(-1 for _ in range(length - num_negated))
E.extend(Permutations(start))
return E

Expand Down
6 changes: 3 additions & 3 deletions src/sage/symbolic/random_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def normalize_prob_list(pl, extra=()):
if len(pl) == 0:
return pl
result = []
total = sum([float(p[0]) for p in pl])
total = sum(float(p[0]) for p in pl)
for p in pl:
prob = p[0]
val = p[1]
Expand All @@ -120,8 +120,8 @@ def normalize_prob_list(pl, extra=()):
p_extra = extra
if isinstance(val, list):
norm_val = normalize_prob_list(val, extra=p_extra)
for np in norm_val:
result.append(((prob / total) * np[0], np[1]) + np[2:])
result.extend(((prob / total) * np[0], np[1]) + np[2:]
for np in norm_val)
else:
result.append(((prob / total), val) + p_extra)
return result
Expand Down
8 changes: 3 additions & 5 deletions src/sage/tensor/modules/free_module_tensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1496,12 +1496,10 @@ def del_other_comp(self, basis=None):
if basis is None:
basis = self._fmodule._def_basis
if basis not in self._components:
raise ValueError("the components w.r.t. the {}".format(basis) +
raise ValueError(f"the components w.r.t. the {basis}"
" have not been defined")
to_be_deleted = []
for other_basis in self._components:
if other_basis != basis:
to_be_deleted.append(other_basis)
to_be_deleted = [other_basis for other_basis in self._components
if other_basis != basis]
for other_basis in to_be_deleted:
del self._components[other_basis]

Expand Down
8 changes: 2 additions & 6 deletions src/sage/tests/arxiv_0812_2725.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,12 +204,8 @@ def setp_to_edges(p):
sage: sorted(setp_to_edges(Set(map(Set, [[1,5],[2,4,9],[3],[6,12],[7,10,11],[8]]))))
[[1, 5], [2, 4], [4, 9], [6, 12], [7, 10], [10, 11]]
"""
q = [sorted(b) for b in p]
ans = []
for b in q:
for n in range(len(b) - 1):
ans.append(b[n: n + 2])
return ans
q = (sorted(b) for b in p)
return [b[n: n + 2] for b in q for n in range(len(b) - 1)]


def dcrossvec_setp(n):
Expand Down

0 comments on commit 607786a

Please sign in to comment.