Skip to content

Commit 69a8c02

Browse files
author
Release Manager
committed
sagemathgh-38903: a few details in combinat, following ruff and pycodestyle just fixing a few ruff PERF suggestions in 4 files ### 📝 Checklist - [x] The title is concise and informative. - [x] The description explains in detail what this PR is about. - [ ] I have linked a relevant issue or discussion. - [ ] I have created tests covering the changes. - [ ] I have updated the documentation and checked the documentation preview. URL: sagemath#38903 Reported by: Frédéric Chapoton Reviewer(s): Frédéric Chapoton, Martin Rubey, Travis Scrimshaw, Vincent Macri
2 parents a9f3f77 + 826f34f commit 69a8c02

4 files changed

Lines changed: 62 additions & 73 deletions

File tree

src/sage/combinat/rigged_configurations/kleber_tree.py

Lines changed: 30 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -122,11 +122,11 @@ def _draw_tree(tree_node, node_label=True, style_point=None, style_node='fill=wh
122122
start = [0., 0.]
123123
if rpos is None:
124124
rpos = [0., 0.]
125-
draw_point = lambda point: '(%.3f, %.3f)' % (point[0],point[1])
125+
126126
if not tree_node.children:
127127
r = ''
128128
node_name = node_prefix + str(node_id)
129-
r = "\\node (%s) at %s" % (node_name, draw_point(start))
129+
r = "\\node (%s) at (%.3f, %.3f)" % (node_name, *start)
130130
if node_label:
131131
r += "{$%s$};\n" % tree_node._latex_()
132132
else:
@@ -149,7 +149,7 @@ def _draw_tree(tree_node, node_label=True, style_point=None, style_node='fill=wh
149149
nb_children = len(tree_node.children)
150150
half = nb_children // 2
151151
children_str = ''
152-
pos = [start[0],start[1]]
152+
pos = [start[0], start[1]]
153153
start[1] += vspace
154154
lines_str = ''
155155

@@ -184,7 +184,7 @@ def _draw_tree(tree_node, node_label=True, style_point=None, style_node='fill=wh
184184
rpos[0] = pos[0]
185185
rpos[1] = pos[1]
186186
point_str = ''
187-
node_str = "\\node%s (%s) at %s" % (style_node, node_name, draw_point(pos))
187+
node_str = "\\node%s (%s) at (%.3f, %.3f)" % (style_node, node_name, *pos)
188188
if node_label:
189189
node_str += "{$%s$};\n" % tree_node._latex_()
190190
else:
@@ -269,7 +269,7 @@ def depth(self):
269269
sage: n2.depth
270270
1
271271
"""
272-
depth = -1 # Offset
272+
depth = -1 # Offset
273273
cur = self
274274
while cur is not None:
275275
depth += 1
@@ -337,7 +337,7 @@ def multiplicity(self):
337337
mult = Integer(1)
338338
for a, m in self.up_root:
339339
p = self.weight[a]
340-
for r,s in self.parent().B:
340+
for r, s in self.parent().B:
341341
if r == a and s > self.depth:
342342
p -= s - self.depth
343343
mult *= binomial(m + p, m)
@@ -346,7 +346,7 @@ def multiplicity(self):
346346
cur = self.parent_node
347347
while cur.parent_node is not None:
348348
root_diff = cur.up_root - prev_up_root
349-
for a,m in root_diff:
349+
for a, m in root_diff:
350350
p = cur.weight[a]
351351
for r, s in self.parent().B:
352352
if r == a and s > cur.depth:
@@ -636,7 +636,8 @@ def __init__(self, cartan_type, B, classical_ct):
636636
self._CM = self._classical_ct.cartan_matrix().dense_matrix()
637637
self._build_tree()
638638
self._latex_options = dict(edge_labels=True, use_vector_notation=False,
639-
hspace=2.5, vspace=min(-2.5, -0.75*self._classical_ct.rank()))
639+
hspace=2.5,
640+
vspace=min(-2.5, -0.75*self._classical_ct.rank()))
640641

641642
def latex_options(self, **options):
642643
"""
@@ -705,21 +706,19 @@ def _build_tree(self):
705706
# Create an empty node at first step
706707
self.root = KleberTreeNode(self, P.zero(),
707708
self._classical_ct.root_system().root_lattice().zero())
708-
full_list = [self.root] # The list of tree nodes
709+
full_list = [self.root] # The list of tree nodes
709710

710711
n = self._classical_ct.rank()
711712

712713
# Convert the B values into an L matrix
713-
L = []
714714
I = self._classical_ct.index_set()
715-
for i in range(n):
716-
L.append([0])
715+
L = [[0] for _ in range(n)]
717716

718-
for r,s in self.B:
719-
while len(L[0]) < s: # Add more columns if needed
717+
for r, s in self.B:
718+
while len(L[0]) < s: # Add more columns if needed
720719
for row in L:
721720
row.append(0)
722-
L[I.index(r)][s - 1] += 1 # The -1 is for indexing
721+
L[I.index(r)][s - 1] += 1 # The -1 is for indexing
723722

724723
# Perform a special case of the algorithm for the root node
725724
weight_basis = P.basis()
@@ -751,7 +750,7 @@ def _build_tree(self):
751750
for x in full_list:
752751
growth = True
753752
for a in range(n):
754-
for i in range(depth - 1, len(L[a])): # Subtract 1 for indexing
753+
for i in range(depth - 1, len(L[a])): # Subtract 1 for indexing
755754
x.weight += L[a][i] * weight_basis[I[a]]
756755

757756
new_children = [new_child
@@ -824,16 +823,16 @@ def _children_iter(self, node):
824823
# Construct the shifted weight cone
825824
root_weight = node.weight.to_vector()
826825
ieqs = [[root_weight[i]] + list(col)
827-
for i,col in enumerate(self._CM.columns())]
826+
for i, col in enumerate(self._CM.columns())]
828827
# Construct the negative weight cone
829828
for i in range(n):
830829
v = [0] * (n+1)
831830
v[i+1] = -1
832831
ieqs.append(v)
833-
ieqs.append([-1]*(n+1)) # For avoiding the origin
832+
ieqs.append([-1]*(n+1)) # For avoiding the origin
834833
# Construct the bounds for the non-root nodes
835834
if node != self.root:
836-
for i,c in enumerate(node.up_root.to_vector()):
835+
for i, c in enumerate(node.up_root.to_vector()):
837836
v = [0] * (n+1)
838837
v[0] = c
839838
v[i+1] = 1
@@ -849,9 +848,9 @@ def _children_iter(self, node):
849848
# Build the nodes from the polytope
850849
# Sort for a consistent ordering (it is typically a small list)
851850
for pt in sorted(poly.integral_points(), reverse=True):
852-
up_root = Q._from_dict({I[i]: -val for i,val in enumerate(pt) if val != 0},
851+
up_root = Q._from_dict({I[i]: -val for i, val in enumerate(pt) if val != 0},
853852
remove_zeros=False)
854-
wt = node.weight + sum(val * P.simple_root(I[i]) for i,val in enumerate(pt))
853+
wt = node.weight + sum(val * P.simple_root(I[i]) for i, val in enumerate(pt))
855854
yield KleberTreeNode(self, wt, up_root, node)
856855

857856
def _children_iter_vector(self, node):
@@ -895,9 +894,9 @@ def _children_iter_vector(self, node):
895894
converted_root = sum(cols[i] * c for i, c in enumerate(root)
896895
if c != 0)
897896

898-
if all(wt[i] >= val for i,val in enumerate(converted_root)):
899-
wd = {I[i]: wt[i] - val for i,val in enumerate(converted_root)}
900-
rd = {I[i]: val for i,val in enumerate(root) if val != 0}
897+
if all(wt[i] >= val for i, val in enumerate(converted_root)):
898+
wd = {I[i]: wt[i] - val for i, val in enumerate(converted_root)}
899+
rd = {I[i]: val for i, val in enumerate(root) if val != 0}
901900
yield KleberTreeNode(self,
902901
P._from_dict(wd),
903902
Q._from_dict(rd, remove_zeros=False),
@@ -1171,14 +1170,12 @@ def __init__(self, cartan_type, B):
11711170
sage: TestSuite(KT).run(skip='_test_elements')
11721171
"""
11731172
self._folded_ct = cartan_type.as_folding()
1174-
virtual_dims = []
11751173
self.base_dims = B
11761174
sigma = self._folded_ct.folding_orbit()
11771175
gamma = self._folded_ct.scaling_factors()
11781176
classical_ct = self._folded_ct.folding_of().classical()
1179-
for r,s in B:
1180-
for i in sigma[r]:
1181-
virtual_dims.append([i, s * gamma[r]])
1177+
virtual_dims = [[i, s * gamma[r]]
1178+
for r, s in B for i in sigma[r]]
11821179

11831180
KleberTree.__init__(self, cartan_type, virtual_dims, classical_ct)
11841181

@@ -1229,8 +1226,9 @@ def _prune(self, new_child, depth):
12291226
return True
12301227
gamma = self._folded_ct.scaling_factors()
12311228
for a in range(1, len(gamma)):
1232-
if (depth - 1) % gamma[a] != 0 and new_child.up_root[sigma[a][0]] \
1233-
!= new_child.parent_node.up_root[sigma[a][0]]:
1229+
s = sigma[a][0]
1230+
if ((depth - 1) % gamma[a] != 0 and
1231+
new_child.up_root[s] != new_child.parent_node.up_root[s]):
12341232
return True
12351233
return False
12361234

@@ -1371,12 +1369,11 @@ def __init__(self, cartan_type, B):
13711369
self.base_dims = B
13721370
sigma = self._folded_ct.folding_orbit()
13731371
classical_ct = self._folded_ct.folding_of().classical()
1374-
for r,s in B:
1372+
for r, s in B:
13751373
if r == n:
13761374
virtual_dims.extend([[n, s], [n, s]])
13771375
else:
1378-
for i in sigma[r]:
1379-
virtual_dims.append([i, s])
1376+
virtual_dims.extend([i, s] for i in sigma[r])
13801377

13811378
KleberTree.__init__(self, cartan_type, virtual_dims, classical_ct)
13821379

src/sage/combinat/tableau.py

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2055,14 +2055,14 @@ def k_weight(self, k):
20552055
w = self.weight()
20562056
s = self.cells()
20572057

2058-
for l in range(1, len(w)+1):
2058+
for l in range(1, len(w) + 1):
20592059
new_s = [(i, j) for i, j in s if self[i][j] == l]
20602060

20612061
# If there are no elements that meet the condition
2062-
if new_s == []:
2062+
if not new_s:
20632063
res.append(0)
20642064
continue
2065-
x = set((i-j) % (k+1) for i, j in new_s)
2065+
x = {(i - j) % (k + 1) for i, j in new_s}
20662066
res.append(len(x))
20672067

20682068
return res
@@ -2955,9 +2955,8 @@ def row_stabilizer(self):
29552955
# tableau, by including the identity permutation on the set [1..k].
29562956
k = self.size()
29572957
gens = [list(range(1, k + 1))]
2958-
for row in self:
2959-
for j in range(len(row) - 1):
2960-
gens.append((row[j], row[j + 1]))
2958+
gens.extend((row[j], row[j + 1])
2959+
for row in self for j in range(len(row) - 1))
29612960
return PermutationGroup(gens)
29622961

29632962
def column_stabilizer(self):
@@ -7675,9 +7674,9 @@ def __contains__(self, x):
76757674
"""
76767675
if isinstance(x, StandardTableau):
76777676
return True
7678-
elif Tableaux.__contains__(self, x):
7677+
if Tableaux.__contains__(self, x):
76797678
flatx = sorted(c for row in x for c in row)
7680-
return flatx == list(range(1, len(flatx)+1)) and (len(x) == 0 or
7679+
return all(i == fi for i, fi in enumerate(flatx, start=1)) and (len(x) == 0 or
76817680
(all(row[i] < row[i+1] for row in x for i in range(len(row)-1)) and
76827681
all(x[r][c] < x[r+1][c] for r in range(len(x)-1)
76837682
for c in range(len(x[r+1])))
@@ -8183,25 +8182,20 @@ def random_element(self):
81838182
t = [[None] * n for n in p]
81848183

81858184
# Get the cells in the Young diagram
8186-
cells = []
8187-
for i in range(len(p)):
8188-
for j in range(p[i]):
8189-
cells.append((i, j))
8185+
cells = [(i, j) for i in range(len(p)) for j in range(p[i])]
81908186

81918187
m = sum(p)
8192-
while m > 0:
8188+
while m:
81938189
# Choose a cell at random
81948190
cell = random.choice(cells)
81958191

81968192
# Find a corner
81978193
inner_corners = p.corners()
81988194
while cell not in inner_corners:
8199-
hooks = []
8200-
for k in range(cell[1] + 1, p[cell[0]]):
8201-
hooks.append((cell[0], k))
8202-
for k in range(cell[0] + 1, len(p)):
8203-
if p[k] > cell[1]:
8204-
hooks.append((k, cell[1]))
8195+
c0, c1 = cell
8196+
hooks = [(c0, k) for k in range(c1 + 1, p[c0])]
8197+
hooks.extend((k, c1)
8198+
for k in range(c0 + 1, len(p)) if p[k] > c1)
82058199
cell = random.choice(hooks)
82068200

82078201
# Assign m to cell

src/sage/combinat/words/finite_word.py

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -511,10 +511,10 @@ def fcn(n):
511511
length = exp * self.length()
512512
if length in ZZ and length >= 0:
513513
return self._parent(fcn, length=length)
514-
else:
515-
raise ValueError("Power of the word is not defined on the exponent {}:"
516-
" the length of the word ({}) times the exponent ({}) must"
517-
" be a positive integer".format(exp, self.length(), exp))
514+
515+
raise ValueError("Power of the word is not defined on the exponent {}: "
516+
"the length of the word ({}) times the exponent ({}) must "
517+
"be a positive integer".format(exp, self.length(), exp))
518518

519519
def length(self):
520520
r"""
@@ -4153,8 +4153,7 @@ def last_position_dict(self):
41534153
{'1': 3, '2': 6, '3': 5}
41544154
"""
41554155
d = {}
4156-
for i, letter in enumerate(self):
4157-
d[letter] = i
4156+
d.update((letter, i) for i, letter in enumerate(self))
41584157
return d
41594158

41604159
def _pos_in(self, other, p):
@@ -4191,7 +4190,7 @@ def _pos_in(self, other, p):
41914190
"""
41924191
from sage.misc.superseded import deprecation
41934192
deprecation(30187, 'f._pos_in(w, start) is deprecated.'
4194-
' Use w.first_occurrence(f, start) instead.')
4193+
' Use w.first_occurrence(f, start) instead.')
41954194
return other.first_occurrence(self, p)
41964195

41974196
def first_pos_in(self, other):
@@ -4219,7 +4218,7 @@ def first_pos_in(self, other):
42194218
"""
42204219
from sage.misc.superseded import deprecation
42214220
deprecation(30187, 'f.first_pos_in(w) is deprecated.'
4222-
' Use w.first_occurrence(f) instead.')
4221+
' Use w.first_occurrence(f) instead.')
42234222
return other.first_occurrence(self)
42244223

42254224
def find(self, sub, start=0, end=None):
@@ -4440,7 +4439,7 @@ def factor_occurrences_in(self, other):
44404439
"""
44414440
from sage.misc.superseded import deprecation
44424441
deprecation(30187, 'f.factor_occurrences_in(w) is deprecated.'
4443-
' Use w.factor_occurrences_iterator(f) instead.')
4442+
' Use w.factor_occurrences_iterator(f) instead.')
44444443
return other.factor_occurrences_iterator(self)
44454444

44464445
def nb_factor_occurrences_in(self, other):
@@ -4475,7 +4474,7 @@ def nb_factor_occurrences_in(self, other):
44754474
"""
44764475
from sage.misc.superseded import deprecation
44774476
deprecation(30187, 'f.nb_factor_occurrences_in(w) is deprecated.'
4478-
' Use w.number_of_factor_occurrences(f) instead.')
4477+
' Use w.number_of_factor_occurrences(f) instead.')
44794478
return other.number_of_factor_occurrences(self)
44804479

44814480
def nb_subword_occurrences_in(self, other):
@@ -4544,7 +4543,7 @@ def nb_subword_occurrences_in(self, other):
45444543
"""
45454544
from sage.misc.superseded import deprecation
45464545
deprecation(30187, 'f.nb_subword_occurrences_in(w) is deprecated.'
4547-
' Use w.number_of_subword_occurrences(f) instead.')
4546+
' Use w.number_of_subword_occurrences(f) instead.')
45484547
return other.number_of_subword_occurrences(self)
45494548

45504549
def number_of_factor_occurrences(self, other):
@@ -5675,7 +5674,7 @@ def abelian_vectors(self, n):
56755674
size = alphabet.cardinality()
56765675
if size == float('inf'):
56775676
raise TypeError("The alphabet of the parent is infinite; define"
5678-
" the word with a parent on a finite alphabet")
5677+
" the word with a parent on a finite alphabet")
56795678
S = set()
56805679
if n > self.length():
56815680
return S
@@ -6105,8 +6104,8 @@ def abelian_vector(self):
61056104
alphabet = self.parent().alphabet()
61066105
if alphabet.cardinality() is Infinity:
61076106
raise TypeError("The alphabet of the parent is infinite; define "
6108-
"the word with a parent on a finite alphabet or use "
6109-
"evaluation_dict() instead")
6107+
"the word with a parent on a finite alphabet "
6108+
"or use evaluation_dict() instead")
61106109
ev_dict = self.evaluation_dict()
61116110
return [ev_dict.get(a, 0) for a in alphabet]
61126111

@@ -6803,8 +6802,8 @@ def colored_vector(self, x=0, y=0, width='default', height=1, cmap='hsv', thickn
68036802
else:
68046803
ordered_alphabet = self.parent().alphabet()
68056804
dim = float(self.parent().alphabet().cardinality())
6806-
letter_to_integer_dict = {a: i for i, a in
6807-
enumerate(ordered_alphabet)}
6805+
letter_to_integer_dict = {a: i
6806+
for i, a in enumerate(ordered_alphabet)}
68086807
xp = x
68096808
for a in self:
68106809
i = letter_to_integer_dict[a]

src/sage/combinat/words/morphism.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1048,8 +1048,7 @@ def extend_by(self, other):
10481048
raise TypeError("other (=%s) is not a WordMorphism" % other)
10491049

10501050
nv = dict(other._morph)
1051-
for k, v in self._morph.items():
1052-
nv[k] = v
1051+
nv.update(self._morph)
10531052
return WordMorphism(nv)
10541053

10551054
def restrict_domain(self, alphabet):
@@ -2467,9 +2466,9 @@ def dual_map(self, k=1):
24672466
if k == 1:
24682467
from sage.combinat.e_one_star import E1Star
24692468
return E1Star(self)
2470-
else:
2471-
raise NotImplementedError("the dual map E_k^*" +
2472-
" is implemented only for k = 1 (not %s)" % k)
2469+
2470+
raise NotImplementedError("the dual map E_k^* is implemented only "
2471+
"for k = 1 (not %s)" % k)
24732472

24742473
@cached_method
24752474
def rauzy_fractal_projection(self, eig=None, prec=53):

0 commit comments

Comments
 (0)