[Tutor] pylint(too-many-nested-blocks)

Phil phillor9 at gmail.com
Sat Nov 27 22:51:02 EST 2021


"https://pycodequ.al/docs/pylint-messages/r1702-too-many-nested-blocks.html" 
describes this error as:

"Used when a function or method has too many nested blocks. This makes 
the code less understandable and maintainable."

The following is one of several functions that fits this description and 
I'm wondering how I might reduce the number of for-loops. If the number 
of for-loops cannot be reduced then I suppose the function should be 
broken up into smaller functions. The problem is, as I see it, little of 
the code is reusable in other functions that also have too many nested 
blocks.

     def pointingPairRow(self):
         """
         If a candidate is present in only two cells of a box, then it 
must be the
         solution for one of these two cells. If these two cells belong 
to the same row,
         then this candidate can not be the solution in any other cell 
of the same row.
         """
         box_start = [(0, 0), (0, 3), (0, 6),
                     (3, 0), (3, 3), (3, 6),
                     (6, 0), (6, 3), (6, 6)
                     ]

         for x, y in box_start:
             pairs = Counter()

             for number in range(1, 10):
                 number= str(number)

                 for row in range(x, x + 3):
                     for col in range(y, y + 3):
                         if len(self.solution[row][col]) > 1 and number 
in self.solution[row][col]:
                             pairs[number] += 1

             for item, count in pairs.items():
                 if count == 2:  # candidate
                     for row in range(x, x + 3):
                         icount = 0
                         col_list = []

                         for col in range(y, y + 3):
                             if item in self.solution[row][col]:
                                 icount += 1
                                 col_list.append(col)

                             if icount == 2:
                                 for c in range(self.num_cols):
                                     if  len(self.solution[row][c]) > 1 
and item in self.solution[row][c] and c not in col_list:
                                         self.solution[row][c] -= set(item)

Also, the 3 for-loops before "if count == 2" don't need to be repeated 
once the candidate has been removed from the row with 
"self.solution[row][c] -= set(item)". Setting a boolean switch here to 
prevent the for-loops from continuing does the job but it adds yet 
another "if" statement.

The function works and so it's logically correct but it's messy and 
inefficient.

-- 
Regards,
Phil



More information about the Tutor mailing list