@@ -45,14 +45,14 @@ def annotate(garden: list[str]) -> list[str]:
4545 _validate (garden )
4646 new_garden : list [str ] = []
4747 for i_row , row in enumerate (garden ):
48- new_row : str = ""
48+ new_row : list [ str ] = []
4949 for i_col , char in enumerate (row ):
5050 flower_count = _calc_surrounding_flowers (i_row , i_col , garden )
5151 if flower_count != 0 :
52- new_row += str (flower_count )
52+ new_row . append ( str (flower_count ) )
5353 else :
54- new_row += char
55- new_garden .append (new_row )
54+ new_row . append ( char )
55+ new_garden .append ("" . join ( new_row ) )
5656 return new_garden
5757
5858
@@ -74,11 +74,14 @@ def _calc_surrounding_flowers(i_row: int, i_col: int, garden: list[str]) -> int:
7474 if garden [i_row ][i_col ] == " " :
7575 # Count flowers all around current position
7676 for row , col in COORDINATES :
77- # Avoid IndexError
78- if 0 <= i_row + row < len (garden ) and 0 <= i_col + col < len (garden [0 ]):
79- # Detect and count flower
80- if garden [i_row + row ][i_col + col ] == "*" :
81- total += 1
77+ sum_row = sum ((i_row , row ))
78+ sum_col = sum ((i_col , col ))
79+ if (
80+ 0 <= sum_row < len (garden ) # ROW: Avoid IndexError
81+ and 0 <= sum_col < len (garden [0 ]) # COL: Avoid IndexError
82+ and garden [sum_row ][sum_col ] == "*" # Detect/count flower
83+ ):
84+ total += 1
8285 return total
8386
8487
@@ -87,15 +90,17 @@ def _validate(garden: list[str]) -> None:
8790 Validate the garden shape and contents.
8891
8992 Ensures the input is rectangular and contains only spaces and ``*``.
93+ Raise ValueError when the board receives malformed input garden is not
94+ a rectangle due to inconsistent row length or contains invalid chars
95+ inside the row.
9096
9197 :param list garden: A list of equal-length strings to validate.
9298 :raises ValueError: If rows have differing lengths or contain characters
9399 other than space or ``*``.
94100 """
95101 garden_length = len (garden [0 ])
96- for row in garden :
97- # when the board receives malformed input
98- # garden is not a rectangle due to inconsistent row length
99- # or contains invalid chars inside the row
100- if len (row ) != garden_length or not all (char in " *" for char in row ):
101- raise ValueError ("The board is invalid with current input." )
102+ if any (
103+ (len (row ) != garden_length or not all (char in " *" for char in row ))
104+ for row in garden
105+ ):
106+ raise ValueError ("The board is invalid with current input." )
0 commit comments