Skip to content

Commit 4f321a7

Browse files
authored
Merge pull request #274 from ikostan/exercism-sync/3e68c20eeff896f4
Exercism sync/3e68c20eeff896f4
2 parents d5b1abd + 3c43dc1 commit 4f321a7

8 files changed

Lines changed: 451 additions & 33 deletions

File tree

flower-field/flower_field.py

Lines changed: 22 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,16 @@
1010
"""
1111

1212
# Relative offsets to the eight neighboring cells around a given position
13-
COORDINATES: tuple[tuple[int, int]] = (
13+
COORDINATES: tuple[
14+
tuple[int, int],
15+
tuple[int, int],
16+
tuple[int, int],
17+
tuple[int, int],
18+
tuple[int, int],
19+
tuple[int, int],
20+
tuple[int, int],
21+
tuple[int, int],
22+
] = (
1423
(-1, -1),
1524
(-1, 0),
1625
(-1, 1),
@@ -71,38 +80,18 @@ def _calc_surrounding_flowers(i_row: int, i_col: int, garden: list[str]) -> int:
7180
"""
7281
if garden[i_row][i_col] != " ":
7382
return 0
74-
return sum(
75-
_process_cell(i_row, offset_row, i_col, offset_col, garden)
76-
for offset_row, offset_col in COORDINATES
77-
)
78-
79-
80-
def _process_cell(i_row, offset_row, i_col, offset_col, garden) -> int:
81-
"""
82-
Return 1 if the neighbor at the given relative offset contains a flower.
83-
84-
Computes the absolute coordinates from ``(i_row, i_col)`` and the provided
85-
offsets, performs bounds checking to avoid ``IndexError``, and returns ``1``
86-
only when the cell is within the garden and equals ``"*"``.
87-
88-
:param int i_row: Row index of the reference cell.
89-
:param int offset_row: Row delta to apply to ``i_row``.
90-
:param int i_col: Column index of the reference cell.
91-
:param int offset_col: Column delta to apply to ``i_col``.
92-
:param list garden: The rectangular garden representation.
93-
:returns: ``1`` when the computed neighbor cell contains a flower, otherwise ``0``.
94-
:rtype: int
95-
"""
96-
row: int = i_row + offset_row
97-
col: int = i_col + offset_col
98-
99-
if (
100-
0 <= row < len(garden) # ROW: Avoid IndexError
101-
and 0 <= col < len(garden[0]) # COL: Avoid IndexError
102-
and garden[row][col] == "*" # Detect/count flower
103-
):
104-
return 1
105-
return 0
83+
total: int = 0
84+
# Count flowers all around current position
85+
for offset_row, offset_col in COORDINATES:
86+
sum_row = i_row + offset_row
87+
sum_col = i_col + offset_col
88+
if (
89+
0 <= sum_row < len(garden) # ROW: Avoid IndexError
90+
and 0 <= sum_col < len(garden[0]) # COL: Avoid IndexError
91+
and garden[sum_row][sum_col] == "*" # Detect/count flower
92+
):
93+
total += 1
94+
return total
10695

10796

10897
def _validate(garden: list[str]) -> None:
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
{
2+
"authors": [
3+
"meatball133",
4+
"bethanyg"
5+
],
6+
"files": {
7+
"solution": [
8+
"resistor_color_trio.py"
9+
],
10+
"test": [
11+
"resistor_color_trio_test.py"
12+
],
13+
"example": [
14+
".meta/example.py"
15+
]
16+
},
17+
"blurb": "Convert color codes, as used on resistors, to a human-readable label.",
18+
"source": "Maud de Vries, Erik Schierboom",
19+
"source_url": "https://github.com/exercism/problem-specifications/issues/1549"
20+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"track":"python","exercise":"resistor-color-trio","id":"a3ae5a759afb4e5aa99bfe4c281a4bfd","url":"https://exercism.org/tracks/python/exercises/resistor-color-trio","handle":"myFirstCode","is_requester":true,"auto_approve":false}

resistor-color-trio/HELP.md

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
# Help
2+
3+
## Running the tests
4+
5+
We use [pytest][pytest: Getting Started Guide] as our website test runner.
6+
You will need to install `pytest` on your development machine if you want to run tests for the Python track locally.
7+
You should also install the following `pytest` plugins:
8+
9+
- [pytest-cache][pytest-cache]
10+
- [pytest-subtests][pytest-subtests]
11+
12+
Extended information can be found in our website [Python testing guide][Python track tests page].
13+
14+
15+
### Running Tests
16+
17+
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_).
18+
Test files usually end in `_test.py`, and are the same tests that run on the website when a solution is uploaded.
19+
20+
Linux/MacOS
21+
```bash
22+
$ cd {path/to/exercise-folder-location}
23+
```
24+
25+
Windows
26+
```powershell
27+
PS C:\Users\foobar> cd {path\to\exercise-folder-location}
28+
```
29+
30+
<br>
31+
32+
Next, run the `pytest` command in your terminal, replacing `{exercise_test.py}` with the name of the test file:
33+
34+
Linux/MacOS
35+
```bash
36+
$ python3 -m pytest -o markers=task {exercise_test.py}
37+
==================== 7 passed in 0.08s ====================
38+
```
39+
40+
Windows
41+
```powershell
42+
PS C:\Users\foobar> py -m pytest -o markers=task {exercise_test.py}
43+
==================== 7 passed in 0.08s ====================
44+
```
45+
46+
47+
### Common options
48+
- `-o` : override default `pytest.ini` (_you can use this to avoid marker warnings_)
49+
- `-v` : enable verbose output.
50+
- `-x` : stop running tests on first failure.
51+
- `--ff` : run failures from previous test before running other test cases.
52+
53+
For additional options, use `python3 -m pytest -h` or `py -m pytest -h`.
54+
55+
56+
### Fixing warnings
57+
58+
If you do not use `pytest -o markers=task` when invoking `pytest`, you might receive a `PytestUnknownMarkWarning` for tests that use our new syntax:
59+
60+
```bash
61+
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
62+
```
63+
64+
To avoid typing `pytest -o markers=task` for every test you run, you can use a `pytest.ini` configuration file.
65+
We have made one that can be downloaded from the top level of the Python track directory: [pytest.ini][pytest.ini].
66+
67+
You can also create your own `pytest.ini` file with the following content:
68+
69+
```ini
70+
[pytest]
71+
markers =
72+
task: A concept exercise task.
73+
```
74+
75+
Placing the `pytest.ini` file in the _root_ or _working_ directory for your Python track exercises will register the marks and stop the warnings.
76+
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].
77+
78+
Information on customizing pytest configurations can be found in the `pytest` documentation on [configuration file formats][pytest: configuration file formats].
79+
80+
81+
### Extending your IDE or Code Editor
82+
83+
Many IDEs and code editors have built-in support for using `pytest` and other code quality tools.
84+
Some community-sourced options can be found on our [Python track tools page][Python track tools page].
85+
86+
[Pytest: Getting Started Guide]: https://docs.pytest.org/en/latest/getting-started.html
87+
[Python track tools page]: https://exercism.org/docs/tracks/python/tools
88+
[Python track tests page]: https://exercism.org/docs/tracks/python/tests
89+
[pytest-cache]:http://pythonhosted.org/pytest-cache/
90+
[pytest-subtests]:https://github.com/pytest-dev/pytest-subtests
91+
[pytest.ini]: https://github.com/exercism/python/blob/main/pytest.ini
92+
[pytest: configuration file formats]: https://docs.pytest.org/en/6.2.x/customize.html#configuration-file-formats
93+
[pytest: marking test functions with attributes]: https://docs.pytest.org/en/6.2.x/mark.html#raising-errors-on-unknown-marks
94+
[pytest: working with custom markers]: https://docs.pytest.org/en/6.2.x/example/markers.html#working-with-custom-markers
95+
96+
## Submitting your solution
97+
98+
You can submit your solution using the `exercism submit resistor_color_trio.py` command.
99+
This command will upload your solution to the Exercism website and print the solution page's URL.
100+
101+
It's possible to submit an incomplete solution which allows you to:
102+
103+
- See how others have completed the exercise
104+
- Request help from a mentor
105+
106+
## Need to get help?
107+
108+
If you'd like help solving the exercise, check the following pages:
109+
110+
- The [Python track's documentation](https://exercism.org/docs/tracks/python)
111+
- The [Python track's programming category on the forum](https://forum.exercism.org/c/programming/python)
112+
- [Exercism's programming category on the forum](https://forum.exercism.org/c/programming/5)
113+
- The [Frequently Asked Questions](https://exercism.org/docs/using/faqs)
114+
115+
Should those resources not suffice, you could submit your (incomplete) solution to request mentoring.
116+
117+
Below are some resources for getting help if you run into trouble:
118+
119+
- [The PSF](https://www.python.org) hosts Python downloads, documentation, and community resources.
120+
- [The Exercism Community on Discord](https://exercism.org/r/discord)
121+
- [Python Community on Discord](https://pythondiscord.com/) is a very helpful and active community.
122+
- [/r/learnpython/](https://www.reddit.com/r/learnpython/) is a subreddit designed for Python learners.
123+
- [#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.
124+
- [Python Community Forums](https://discuss.python.org/)
125+
- [Free Code Camp Community Forums](https://forum.freecodecamp.org/)
126+
- [CodeNewbie Community Help Tag](https://community.codenewbie.org/t/help)
127+
- [Pythontutor](http://pythontutor.com/) for stepping through small code snippets visually.
128+
129+
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.
130+
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.

resistor-color-trio/README.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# Resistor Color Trio
2+
3+
Welcome to Resistor Color Trio on Exercism's Python Track.
4+
If you need help running the tests or submitting your code, check out `HELP.md`.
5+
6+
## Instructions
7+
8+
If you want to build something using a Raspberry Pi, you'll probably use _resistors_.
9+
For this exercise, you need to know only three things about them:
10+
11+
- Each resistor has a resistance value.
12+
- Resistors are small - so small in fact that if you printed the resistance value on them, it would be hard to read.
13+
To get around this problem, manufacturers print color-coded bands onto the resistors to denote their resistance values.
14+
- Each band acts as a digit of a number.
15+
For example, if they printed a brown band (value 1) followed by a green band (value 5), it would translate to the number 15.
16+
In this exercise, you are going to create a helpful program so that you don't have to remember the values of the bands.
17+
The program will take 3 colors as input, and outputs the correct value, in ohms.
18+
The color bands are encoded as follows:
19+
20+
- black: 0
21+
- brown: 1
22+
- red: 2
23+
- orange: 3
24+
- yellow: 4
25+
- green: 5
26+
- blue: 6
27+
- violet: 7
28+
- grey: 8
29+
- white: 9
30+
31+
In Resistor Color Duo you decoded the first two colors.
32+
For instance: orange-orange got the main value `33`.
33+
The third color stands for how many zeros need to be added to the main value.
34+
The main value plus the zeros gives us a value in ohms.
35+
For the exercise it doesn't matter what ohms really are.
36+
For example:
37+
38+
- orange-orange-black would be 33 and no zeros, which becomes 33 ohms.
39+
- orange-orange-red would be 33 and 2 zeros, which becomes 3300 ohms.
40+
- orange-orange-orange would be 33 and 3 zeros, which becomes 33000 ohms.
41+
42+
(If Math is your thing, you may want to think of the zeros as exponents of 10.
43+
If Math is not your thing, go with the zeros.
44+
It really is the same thing, just in plain English instead of Math lingo.)
45+
46+
This exercise is about translating the colors into a label:
47+
48+
> "... ohms"
49+
50+
So an input of `"orange", "orange", "black"` should return:
51+
52+
> "33 ohms"
53+
54+
When we get to larger resistors, a [metric prefix][metric-prefix] is used to indicate a larger magnitude of ohms, such as "kiloohms".
55+
That is similar to saying "2 kilometers" instead of "2000 meters", or "2 kilograms" for "2000 grams".
56+
57+
For example, an input of `"orange", "orange", "orange"` should return:
58+
59+
> "33 kiloohms"
60+
61+
[metric-prefix]: https://en.wikipedia.org/wiki/Metric_prefix
62+
63+
## Source
64+
65+
### Created by
66+
67+
- @meatball133
68+
- @bethanyg
69+
70+
### Based on
71+
72+
Maud de Vries, Erik Schierboom - https://github.com/exercism/problem-specifications/issues/1549
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""
2+
Resistor Color Trio.
3+
4+
In Resistor Color Duo you decoded the first two colors.
5+
For instance: orange-orange got the main value 33.
6+
The third color stands for how many zeros need to be added to the main value.
7+
The main value plus the zeros gives us a value in ohms. For the exercise it
8+
doesn't matter what ohms really are.
9+
"""
10+
11+
# Mapping of resistor color names to their corresponding digit values.
12+
COLOR_VALUES: dict[str, int] = {
13+
"black": 0,
14+
"brown": 1,
15+
"red": 2,
16+
"orange": 3,
17+
"yellow": 4,
18+
"green": 5,
19+
"blue": 6,
20+
"violet": 7,
21+
"grey": 8,
22+
"white": 9,
23+
}
24+
25+
26+
def label(colors: list[str]) -> str:
27+
"""
28+
Return a human-readable label for a 3-band resistor value.
29+
30+
The first two colors form the significant digits and the third color
31+
is the multiplier (number of trailing zeros). The resulting value is
32+
scaled to the largest whole unit among ohms, kiloohms, megaohms, or
33+
gigaohms.
34+
35+
:param colors: Three resistor color names in order [band1, band2, multiplier].
36+
band1 and band2 provide the significant digits; multiplier
37+
adds zeros.
38+
:return: Formatted resistance value string using the largest whole unit
39+
(e.g., '47 kiloohms', '680 ohms').
40+
:raises KeyError: If a color name is not recognized.
41+
:raises IndexError: If fewer than three colors are provided.
42+
"""
43+
prefix: str = f"{COLOR_VALUES[colors[0]]}{COLOR_VALUES[colors[1]]}"
44+
postfix: str = f"{'0' * COLOR_VALUES[colors[2]]}"
45+
int_val: int = int(prefix + postfix)
46+
47+
# Scale to the largest whole unit
48+
# (ohms, kiloohms, megaohms, gigaohms) for readability
49+
if 1000 <= int_val < 1000000:
50+
return f"{int_val // 1000} kiloohms"
51+
52+
if 1000000 <= int_val < 1000000000:
53+
return f"{int_val // 1000000} megaohms"
54+
55+
if 1000000000 <= int_val:
56+
return f"{int_val // 1000000000} gigaohms"
57+
58+
return f"{int_val} ohms"

0 commit comments

Comments
 (0)