Skip to content

Commit

Permalink
sagemathgh-36392: a few details in combinat, as suggested by ruff
Browse files Browse the repository at this point in the history
    
this is fixing a few things in combinat, as suggested by the very fast
linter `ruff`

### 📝 Checklist

- [x] The title is concise, informative, and self-explanatory.
- [x] The description explains in detail what this PR is about.
    
URL: sagemath#36392
Reported by: Frédéric Chapoton
Reviewer(s): David Coudert
  • Loading branch information
Release Manager committed Oct 11, 2023
2 parents d0073b2 + bdc43e7 commit 384493c
Show file tree
Hide file tree
Showing 10 changed files with 32 additions and 32 deletions.
26 changes: 13 additions & 13 deletions src/sage/combinat/bijectionist.py
Original file line number Diff line number Diff line change
Expand Up @@ -1672,7 +1672,7 @@ def different_values(p1, p2):
def merge_until_split():
for tZ in list(multiple_preimages):
tP = multiple_preimages[tZ]
for i2 in range(len(tP)-1, -1, -1):
for i2 in range(len(tP) - 1, -1, -1):
for i1 in range(i2):
try:
solution = different_values(tP[i1], tP[i2])
Expand Down Expand Up @@ -1767,17 +1767,16 @@ def possible_values(self, p=None, optimal=False):
{'a': {0, 1}, 'b': {0, 1}}
sage: bij.possible_values(p="a", optimal=True)
{'a': set(), 'b': set()}
"""
# convert input to set of block representatives
blocks = set()
if p in self._A:
blocks.add(self._P.find(p))
elif type(p) is list: # TODO: this looks very brittle
elif isinstance(p, list): # TODO: this looks very brittle
for p1 in p:
if p1 in self._A:
blocks.add(self._P.find(p1))
elif type(p1) is list:
elif isinstance(p1, list):
for p2 in p1:
blocks.add(self._P.find(p2))

Expand Down Expand Up @@ -2084,7 +2083,7 @@ def minimal_subdistributions_blocks_iterator(self):
minimal_subdistribution.add_constraint(sum(D[p] for p in P) >= 1)
for p in P:
minimal_subdistribution.add_constraint(D[p] <= len(self._P.root_to_elements_dict()[p]))
minimal_subdistribution.add_constraint(X[p]*len(self._P.root_to_elements_dict()[p]) >= D[p] >= X[p])
minimal_subdistribution.add_constraint(X[p] * len(self._P.root_to_elements_dict()[p]) >= D[p] >= X[p])

def add_counter_example_constraint(s):
for v in self._Z:
Expand Down Expand Up @@ -2176,7 +2175,7 @@ def _preprocess_intertwining_relations(self):
P = self._P
images = defaultdict(set) # A^k -> A, a_1,...,a_k +-> {pi(a_1,...,a_k) for all pi}
for pi_rho in self._pi_rho:
for a_tuple in itertools.product(*([A]*pi_rho.numargs)):
for a_tuple in itertools.product(*([A] * pi_rho.numargs)):
if pi_rho.domain is not None and not pi_rho.domain(*a_tuple):
continue
a = pi_rho.pi(*a_tuple)
Expand Down Expand Up @@ -2566,9 +2565,9 @@ def show(self, variables=True):
varid_name[i] = default_name
for i, (lb, (indices, values), ub) in enumerate(self.milp.constraints()):
if b.row_name(i):
print(" "+b.row_name(i)+":", end=" ")
print(" " + b.row_name(i) + ":", end=" ")
if lb is not None:
print(str(ZZ(lb))+" <=", end=" ")
print(str(ZZ(lb)) + " <=", end=" ")
first = True
for j, c in sorted(zip(indices, values)):
c = ZZ(c)
Expand All @@ -2582,7 +2581,7 @@ def show(self, variables=True):
+ varid_name[j]), end=" ")
first = False
# Upper bound
print("<= "+str(ZZ(ub)) if ub is not None else "")
print("<= " + str(ZZ(ub)) if ub is not None else "")

if variables:
print("Variables are:")
Expand Down Expand Up @@ -2864,8 +2863,8 @@ def add_distribution_constraints(self):
Z_dict = {z: i for i, z in enumerate(Z)}
zero = self.milp.linear_functions_parent().zero()
for tA, tZ in self._bijectionist._elements_distributions:
tA_sum = [zero]*len(Z_dict)
tZ_sum = [zero]*len(Z_dict)
tA_sum = [zero] * len(Z_dict)
tZ_sum = [zero] * len(Z_dict)
for a in tA:
p = self._bijectionist._P.find(a)
for z in self._bijectionist._possible_block_values[p]:
Expand Down Expand Up @@ -3046,12 +3045,13 @@ def add_homomesic_constraints(self):
tZ = self._bijectionist._possible_block_values

def sum_q(q):
return sum(sum(z*self._x[P.find(a), z] for z in tZ[P.find(a)])
return sum(sum(z * self._x[P.find(a), z] for z in tZ[P.find(a)])
for a in q)
q0 = Q[0]
v0 = sum_q(q0)
for q in Q[1:]:
self.milp.add_constraint(len(q0)*sum_q(q) == len(q)*v0, name=f"h: ({q})~({q0})")
self.milp.add_constraint(len(q0) * sum_q(q) == len(q) * v0,
name=f"h: ({q})~({q0})")


def _invert_dict(d):
Expand Down
12 changes: 6 additions & 6 deletions src/sage/combinat/binary_recurrence_sequences.py
Original file line number Diff line number Diff line change
Expand Up @@ -693,7 +693,7 @@ def pthpowers(self, p, Bound):
#gather congruence data for the sequence mod ell, which will be mod period(ell) = modu
cong1, modu = _find_cong1(p, self, ell)

CongNew = [] #makes a new list from cong that is now mod M = lcm(M1, modu) instead of M1
CongNew = [] # makes a new list from cong that is now mod M = lcm(M1, modu) instead of M1
M = lcm(M1, modu)
for k in range(M // M1):
for i in cong:
Expand All @@ -702,18 +702,18 @@ def pthpowers(self, p, Bound):

M1 = M

killed_something = False #keeps track of when cong1 can rule out a congruence in cong
killed_something = False # keeps track of when cong1 can rule out a congruence in cong

#CRT by hand to gain speed
# CRT by hand to gain speed
for i in list(cong):
if i % modu not in cong1: #congruence in cong is inconsistent with any in cong1
cong.remove(i) #remove that congruence
if i % modu not in cong1: # congruence in cong is inconsistent with any in cong1
cong.remove(i) # remove that congruence
killed_something = True

if M1 == M2:
if not killed_something:
tries += 1
if tries == 2: #try twice to rule out congruences
if tries == 2: # try twice to rule out congruences
cong = list(cong)
qqold = qq
qq = next_prime_power(qq)
Expand Down
2 changes: 1 addition & 1 deletion src/sage/combinat/composition_tableau.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def __init__(self, parent, t):
if not all(isinstance(row, list) for row in t):
raise ValueError("a composition tableau must be a list of lists")

if not [len(r) for r in t] in Compositions():
if any(not r for r in t):
raise ValueError("a composition tableau must be a list of non-empty lists")

# Verify rows weakly decrease from left to right
Expand Down
2 changes: 1 addition & 1 deletion src/sage/combinat/crystals/crystals.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ def _rec(self, x, state):
for j in self._index_set:
if j == i:
break
if not y.e(j) is None:
if y.e(j) is not None:
hasParent = True
break
if hasParent:
Expand Down
1 change: 0 additions & 1 deletion src/sage/combinat/designs/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -2504,7 +2504,6 @@ def QDM_57_9_1_1_8():
(3 ,6 ) : ((0,1,3,7), _ref_Handbook),
(3 ,26) : ((0,1,3,8), _ref_Handbook),
(3 ,32) : ((0,1,3,9), _ref_Handbook),
(3 ,6 ) : ((0,1,3,7), _ref_Handbook),
(3 ,14) : ((0,1,4,13), _ref_Handbook),
(3 ,24) : ((0,1,3,15), _ref_Handbook),
(3 ,34) : ((0,1,3,7), _ref_Handbook),
Expand Down
4 changes: 2 additions & 2 deletions src/sage/combinat/matrices/hadamard_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -994,12 +994,12 @@ def hadamard_matrix_from_sds(n, existence=False, check=True):
sage: hadamard_matrix_from_sds(14)
Traceback (most recent call last):
...
ValueError: n must be a positive multiple of four.
ValueError: n must be a positive multiple of four
"""
from sage.combinat.designs.difference_family import supplementary_difference_set_hadamard

if n <= 0 or n % 4 != 0:
raise ValueError(f'n must be a positive multiple of four.')
raise ValueError('n must be a positive multiple of four')
t = n // 4

if existence:
Expand Down
5 changes: 3 additions & 2 deletions src/sage/combinat/partition.py
Original file line number Diff line number Diff line change
Expand Up @@ -4201,8 +4201,9 @@ def zero_one_sequence(self):
sage: all(Partitions().from_zero_one(mu.zero_one_sequence()) == mu for n in range(10) for mu in Partitions(n))
True
"""
tmp = [self[i]-i for i in range(len(self))]
return ([Integer(not (i in tmp)) for i in range(-len(self)+1,self.get_part(0)+1)])
tmp = set(self[i] - i for i in range(len(self)))
return [Integer(i not in tmp)
for i in range(-len(self) + 1, self.get_part(0) + 1)]

def core(self, length):
r"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,14 +313,14 @@ def _test_demazure_operators(self, **options):
alphacheck = L.simple_coroots()
s = L.simple_reflections()
for i in self.cartan_type().index_set():
emalphai = self.monomial(-alpha[i]) # X^{-\alpha_i}
emalphai = self.monomial(-alpha[i]) # X^{-\alpha_i}
for weight in L.some_elements():
if not weight.scalar(alphacheck[i]) in ZZ:
if weight.scalar(alphacheck[i]) not in ZZ:
# Demazure operators are not defined in this case
continue
x = self.monomial(weight)
result = pi[i](x)
tester.assertEqual(result * (self.one()-emalphai),
tester.assertEqual(result * (self.one() - emalphai),
x - emalphai * x.map_support(s[i]))
except ImportError:
pass
Expand Down
4 changes: 2 additions & 2 deletions src/sage/combinat/skew_partition.py
Original file line number Diff line number Diff line change
Expand Up @@ -1005,11 +1005,11 @@ def frobenius_rank(self):
True
"""
N = len(self[0])
mu_betas = [x - j for (j, x) in enumerate(self[1])]
mu_betas = [x - j for j, x in enumerate(self[1])]
mu_betas.extend([- j for j in range(len(self[1]), N)])
res = 0
for i, x in enumerate(self[0]):
if not x - i in mu_betas:
if (x - i) not in mu_betas:
res += 1
return res

Expand Down
2 changes: 1 addition & 1 deletion src/sage/combinat/words/abstract_word.py
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,7 @@ def _to_integer_iterator(self, use_parent_alphabet=False):
"""
from sage.combinat.words.words import FiniteWords, InfiniteWords
if use_parent_alphabet and\
isinstance(self.parent(), (FiniteWords, InfiniteWords)):
isinstance(self.parent(), (FiniteWords, InfiniteWords)):
A = self.parent().alphabet()
for letter in self:
yield A.rank(letter)
Expand Down

0 comments on commit 384493c

Please sign in to comment.