[Tutor] function return values

dn PyTutor at DancesWithMice.info
Wed Dec 1 22:34:52 EST 2021


On 02/12/2021 13.24, Phil wrote:
> I was quite pleased with myself that I had reduced the complexity of a
> function until I tried to reuse the same code elsewhere. I had the
> return values set to some dummy values and that was good in this case.
> However, this idea failed when I tried to test if the pairs are in the
> same column. So, what is the correct way to handle a case where there
> isn't a valid pair, row or list value to return?
> 
>     def boxPairsInSameRow(self, pairs, x, y):
>         col_list = []
> 
>         for item, count in pairs.items():
>             if count == 2:  # then item is a pair candidate
>                 for row in range(x, x + 3):
>                     col_list = []
>                     for col in range(y, y + 3):
>                         if item in self.solution[row][col]:
>                             col_list.append(col)
>                     return item, row, col_list
>         return None, None, None # item, row and col_list were originally
> dummy values
> 
> This is the calling function:
> 
>             item, row, column_list =
> self.boxPairsInSameRow(candidate_pairs, x , y)
>             if item is not None and row is not None and column_list is
> not None:
>                 do this only if the returned values are valid. In other
> words, this is a pair in a row.
> 
> Maybe the boxPairsInSameRow function is still too complex? The aim is to
> feed in the pairs, from a counter dictionary, and the row and column
> starting coordinates and have it return the pairs.item, the row that the
> item is on and a list containing the two columns for that row position.
> Once the pairs have been found on a row then there is no need to search
> the remaining row or rows.
> 
> It all sounds simple, however, evidently it's not simple enough.


Suggest creating another function which returns a boolean. Then use that
to initiate (or not) the scan. Perhaps along these lines:

if is_pair_in_row( item, row, column_list ):
    ( item,
      row,
      column_list,
      ) = self.boxPairsInSameRow(candidate_pairs, x , y)


which requires:

def is_pair_in_row( item, row, column_list ):
    """Docstring."""
    return item and row and column_list

NB am not guaranteeing that I have understood which
argument/parameter/identifier goes where!

NBB asking "if xyz" is the same as "if xyz is not None" - a concept
known as "truthiness" (falsiness)

NBBB Python's PEP-008 (a guide (maybe) and not a "standard") for naming
identifiers and functions:

box_pairs_in_same_row()


-- 
Regards,
=dn


More information about the Tutor mailing list