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

fixing most ruff PERF4 warnings in combinat #38635

Merged
merged 1 commit into from
Sep 15, 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: 1 addition & 4 deletions src/sage/combinat/composition_tableau.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,10 +211,7 @@ def descent_set(self):
sage: CompositionTableau([[1],[3,2],[4,4]]).descent_set()
[1, 3]
"""
cols = {}
for row in self:
for col, i in enumerate(row):
cols[i] = col
cols = {i: col for row in self for col, i in enumerate(row)}
return sorted(i for i in cols if i + 1 in cols and cols[i + 1] >= cols[i])

def descent_composition(self):
Expand Down
9 changes: 3 additions & 6 deletions src/sage/combinat/diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,12 +336,9 @@ def _latex_(self):

lr = r'\def\lr#1{\multicolumn{1}{|@{\hspace{.6ex}}c@{\hspace{.6ex}}|}{\raisebox{-.3ex}{$#1$}}}'

array = []
for i in range(self._n_rows):
row = []
for j in range(self._n_cols):
row.append("\\phantom{x}" if (i, j) in self else None)
array.append(row)
array = [[("\\phantom{x}" if (i, j) in self else None)
for j in range(self._n_cols)]
for i in range(self._n_rows)]

def end_line(r):
# give the line ending to row ``r``
Expand Down
10 changes: 4 additions & 6 deletions src/sage/combinat/diagram_algebras.py
Original file line number Diff line number Diff line change
Expand Up @@ -3013,7 +3013,7 @@ def jucys_murphy_element(self, i):
sage: L = [P.L(i/2) for i in range(1,2*k+1)]
sage: all(x.dual() == x for x in L)
True
sage: all(x * y == y * x for x in L for y in L) # long time
sage: all(x * y == y * x for x, y in Subsets(L, 2)) # long time
True
sage: Lsum = sum(L)
sage: gens = [P.s(i) for i in range(1,k)]
Expand Down Expand Up @@ -3045,13 +3045,13 @@ def jucys_murphy_element(self, i):
The same tests for a half integer partition algebra::
sage: k = 9/2
sage: k = 7/2
sage: R.<n> = QQ[]
sage: P = PartitionAlgebra(k, n)
sage: L = [P.L(i/2) for i in range(1,2*k+1)]
sage: all(x.dual() == x for x in L)
True
sage: all(x * y == y * x for x in L for y in L) # long time
sage: all(x * y == y * x for x, y in Subsets(L, 2)) # long time
True
sage: Lsum = sum(L)
sage: gens = [P.s(i) for i in range(1,k-1/2)]
Expand Down Expand Up @@ -5847,11 +5847,9 @@ def to_Brauer_partition(l, k=None):
True
"""
L = to_set_partition(l, k=k)
L2 = []
paired = []
not_paired = []
for i in L:
L2.append(list(i))
L2 = (list(i) for i in L)
for i in L2:
if len(i) > 2:
raise ValueError("blocks must have size at most 2, but {} has {}".format(i, len(i)))
Expand Down
5 changes: 1 addition & 4 deletions src/sage/combinat/dlx.py
Original file line number Diff line number Diff line change
Expand Up @@ -484,10 +484,7 @@ def AllExactCovers(M):
ones = []
r = 1 # damn 1-indexing
for R in M.rows():
row = []
for i in range(len(R)):
if R[i]:
row.append(i + 1) # damn 1-indexing
row = [i for i, Ri in enumerate(R, start=1) if Ri]
ones.append([r, row])
r += 1
for s in DLXMatrix(ones):
Expand Down
6 changes: 3 additions & 3 deletions src/sage/combinat/finite_state_machine.py
Original file line number Diff line number Diff line change
Expand Up @@ -9437,9 +9437,9 @@ def graph(self, edge_labels='words_in_out'):
transitions = state.transitions
if not transitions:
isolated_vertices.append(state.label())
for t in transitions:
graph_data.append((t.from_state.label(), t.to_state.label(),
label_fct(t)))
graph_data.extend((t.from_state.label(), t.to_state.label(),
label_fct(t))
for t in transitions)

G = DiGraph(graph_data, multiedges=True, loops=True)
G.add_vertices(isolated_vertices)
Expand Down
10 changes: 4 additions & 6 deletions src/sage/combinat/free_dendriform_algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -939,14 +939,12 @@ def merge(self, other):
return self
ret = list(self.vars)
cur_vars = set(ret)
for v in other.vars:
if v not in cur_vars:
ret.append(v)
ret.extend(v for v in other.vars if v not in cur_vars)
return DendriformFunctor(Alphabet(ret))
else:
return None

def _repr_(self):
return None

def _repr_(self) -> str:
"""
TESTS::
Expand Down
10 changes: 4 additions & 6 deletions src/sage/combinat/free_prelie_algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -1023,14 +1023,12 @@ def merge(self, other):
return self
ret = list(self.vars)
cur_vars = set(ret)
for v in other.vars:
if v not in cur_vars:
ret.append(v)
ret.extend(v for v in other.vars if v not in cur_vars)
return PreLieFunctor(Alphabet(ret))
else:
return None

def _repr_(self):
return None

def _repr_(self) -> str:
"""
TESTS::
Expand Down
24 changes: 9 additions & 15 deletions src/sage/combinat/gelfand_tsetlin_patterns.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,11 +302,9 @@ def boxed_entries(self) -> tuple:
sage: G.boxed_entries()
((1, 0),)
"""
ret = []
for i in range(1, len(self)):
for j in range(len(self[i])):
if self[i][j] == self[i - 1][j]:
ret.append((i, j))
ret = [(i, j) for i in range(1, len(self))
for j, selfij in enumerate(self[i])
if selfij == self[i - 1][j]]
return tuple(ret)

@cached_method
Expand All @@ -324,11 +322,9 @@ def circled_entries(self) -> tuple:
sage: G.circled_entries()
((1, 1), (2, 0))
"""
ret = []
for i in range(1, len(self)):
for j in range(len(self[i])):
if self[i][j] == self[i - 1][j + 1]:
ret.append((i, j))
ret = [(i, j) for i in range(1, len(self))
for j, selfij in enumerate(self[i])
if selfij == self[i - 1][j + 1]]
return tuple(ret)

@cached_method
Expand All @@ -349,11 +345,9 @@ def special_entries(self) -> tuple:
sage: G.special_entries()
((2, 0),)
"""
ret = []
for i in range(1, len(self)):
for j in range(len(self[i])):
if self[i-1][j] > self[i][j] and self[i][j] > self[i-1][j+1]:
ret.append((i, j))
ret = [(i, j) for i in range(1, len(self))
for j, selfij in enumerate(self[i])
if self[i - 1][j] > selfij > self[i - 1][j + 1]]
return tuple(ret)

def number_of_boxes(self) -> int:
Expand Down
6 changes: 1 addition & 5 deletions src/sage/combinat/graph_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,11 +236,7 @@ def paths_from_source_to_target(self, source, target):
[[2, 3, 4], [2, 4]]
"""
source_paths = self.outgoing_paths(source)
paths = []
for path in source_paths:
if path[-1] == target:
paths.append(path)
return paths
return [path for path in source_paths if path[-1] == target]

def paths(self):
"""
Expand Down
10 changes: 4 additions & 6 deletions src/sage/combinat/integer_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -1174,19 +1174,17 @@ def _list_rec(self, n, k):
EXAMPLES::

sage: IV = IntegerVectors(2,3)
sage: IV._list_rec(2,3)
sage: list(IV._list_rec(2,3))
[(2, 0, 0), (1, 1, 0), (1, 0, 1), (0, 2, 0), (0, 1, 1), (0, 0, 2)]
"""
res = []

if k == 1:
return [(n, )]
yield (n,)
return

for nbar in range(n + 1):
n_diff = n - nbar
for rest in self._list_rec(nbar, k - 1):
res.append((n_diff,) + rest)
return res
yield (n_diff,) + rest

def __iter__(self):
"""
Expand Down
9 changes: 3 additions & 6 deletions src/sage/combinat/knutson_tao_puzzles.py
Original file line number Diff line number Diff line change
Expand Up @@ -2064,12 +2064,9 @@ def _fill_piece(self, nw_label, ne_label, pieces) -> list[PuzzlePiece]:
sage: ps._fill_piece('0', '0', ps._bottom_deltas)
[0/0\0]
"""
output = []
for piece in pieces:
if (piece['north_west'] == nw_label and
piece['north_east'] == ne_label):
output.append(piece)
return output
return [piece for piece in pieces
if (piece['north_west'] == nw_label and
piece['north_east'] == ne_label)]

@cached_method
def _fill_strip(self, nw_labels, ne_label, pieces, final_pieces=None):
Expand Down
8 changes: 2 additions & 6 deletions src/sage/combinat/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,11 +202,7 @@ def _monomial_exponent_to_lower_factorial(me, x):
sage: _monomial_exponent_to_lower_factorial(([2,2,2]),a)
x^2*y^2*z^2 - x^2*y^2*z - x^2*y*z^2 - x*y^2*z^2 + x^2*y*z + x*y^2*z + x*y*z^2 - x*y*z
"""
terms = []
for i in range(len(me)):
for j in range(me[i]):
terms.append( x[i]-j )
return prod(terms)
return prod(x[i] - j for i, mei in enumerate(me) for j in range(mei))


def umbral_operation(poly):
Expand Down Expand Up @@ -235,7 +231,7 @@ def umbral_operation(poly):
exponents = poly.exponents()
coefficients = poly.coefficients()
length = len(exponents)
return sum( [coefficients[i]*_monomial_exponent_to_lower_factorial(exponents[i],x) for i in range(length)] )
return sum(coefficients[i]*_monomial_exponent_to_lower_factorial(exponents[i], x) for i in range(length))


class IterableFunctionCall:
Expand Down
14 changes: 5 additions & 9 deletions src/sage/combinat/parallelogram_polyomino.py
Original file line number Diff line number Diff line change
Expand Up @@ -1974,12 +1974,9 @@ def widths(self) -> list:
sage: pp.widths()
[]
"""
widths = []
uw = self.upper_widths()
lw = self.lower_widths()
for i in range(len(lw)):
widths.append(uw[i] - lw[i])
return widths
return [up - lo for up, lo in zip(uw, lw)]

def degree_convexity(self) -> int:
r"""
Expand Down Expand Up @@ -3387,11 +3384,10 @@ def get_BS_nodes(self):
sage: pp.set_options(drawing_components=dict(tree=True))
sage: view(pp) # not tested
"""
result = []
for h in range(1, self.height()):
result.append(self._get_node_position_at_row(h))
for w in range(1, self.width()):
result.append(self._get_node_position_at_column(w))
result = [self._get_node_position_at_row(h)
for h in range(1, self.height())]
result.extend(self._get_node_position_at_column(w)
for w in range(1, self.width()))
return result

def get_right_BS_nodes(self):
Expand Down
13 changes: 4 additions & 9 deletions src/sage/combinat/partition_algebra.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,9 +364,7 @@ def __iter__(self):
True
"""
for p in Permutations(self.k):
res = []
for i in range(self.k):
res.append(Set([i + 1, -p[i]]))
res = [Set([i, -pi]) for i, pi in enumerate(p, start=1)]
yield self.element_class(self, res)


Expand Down Expand Up @@ -433,10 +431,7 @@ def __iter__(self):
{{1, -3}, {2, -2}, {4, -4}, {3, -1}}]
"""
for p in Permutations(self.k):
res = []
for i in range(self.k):
res.append(Set([i + 1, -p[i]]))

res = [Set([i, -pi]) for i, pi in enumerate(p, start=1)]
res.append(Set([self.k + 1, -self.k - 1]))
yield self.element_class(self, res)

Expand Down Expand Up @@ -1941,8 +1936,8 @@ def to_set_partition(l, k=None):
to_be_added -= spart
sp.append(spart)

for singleton in to_be_added:
sp.append(Set([singleton]))
sp.extend(Set([singleton])
for singleton in to_be_added)

return Set(sp)

Expand Down
11 changes: 5 additions & 6 deletions src/sage/combinat/ribbon_shaped_tableau.py
Original file line number Diff line number Diff line change
Expand Up @@ -350,18 +350,17 @@ def from_permutation(self, p):
[[1, 2], [3]],
[[1], [2], [3]]]
"""
if p == []:
if not p:
return self.element_class(self, [])

comp = p.descents()

if comp == []:
if not comp:
return self.element_class(self, [p[:]])

r = []
r.append([p[j] for j in range(comp[0])])
for i in range(len(comp) - 1):
r.append([p[j] for j in range(comp[i], comp[i + 1])])
r = [[p[j] for j in range(comp[0])]]
r.extend([p[j] for j in range(comp[i], comp[i + 1])]
for i in range(len(comp) - 1))
r.append([p[j] for j in range(comp[-1], len(p))])
r.reverse()
return self.element_class(self, r)
Expand Down
6 changes: 2 additions & 4 deletions src/sage/combinat/rsk.py
Original file line number Diff line number Diff line change
Expand Up @@ -2957,12 +2957,10 @@ def _backward_format_output(self, obj1, obj2, output):
if j == 0:
df.append([])
if j > 0 and obj1[j] < obj1[j-1]:
for _ in range(obj1[j-1]-obj1[j]):
df.append([])
df.extend([] for _ in range(obj1[j-1]-obj1[j]))
df[-1].append(obj2[j])
if obj1:
for a in range(obj1[-1]-1):
df.append([])
df.extend([] for a in range(obj1[-1]-1))
# If biword is empty, return a decreasing factorization with 1 factor
else:
df.append([])
Expand Down
8 changes: 5 additions & 3 deletions src/sage/combinat/shifted_primed_tableau.py
Original file line number Diff line number Diff line change
Expand Up @@ -2716,9 +2716,11 @@ def _add_strip(sub_tab, full_tab, length):
if sub_tab and len(sub_tab) < len(full_tab):
plat_list.append(min(sub_tab[-1] + primed_strip[-2] - 1,
full_tab[len(sub_tab)]))
for row in reversed(range(1, len(sub_tab))):
plat_list.append(min(sub_tab[row-1]+primed_strip[row-1]-1, full_tab[row])
- sub_tab[row] - primed_strip[row])
plat_list.extend(
min(sub_tab[row-1] + primed_strip[row-1] - 1, full_tab[row])
- sub_tab[row] - primed_strip[row]
for row in reversed(range(1, len(sub_tab))))

if sub_tab:
plat_list.append(full_tab[0] - sub_tab[0] - primed_strip[0])
else:
Expand Down
Loading
Loading