From 785d59de80f6d7bc1b6138c41ed93e7731e9e5a7 Mon Sep 17 00:00:00 2001 From: Egor Kostan Date: Tue, 28 Oct 2025 14:44:55 -0700 Subject: [PATCH 1/4] Flower Field --- flower-field/.exercism/config.json | 22 +++ flower-field/.exercism/metadata.json | 1 + flower-field/HELP.md | 130 ++++++++++++++++++ flower-field/README.md | 64 +++++++++ flower-field/flower_field.py | 192 +++++++++++++++++++++++++++ flower-field/flower_field_test.py | 88 ++++++++++++ 6 files changed, 497 insertions(+) create mode 100644 flower-field/.exercism/config.json create mode 100644 flower-field/.exercism/metadata.json create mode 100644 flower-field/HELP.md create mode 100644 flower-field/README.md create mode 100644 flower-field/flower_field.py create mode 100644 flower-field/flower_field_test.py diff --git a/flower-field/.exercism/config.json b/flower-field/.exercism/config.json new file mode 100644 index 0000000..ef72b03 --- /dev/null +++ b/flower-field/.exercism/config.json @@ -0,0 +1,22 @@ +{ + "authors": [ + "habere-et-dispertire", + "bethanyg" + ], + "contributors": [ + "isaacg", + "kotp" + ], + "files": { + "solution": [ + "flower_field.py" + ], + "test": [ + "flower_field_test.py" + ], + "example": [ + ".meta/example.py" + ] + }, + "blurb": "Mark all the flowers in a garden." +} diff --git a/flower-field/.exercism/metadata.json b/flower-field/.exercism/metadata.json new file mode 100644 index 0000000..f833e06 --- /dev/null +++ b/flower-field/.exercism/metadata.json @@ -0,0 +1 @@ +{"track":"python","exercise":"flower-field","id":"70ccf9a1a13f46b3818b7e37142c6616","url":"https://exercism.org/tracks/python/exercises/flower-field","handle":"myFirstCode","is_requester":true,"auto_approve":false} \ No newline at end of file diff --git a/flower-field/HELP.md b/flower-field/HELP.md new file mode 100644 index 0000000..45b39b9 --- /dev/null +++ b/flower-field/HELP.md @@ -0,0 +1,130 @@ +# Help + +## Running the tests + +We use [pytest][pytest: Getting Started Guide] as our website test runner. +You will need to install `pytest` on your development machine if you want to run tests for the Python track locally. +You should also install the following `pytest` plugins: + +- [pytest-cache][pytest-cache] +- [pytest-subtests][pytest-subtests] + +Extended information can be found in our website [Python testing guide][Python track tests page]. + + +### Running Tests + +To run the included tests, navigate to the folder where the exercise is stored using `cd` in your terminal (_replace `{exercise-folder-location}` below with your path_). +Test files usually end in `_test.py`, and are the same tests that run on the website when a solution is uploaded. + +Linux/MacOS +```bash +$ cd {path/to/exercise-folder-location} +``` + +Windows +```powershell +PS C:\Users\foobar> cd {path\to\exercise-folder-location} +``` + +
+ +Next, run the `pytest` command in your terminal, replacing `{exercise_test.py}` with the name of the test file: + +Linux/MacOS +```bash +$ python3 -m pytest -o markers=task {exercise_test.py} +==================== 7 passed in 0.08s ==================== +``` + +Windows +```powershell +PS C:\Users\foobar> py -m pytest -o markers=task {exercise_test.py} +==================== 7 passed in 0.08s ==================== +``` + + +### Common options +- `-o` : override default `pytest.ini` (_you can use this to avoid marker warnings_) +- `-v` : enable verbose output. +- `-x` : stop running tests on first failure. +- `--ff` : run failures from previous test before running other test cases. + +For additional options, use `python3 -m pytest -h` or `py -m pytest -h`. + + +### Fixing warnings + +If you do not use `pytest -o markers=task` when invoking `pytest`, you might receive a `PytestUnknownMarkWarning` for tests that use our new syntax: + +```bash +PytestUnknownMarkWarning: Unknown pytest.mark.task - is this a typo? You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/mark.html +``` + +To avoid typing `pytest -o markers=task` for every test you run, you can use a `pytest.ini` configuration file. +We have made one that can be downloaded from the top level of the Python track directory: [pytest.ini][pytest.ini]. + +You can also create your own `pytest.ini` file with the following content: + +```ini +[pytest] +markers = + task: A concept exercise task. +``` + +Placing the `pytest.ini` file in the _root_ or _working_ directory for your Python track exercises will register the marks and stop the warnings. +More information on pytest marks can be found in the `pytest` documentation on [marking test functions][pytest: marking test functions with attributes] and the `pytest` documentation on [working with custom markers][pytest: working with custom markers]. + +Information on customizing pytest configurations can be found in the `pytest` documentation on [configuration file formats][pytest: configuration file formats]. + + +### Extending your IDE or Code Editor + +Many IDEs and code editors have built-in support for using `pytest` and other code quality tools. +Some community-sourced options can be found on our [Python track tools page][Python track tools page]. + +[Pytest: Getting Started Guide]: https://docs.pytest.org/en/latest/getting-started.html +[Python track tools page]: https://exercism.org/docs/tracks/python/tools +[Python track tests page]: https://exercism.org/docs/tracks/python/tests +[pytest-cache]:http://pythonhosted.org/pytest-cache/ +[pytest-subtests]:https://github.com/pytest-dev/pytest-subtests +[pytest.ini]: https://github.com/exercism/python/blob/main/pytest.ini +[pytest: configuration file formats]: https://docs.pytest.org/en/6.2.x/customize.html#configuration-file-formats +[pytest: marking test functions with attributes]: https://docs.pytest.org/en/6.2.x/mark.html#raising-errors-on-unknown-marks +[pytest: working with custom markers]: https://docs.pytest.org/en/6.2.x/example/markers.html#working-with-custom-markers + +## Submitting your solution + +You can submit your solution using the `exercism submit flower_field.py` command. +This command will upload your solution to the Exercism website and print the solution page's URL. + +It's possible to submit an incomplete solution which allows you to: + +- See how others have completed the exercise +- Request help from a mentor + +## Need to get help? + +If you'd like help solving the exercise, check the following pages: + +- The [Python track's documentation](https://exercism.org/docs/tracks/python) +- The [Python track's programming category on the forum](https://forum.exercism.org/c/programming/python) +- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5) +- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs) + +Should those resources not suffice, you could submit your (incomplete) solution to request mentoring. + +Below are some resources for getting help if you run into trouble: + +- [The PSF](https://www.python.org) hosts Python downloads, documentation, and community resources. +- [The Exercism Community on Discord](https://exercism.org/r/discord) +- [Python Community on Discord](https://pythondiscord.com/) is a very helpful and active community. +- [/r/learnpython/](https://www.reddit.com/r/learnpython/) is a subreddit designed for Python learners. +- [#python on Libera.chat](https://www.python.org/community/irc/) this is where the core developers for the language hang out and get work done. +- [Python Community Forums](https://discuss.python.org/) +- [Free Code Camp Community Forums](https://forum.freecodecamp.org/) +- [CodeNewbie Community Help Tag](https://community.codenewbie.org/t/help) +- [Pythontutor](http://pythontutor.com/) for stepping through small code snippets visually. + +Additionally, [StackOverflow](http://stackoverflow.com/questions/tagged/python) is a good spot to search for your problem/question to see if it has been answered already. + If not - you can always [ask](https://stackoverflow.com/help/how-to-ask) or [answer](https://stackoverflow.com/help/how-to-answer) someone else's question. \ No newline at end of file diff --git a/flower-field/README.md b/flower-field/README.md new file mode 100644 index 0000000..80c4f44 --- /dev/null +++ b/flower-field/README.md @@ -0,0 +1,64 @@ +# Flower Field + +Welcome to Flower Field on Exercism's Python Track. +If you need help running the tests or submitting your code, check out `HELP.md`. + +## Introduction + +[Flower Field][history] is a compassionate reimagining of the popular game Minesweeper. +The object of the game is to find all the flowers in the garden using numeric hints that indicate how many flowers are directly adjacent (horizontally, vertically, diagonally) to a square. +"Flower Field" shipped in regional versions of Microsoft Windows in Italy, Germany, South Korea, Japan and Taiwan. + +[history]: https://web.archive.org/web/20020409051321fw_/http://rcm.usr.dsi.unimi.it/rcmweb/fnm/ + +## Instructions + +Your task is to add flower counts to empty squares in a completed Flower Field garden. +The garden itself is a rectangle board composed of squares that are either empty (`' '`) or a flower (`'*'`). + +For each empty square, count the number of flowers adjacent to it (horizontally, vertically, diagonally). +If the empty square has no adjacent flowers, leave it empty. +Otherwise replace it with the count of adjacent flowers. + +For example, you may receive a 5 x 4 board like this (empty spaces are represented here with the '·' character for display on screen): + +```text +·*·*· +··*·· +··*·· +····· +``` + +Which your code should transform into this: + +```text +1*3*1 +13*31 +·2*2· +·111· +``` + +## Exception messages + +Sometimes it is necessary to [raise an exception](https://docs.python.org/3/tutorial/errors.html#raising-exceptions). When you do this, you should always include a **meaningful error message** to indicate what the source of the error is. This makes your code more readable and helps significantly with debugging. For situations where you know that the error source will be a certain type, you can choose to raise one of the [built in error types](https://docs.python.org/3/library/exceptions.html#base-classes), but should still include a meaningful message. + +This particular exercise requires that you use the [raise statement](https://docs.python.org/3/reference/simple_stmts.html#the-raise-statement) to "throw" a `ValueError` when the `board()` function receives malformed input. The tests will only pass if you both `raise` the `exception` and include a message with it. + +To raise a `ValueError` with a message, write the message as an argument to the `exception` type: + +```python +# when the board receives malformed input +raise ValueError("The board is invalid with current input.") +``` + +## Source + +### Created by + +- @habere-et-dispertire +- @bethanyg + +### Contributed to by + +- @isaacg +- @kotp \ No newline at end of file diff --git a/flower-field/flower_field.py b/flower-field/flower_field.py new file mode 100644 index 0000000..36a7e65 --- /dev/null +++ b/flower-field/flower_field.py @@ -0,0 +1,192 @@ +""" +Flower Field is a compassionate reimagining of the popular game Minesweeper. + +This module provides helpers to validate and annotate a rectangular garden +representation, where each row is a string comprised of spaces and ``*`` +characters. A ``*`` denotes a flower; a space denotes an empty square. + +The goal is to compute numeric hints indicating how many flowers are +directly adjacent (horizontally, vertically, diagonally) to each square. +""" + + +def annotate(garden: list) -> list: + """ + Annotate a garden with counts of adjacent flowers. + + Expects a rectangular list of strings containing only spaces and ``*``. + Validation errors raise a :class:`ValueError`. + + :param list garden: A list of equal-length strings representing the garden. + ``*`` marks a flower; space marks empty. + :returns: An annotated garden of the same shape. Empty squares are + replaced by digits (``"1"``–``"8"``) when adjacent to flowers; + squares with zero adjacent flowers remain spaces. Flowers + (``*``) are preserved. + :rtype: list + :raises ValueError: If the garden is non-rectangular or contains + invalid characters. + """ + # empty list + if not garden: + return [] + + # when the board receives malformed input + if not _is_garden_valid(garden): + raise ValueError("The board is invalid with current input.") + + for i_row, row in enumerate(garden): + for i_col, char in enumerate(row): + if char == " ": + flower_count: int = 0 + flower_count += _calc_flower_top(i_row, i_col, garden) + flower_count += _calc_flower_bottom(i_row, i_col, garden) + flower_count += _clac_flower_left(i_row, i_col, garden) + flower_count += _clac_flower_right(i_row, i_col, garden) + + if flower_count != 0: + garden[i_row] = ( + garden[i_row][:i_col] + + str(flower_count) + + garden[i_row][i_col + 1 :] + ) + return garden + + +def _clac_flower_left(i_row: int, i_col: int, garden: list) -> int: + """ + Count contiguous flowers to the left of the current position. + + Scans leftward from ``(i_row, i_col - 1)`` until a non-flower character is + found or the row boundary is reached. + + :param int i_row: Current row index. + :param int i_col: Current column index. + :param list garden: The garden as a list of strings. + :returns: Number of adjacent ``*`` cells to the left. + :rtype: int + """ + flower_count: int = 0 + + if i_col - 1 >= 0: + for char in garden[i_row][:i_col][::-1]: + if char == "*": + flower_count += 1 + else: + break + return flower_count + + +def _clac_flower_right(i_row: int, i_col: int, garden: list) -> int: + """ + Count contiguous flowers to the right of the current position. + + Scans rightward from ``(i_row, i_col + 1)`` until a non-flower character is + found or the row boundary is reached. + + :param int i_row: Current row index. + :param int i_col: Current column index. + :param list garden: The garden as a list of strings. + :returns: Number of adjacent ``*`` cells to the right. + :rtype: int + """ + flower_count: int = 0 + + if i_col + 1 < len(garden[i_row]): + for char in garden[i_row][i_col + 1 :]: + if char == "*": + flower_count += 1 + else: + break + return flower_count + + +def _calc_flower_top(i_row: int, i_col: int, garden: list) -> int: + """ + Count flowers in the three cells directly above the current position. + + Checks the top-left, top, and top-right neighbors when the row above + exists and contains any flowers. + + :param int i_row: Current row index. + :param int i_col: Current column index. + :param list garden: The garden as a list of strings. + :returns: Number of ``*`` cells among the three upper neighbors. + :rtype: int + """ + + flower_count: int = 0 + + if i_row - 1 >= 0 and "*" in garden[i_row - 1]: + # top-left + if i_col > 0 and garden[i_row - 1][i_col - 1] == "*": + flower_count += 1 + # top + if garden[i_row - 1][i_col] == "*": + flower_count += 1 + # top-right + if ( + i_col + 1 < len(garden[i_row]) + and garden[i_row - 1][i_col + 1] == "*" + ): + flower_count += 1 + return flower_count + + +def _calc_flower_bottom(i_row: int, i_col: int, garden: list) -> int: + """ + Count flowers in the three cells directly below the current position. + + Checks the bottom-left, bottom, and bottom-right neighbors when the row + below exists and contains any flowers. + + :param int i_row: Current row index. + :param int i_col: Current column index. + :param list garden: The garden as a list of strings. + :returns: Number of ``*`` cells among the three lower neighbors. + :rtype: int + """ + + flower_count: int = 0 + + if i_row + 1 < len(garden) and "*" in garden[i_row + 1]: + # bottom-left + if i_col > 0 and garden[i_row + 1][i_col - 1] == "*": + flower_count += 1 + # bottom + if garden[i_row + 1][i_col] == "*": + flower_count += 1 + # bottom-right + if ( + i_col + 1 < len(garden[i_row]) + and garden[i_row + 1][i_col + 1] == "*" + ): + flower_count += 1 + return flower_count + + +def _is_garden_valid(garden: list) -> bool: + """ + Check whether the garden input is a valid rectangular board. + + A garden is considered valid when all rows have the same length and only + contain spaces or ``*`` characters. + + :param list garden: Candidate garden as a list of strings. + :returns: ``True`` if the input is rectangular and uses only valid + characters; otherwise ``False``. + :rtype: bool + """ + + garden_length: int = len(garden[0]) + # when the board receives malformed input + for row in garden: + # garden is not a rectangle due to inconsistent row length + if len(row) != garden_length: + print("return false") + return False + # contains invalid chars inside row + valid_chars: bool = all(char in " *" for char in row) + if not valid_chars: + return False + return True diff --git a/flower-field/flower_field_test.py b/flower-field/flower_field_test.py new file mode 100644 index 0000000..0676cec --- /dev/null +++ b/flower-field/flower_field_test.py @@ -0,0 +1,88 @@ +# pylint: disable=C0301, C0114, C0115, C0116, R0904 +# These tests are auto-generated with test data from: +# https://github.com/exercism/problem-specifications/tree/main/exercises/flower-field/canonical-data.json +# File last updated on 2025-06-25 + +import unittest + +from flower_field import ( + annotate, +) + + +class FlowerFieldTest(unittest.TestCase): + def test_no_rows(self): + self.assertEqual(annotate([]), []) + + def test_no_columns(self): + self.assertEqual(annotate([""]), [""]) + + def test_no_flowers(self): + self.assertEqual(annotate([" ", " ", " "]), [" ", " ", " "]) + + def test_garden_full_of_flowers(self): + self.assertEqual(annotate(["***", "***", "***"]), ["***", "***", "***"]) + + def test_flower_surrounded_by_spaces(self): + self.assertEqual(annotate([" ", " * ", " "]), ["111", "1*1", "111"]) + + def test_space_surrounded_by_flowers(self): + self.assertEqual(annotate(["***", "* *", "***"]), ["***", "*8*", "***"]) + + def test_horizontal_line(self): + self.assertEqual(annotate([" * * "]), ["1*2*1"]) + + def test_horizontal_line_flowers_at_edges(self): + self.assertEqual(annotate(["* *"]), ["*1 1*"]) + + def test_vertical_line(self): + self.assertEqual(annotate([" ", "*", " ", "*", " "]), ["1", "*", "2", "*", "1"]) + + def test_vertical_line_flowers_at_edges(self): + self.assertEqual(annotate(["*", " ", " ", " ", "*"]), ["*", "1", " ", "1", "*"]) + + def test_cross(self): + self.assertEqual( + annotate([" * ", " * ", "*****", " * ", " * "]), + [" 2*2 ", "25*52", "*****", "25*52", " 2*2 "], + ) + + def test_large_garden(self): + self.assertEqual( + annotate([" * * ", + " * ", + " * ", + " * *", + " * * ", + " "]), + [ + "1*22*1", + "12*322", + " 123*2", + "112*4*", + "1*22*2", + "111111"], + ) + + # Additional tests for this track + def test_annotate_9(self): + self.assertEqual( + annotate([" ", " * ", " ", " ", " * "]), + [" 111", " 1*1", " 111", "111 ", "1*1 "], + ) + + def test_different_len(self): + with self.assertRaises(ValueError) as err: + annotate([" ", "* ", " "]) + self.assertEqual(type(err.exception), ValueError) + self.assertEqual( + err.exception.args[0], "The board is invalid with current input." + ) + + def test_invalid_char(self): + with self.assertRaises(ValueError) as err: + annotate(["X * "]) + self.assertEqual(type(err.exception), ValueError) + self.assertEqual( + err.exception.args[0], "The board is invalid with current input." + ) From b01d4e2f0c62ea4c2cab56a7e8e2c9c07a1296aa Mon Sep 17 00:00:00 2001 From: Egor Kostan Date: Tue, 28 Oct 2025 14:53:53 -0700 Subject: [PATCH 2/4] Update flower_field.py --- flower-field/flower_field.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/flower-field/flower_field.py b/flower-field/flower_field.py index 36a7e65..85873a8 100644 --- a/flower-field/flower_field.py +++ b/flower-field/flower_field.py @@ -53,7 +53,7 @@ def annotate(garden: list) -> list: return garden -def _clac_flower_left(i_row: int, i_col: int, garden: list) -> int: +def _calc_flower_left(i_row: int, i_col: int, garden: list) -> int: """ Count contiguous flowers to the left of the current position. @@ -77,7 +77,7 @@ def _clac_flower_left(i_row: int, i_col: int, garden: list) -> int: return flower_count -def _clac_flower_right(i_row: int, i_col: int, garden: list) -> int: +def _calc_flower_right(i_row: int, i_col: int, garden: list) -> int: """ Count contiguous flowers to the right of the current position. @@ -183,7 +183,6 @@ def _is_garden_valid(garden: list) -> bool: for row in garden: # garden is not a rectangle due to inconsistent row length if len(row) != garden_length: - print("return false") return False # contains invalid chars inside row valid_chars: bool = all(char in " *" for char in row) From fe6b4fd6d2b31ef83b5342d3f5ba814ab950cb5a Mon Sep 17 00:00:00 2001 From: Egor Kostan Date: Tue, 28 Oct 2025 14:55:02 -0700 Subject: [PATCH 3/4] Update flower_field.py --- flower-field/flower_field.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/flower-field/flower_field.py b/flower-field/flower_field.py index 85873a8..7823170 100644 --- a/flower-field/flower_field.py +++ b/flower-field/flower_field.py @@ -41,14 +41,14 @@ def annotate(garden: list) -> list: flower_count: int = 0 flower_count += _calc_flower_top(i_row, i_col, garden) flower_count += _calc_flower_bottom(i_row, i_col, garden) - flower_count += _clac_flower_left(i_row, i_col, garden) - flower_count += _clac_flower_right(i_row, i_col, garden) + flower_count += _calc_flower_left(i_row, i_col, garden) + flower_count += _calc_flower_right(i_row, i_col, garden) if flower_count != 0: garden[i_row] = ( garden[i_row][:i_col] + str(flower_count) - + garden[i_row][i_col + 1 :] + + garden[i_row][i_col + 1:] ) return garden @@ -93,7 +93,7 @@ def _calc_flower_right(i_row: int, i_col: int, garden: list) -> int: flower_count: int = 0 if i_col + 1 < len(garden[i_row]): - for char in garden[i_row][i_col + 1 :]: + for char in garden[i_row][i_col + 1:]: if char == "*": flower_count += 1 else: From fed3f7c05e9826bbc0bc255f28d2f4f9f863e965 Mon Sep 17 00:00:00 2001 From: Egor Kostan Date: Tue, 28 Oct 2025 14:56:04 -0700 Subject: [PATCH 4/4] Update flower_field.py --- flower-field/flower_field.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/flower-field/flower_field.py b/flower-field/flower_field.py index 7823170..da6e1c0 100644 --- a/flower-field/flower_field.py +++ b/flower-field/flower_field.py @@ -48,7 +48,7 @@ def annotate(garden: list) -> list: garden[i_row] = ( garden[i_row][:i_col] + str(flower_count) - + garden[i_row][i_col + 1:] + + garden[i_row][i_col + 1 :] ) return garden @@ -93,7 +93,7 @@ def _calc_flower_right(i_row: int, i_col: int, garden: list) -> int: flower_count: int = 0 if i_col + 1 < len(garden[i_row]): - for char in garden[i_row][i_col + 1:]: + for char in garden[i_row][i_col + 1 :]: if char == "*": flower_count += 1 else: