primeiro commit com exercicios de Exercism realizados até esta data

This commit is contained in:
2026-10-17 22:10:27 +01:00
commit 58fccbe27a
708 changed files with 35038 additions and 0 deletions
@@ -0,0 +1,19 @@
{
"authors": [
"aldraco",
"BethanyG"
],
"files": {
"solution": [
"strings.py"
],
"test": [
"strings_test.py"
],
"exemplar": [
".meta/exemplar.py"
]
},
"icon": "two-fer",
"blurb": "Learn about strings by helping your little sister with her vocabulary homework."
}
@@ -0,0 +1 @@
{"track":"python","exercise":"little-sisters-vocab","id":"6df0e15de087433caad67729067204a1","url":"https://exercism.org/tracks/python/exercises/little-sisters-vocab","handle":"sanctushck","is_requester":true,"auto_approve":false}
+130
View File
@@ -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}
```
<br>
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 strings.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.
+37
View File
@@ -0,0 +1,37 @@
# Hints
## General
- The Python Docs [Tutorial for strings][python-str-doc] has an overview of the Python `str` type.
- String methods [`str.join()`][str-join] and [`str.split()`][str-split] ar very helpful when processing strings.
- The Python Docs on [Sequence Types][common sequence operations] has a rundown of operations common to all sequences, including `strings`, `lists`, `tuples`, and `ranges`.
There's four activities in the assignment, each with a set of text or words to work with.
## 1. Add a prefix to a word
- Small strings can be concatenated with the `+` operator.
## 2. Add prefixes to word groups
- Believe it or not, [`str.join()`][str-join] is all you need here.
- Like [`str.split()`][str-split]`, `str.join()` can take an arbitrary-length string, made up of any unicode code points.
## 3. Remove a suffix from a word
- Strings can be indexed or sliced from either the left (starting at 0) or the right (starting at -1).
- If you want the last code point of an arbitrary-length string, you can use [-1].
- The last three letters in a string can be "sliced off" using a negative index. e.g. 'beautiful'[:-3] == 'beauti'
## 4. Extract and transform a word
- Using [`str.split()`][str-split] returns a `list` of strings broken on white space.
- `lists` are sequences, and can be indexed.
- [`str.split()`][str-split] can be directly indexed: `'Exercism rocks!'.split()[0] == 'Exercism'`
- Be careful of punctuation! Periods can be removed via slice: `'dark.'[:-1] == 'dark'`
[common sequence operations]: https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str
[python-str-doc]: https://docs.python.org/3/tutorial/introduction.html#strings
[str-join]: https://docs.python.org/3/library/stdtypes.html#str.join
[str-split]: https://docs.python.org/3/library/stdtypes.html#str.split
+340
View File
@@ -0,0 +1,340 @@
# Little Sister's Vocabulary
Welcome to Little Sister's Vocabulary on Exercism's Python Track.
If you need help running the tests or submitting your code, check out `HELP.md`.
If you get stuck on the exercise, check out `HINTS.md`, but try and solve it without using those first :)
## Introduction
A `str` in Python is an [immutable sequence][text sequence] of [Unicode code points][unicode code points].
These could include letters, diacritical marks, positioning characters, numbers, currency symbols, emoji, punctuation, space and line break characters, and more.
Being immutable, a `str` object's value in memory doesn't change; methods that appear to modify a string return a new copy or instance of that `str` object.
A `str` literal can be declared via single `'` or double `"` quotes. The escape `\` character is available as needed.
```python
>>> single_quoted = 'These allow "double quoting" without "escape" characters.'
>>> double_quoted = "These allow embedded 'single quoting', so you don't have to use an 'escape' character".
>>> escapes = 'If needed, a \'slash\' can be used as an escape character within a string when switching quote styles won\'t work.'
```
Multi-line strings are declared with `'''` or `"""`.
```python
>>> triple_quoted = '''Three single quotes or "double quotes" in a row allow for multi-line string literals.
Line break characters, tabs and other whitespace are fully supported.
You\'ll most often encounter these as "doc strings" or "doc tests" written just below the first line of a function or class definition.
They\'re often used with auto documentation ✍ tools.
'''
```
Strings can be concatenated using the `+` operator.
This method should be used sparingly, as it is not very performant or easily maintained.
```python
language = "Ukrainian"
number = "nine"
word = "дев'ять"
sentence = word + " " + "means" + " " + number + " in " + language + "."
>>> print(sentence)
...
"дев'ять means nine in Ukrainian."
```
If a `list`, `tuple`, `set` or other collection of individual strings needs to be combined into a single `str`, [`<str>.join(<iterable>)`][str-join], is a better option:
```python
# str.join() makes a new string from the iterables elements.
>>> chickens = ["hen", "egg", "rooster"]
>>> ' '.join(chickens)
'hen egg rooster'
# Any string can be used as the joining element.
>>> ' :: '.join(chickens)
'hen :: egg :: rooster'
>>> ' 🌿 '.join(chickens)
'hen 🌿 egg 🌿 rooster'
```
Code points within a `str` can be referenced by `0-based index` number from the left:
```python
creative = '창의적인'
>>> creative[0]
'창'
>>> creative[2]
'적'
>>> creative[3]
'인'
```
Indexing also works from the right, starting with a `-1-based index`:
```python
creative = '창의적인'
>>> creative[-4]
'창'
>>> creative[-2]
'적'
>>> creative[-1]
'인'
```
There is no separate “character” or "rune" type in Python, so indexing a string produces a new `str` of length 1:
```python
>>> website = "exercism"
>>> type(website[0])
<class 'str'>
>>> len(website[0])
1
>>> website[0] == website[0:1] == 'e'
True
```
Substrings can be selected via _slice notation_, using [`<str>[<start>:stop:<step>]`][common sequence operations] to produce a new string.
Results exclude the `stop` index.
If no `start` is given, the starting index will be 0.
If no `stop` is given, the `stop` index will be the end of the string.
```python
moon_and_stars = '🌟🌟🌙🌟🌟⭐'
sun_and_moon = '🌞🌙🌞🌙🌞🌙🌞🌙🌞'
>>> moon_and_stars[1:4]
'🌟🌙🌟'
>>> moon_and_stars[:3]
'🌟🌟🌙'
>>> moon_and_stars[3:]
'🌟🌟⭐'
>>> moon_and_stars[:-1]
'🌟🌟🌙🌟🌟'
>>> moon_and_stars[:-3]
'🌟🌟🌙'
>>> sun_and_moon[::2]
'🌞🌞🌞🌞🌞'
>>> sun_and_moon[:-2:2]
'🌞🌞🌞🌞'
>>> sun_and_moon[1:-1:2]
'🌙🌙🌙🌙'
```
Strings can also be broken into smaller strings via [`<str>.split(<separator>)`][str-split], which will return a `list` of substrings.
The list can then be further indexed or split, if needed.
Using `<str>.split()` without any arguments will split the string on whitespace.
```python
>>> cat_ipsum = "Destroy house in 5 seconds mock the hooman."
>>> cat_ipsum.split()
...
['Destroy', 'house', 'in', '5', 'seconds', 'mock', 'the', 'hooman.']
>>> cat_ipsum.split()[-1]
'hooman.'
>>> cat_words = "feline, four-footed, ferocious, furry"
>>> cat_words.split(', ')
...
['feline', 'four-footed', 'ferocious', 'furry']
```
Separators for `<str>.split()` can be more than one character.
The **whole string** is used for split matching.
```python
>>> colors = """red,
orange,
green,
purple,
yellow"""
>>> colors.split(',\n')
['red', 'orange', 'green', 'purple', 'yellow']
```
Strings support all [common sequence operations][common sequence operations].
Individual code points can be iterated through in a loop via `for item in <str>`.
Indexes _with_ items can be iterated through in a loop via `for index, item in enumerate(<str>)`.
```python
>>> exercise = 'လေ့ကျင့်'
# Note that there are more code points than perceived glyphs or characters
>>> for code_point in exercise:
... print(code_point)
...
လ
ေ
့
က
ျ
င
်
့
# Using enumerate will give both the value and index position of each element.
>>> for index, code_point in enumerate(exercise):
... print(index, ": ", code_point)
...
0 : လ
1 : ေ
2 : ့
3 : က
4 : ျ
5 : င
6 : ်
7 : ့
```
[common sequence operations]: https://docs.python.org/3/library/stdtypes.html#common-sequence-operations
[str-join]: https://docs.python.org/3/library/stdtypes.html#str.join
[str-split]: https://docs.python.org/3/library/stdtypes.html#str.split
[text sequence]: https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str
[unicode code points]: https://stackoverflow.com/questions/27331819/whats-the-difference-between-a-character-a-code-point-a-glyph-and-a-grapheme
## Instructions
You are helping your younger sister with her English vocabulary homework, which she is finding very tedious.
Her class is learning to create new words by adding _prefixes_ and _suffixes_.
Given a set of words, the teacher is looking for correctly transformed words with correct spelling by adding the prefix to the beginning or the suffix to the ending.
The assignment has four activities, each with a set of text or words to work with.
## 1. Add a prefix to a word
One of the most common prefixes in English is `un`, meaning "not".
In this activity, your sister needs to make negative, or "not" words by adding `un` to them.
Implement the `add_prefix_un(<word>)` function that takes `word` as a parameter and returns a new `un` prefixed word:
```python
>>> add_prefix_un("happy")
'unhappy'
>>> add_prefix_un("manageable")
'unmanageable'
```
## 2. Add prefixes to word groups
There are four more common prefixes that your sister's class is studying:
`en` (_meaning to 'put into' or 'cover with'_),
`pre` (_meaning 'before' or 'forward'_),
`auto` (_meaning 'self' or 'same'_),
and `inter` (_meaning 'between' or 'among'_).
In this exercise, the class is creating groups of vocabulary words using these prefixes, so they can be studied together.
Each prefix comes in a list with common words it's used with.
The students need to apply the prefix and produce a string that shows the prefix applied to all of the words.
Implement the `make_word_groups(<vocab_words>)` function that takes a `vocab_words` as a parameter in the following form:
`[<prefix>, <word_1>, <word_2> .... <word_n>]`, and returns a string with the prefix applied to each word that looks like:
`'<prefix> :: <prefix><word_1> :: <prefix><word_2> :: <prefix><word_n>'`.
```python
>>> make_word_groups(['en', 'close', 'joy', 'lighten'])
'en :: enclose :: enjoy :: enlighten'
>>> make_word_groups(['pre', 'serve', 'dispose', 'position'])
'pre :: preserve :: predispose :: preposition'
>> make_word_groups(['auto', 'didactic', 'graph', 'mate'])
'auto :: autodidactic :: autograph :: automate'
>>> make_word_groups(['inter', 'twine', 'connected', 'dependent'])
'inter :: intertwine :: interconnected :: interdependent'
```
## 3. Remove a suffix from a word
`ness` is a common suffix that means _'state of being'_.
In this activity, your sister needs to find the original root word by removing the `ness` suffix.
But of course there are pesky spelling rules: If the root word originally ended in a consonant followed by a 'y', then the 'y' was changed to 'i'.
Removing 'ness' needs to restore the 'y' in those root words. e.g. `happiness` --> `happi` --> `happy`.
Implement the `remove_suffix_ness(<word>)` function that takes in a `word`, and returns the root word without the `ness` suffix.
```python
>>> remove_suffix_ness("heaviness")
'heavy'
>>> remove_suffix_ness("sadness")
'sad'
```
## 4. Extract and transform a word
Suffixes are often used to change the part of speech a word is assigned to.
A common practice in English is "verbing" or "verbifying" -- where an adjective _becomes_ a verb by adding an `en` suffix.
In this task, your sister is going to practice "verbing" words by extracting an adjective from a sentence and turning it into a verb.
Fortunately, all the words that need to be transformed here are "regular" - they don't need spelling changes to add the suffix.
Implement the `adjective_to_verb(<sentence>, <index>)` function that takes two parameters.
A `sentence` using the vocabulary word, and the `index` of the word, once that sentence is split apart.
The function should return the extracted adjective as a verb.
```python
>>> adjective_to_verb('I need to make that bright.', -1 )
'brighten'
>>> adjective_to_verb('It got dark as the sun set.', 2)
'darken'
```
## Source
### Created by
- @aldraco
- @BethanyG
+59
View File
@@ -0,0 +1,59 @@
"""Functions for creating, transforming, and adding prefixes to strings."""
def add_prefix_un(word):
"""Take the given word and add the 'un' prefix.
:param word: str - containing the root word.
:return: str - of root word prepended with 'un'.
"""
return "un" + word
def make_word_groups(vocab_words):
"""Transform a list containing a prefix and words into a string with the prefix followed by the words with prefix prepended.
:param vocab_words: list - of vocabulary words with prefix in first index.
:return: str - of prefix followed by vocabulary words with
prefix applied.
This function takes a `vocab_words` list and returns a string
with the prefix and the words with prefix applied, separated
by ' :: '.
For example: list('en', 'close', 'joy', 'lighten'),
produces the following string: 'en :: enclose :: enjoy :: enlighten'.
"""
result: str = vocab_words[0]
for word in vocab_words[1:]:
result += " :: " + vocab_words[0] + word
return result
def remove_suffix_ness(word):
"""Remove the suffix from the word while keeping spelling in mind.
:param word: str - of word to remove suffix from.
:return: str - of word with suffix removed & spelling adjusted.
For example: "heaviness" becomes "heavy", but "sadness" becomes "sad".
"""
new_word: str = word[: len(word) - 4]
match new_word[-1]:
case "i":
return new_word[: len(new_word) - 1] + "y"
case _:
return new_word
def adjective_to_verb(sentence, index):
"""Change the adjective within the sentence to a verb.
:param sentence: str - that uses the word in sentence.
:param index: int - index of the word to remove and transform.
:return: str - word that changes the extracted adjective to a verb.
For example, ("It got dark as the sun set.", 2) becomes "darken".
"""
word_to_transform: str = sentence.split(" ")[index]
return word_to_transform.strip(".,!?") + "en"
+126
View File
@@ -0,0 +1,126 @@
import unittest
import pytest
from strings import (add_prefix_un,
make_word_groups,
remove_suffix_ness,
adjective_to_verb)
class LittleSistersVocabTest(unittest.TestCase):
@pytest.mark.task(taskno=1)
def test_add_prefix_un(self):
input_data = ['happy', 'manageable', 'fold', 'eaten', 'avoidable', 'usual']
result_data = [f'un{item}' for item in input_data]
for variant, (word, expected) in enumerate(zip(input_data, result_data), start=1):
with self.subTest(f'variation #{variant}', word=word, expected=expected):
actual_result = add_prefix_un(word)
error_message = (f'Called add_prefix_un("{word}"). '
f'The function returned "{actual_result}", but the '
f'tests expected "{expected}" after adding "un" as a prefix.')
self.assertEqual(actual_result, expected, msg=error_message)
@pytest.mark.task(taskno=2)
def test_make_word_groups_en(self):
input_data = ['en', 'circle', 'fold', 'close', 'joy', 'lighten', 'tangle', 'able', 'code', 'culture']
expected = ('en :: encircle :: enfold :: enclose :: enjoy :: enlighten ::'
' entangle :: enable :: encode :: enculture')
actual_result = make_word_groups(input_data)
error_message = (f'Called make_word_groups({input_data}). '
f'The function returned "{actual_result}", '
f'but the tests expected "{expected}" for the '
'word groups.')
self.assertEqual(actual_result, expected, msg=error_message)
@pytest.mark.task(taskno=2)
def test_make_word_groups_pre(self):
input_data = ['pre', 'serve', 'dispose', 'position', 'requisite', 'digest',
'natal', 'addressed', 'adolescent', 'assumption', 'mature', 'compute']
expected = ('pre :: preserve :: predispose :: preposition :: prerequisite :: '
'predigest :: prenatal :: preaddressed :: preadolescent :: preassumption :: '
'premature :: precompute')
actual_result = make_word_groups(input_data)
error_message = (f'Called make_word_groups({input_data}). '
f'The function returned "{actual_result}", '
f'but the tests expected "{expected}" for the '
'word groups.')
self.assertEqual(actual_result, expected, msg=error_message)
@pytest.mark.task(taskno=2)
def test_make_word_groups_auto(self):
input_data = ['auto', 'didactic', 'graph', 'mate', 'chrome', 'centric', 'complete',
'echolalia', 'encoder', 'biography']
expected = ('auto :: autodidactic :: autograph :: automate :: autochrome :: '
'autocentric :: autocomplete :: autoecholalia :: autoencoder :: '
'autobiography')
actual_result = make_word_groups(input_data)
error_message = (f'Called make_word_groups({input_data}). '
f'The function returned "{actual_result}", '
f'but the tests expected "{expected}" for the '
'word groups.')
self.assertEqual(actual_result, expected, msg=error_message)
@pytest.mark.task(taskno=2)
def test_make_words_groups_inter(self):
input_data = ['inter', 'twine', 'connected', 'dependent', 'galactic', 'action',
'stellar', 'cellular', 'continental', 'axial', 'operative', 'disciplinary']
expected = ('inter :: intertwine :: interconnected :: interdependent :: '
'intergalactic :: interaction :: interstellar :: intercellular :: '
'intercontinental :: interaxial :: interoperative :: interdisciplinary')
actual_result = make_word_groups(input_data)
error_message = (f'Called make_word_groups({input_data}). '
f'The function returned "{actual_result}", '
f'but the tests expected "{expected}" for the '
'word groups.')
self.assertEqual(actual_result, expected, msg=error_message)
@pytest.mark.task(taskno=3)
def test_remove_suffix_ness(self):
input_data = ['heaviness', 'sadness', 'softness', 'crabbiness', 'lightness', 'artiness', 'edginess']
result_data = ['heavy', 'sad', 'soft', 'crabby', 'light', 'arty', 'edgy']
for variant, (word, expected) in enumerate(zip(input_data, result_data), start=1):
with self.subTest(f'variation #{variant}', word=word, expected=expected):
actual_result = remove_suffix_ness(word)
error_message = (f'Called remove_suffix_ness("{word}"). '
f'The function returned "{actual_result}", '
f'but the tests expected "{expected}" after the '
'suffix was removed.')
self.assertEqual(actual_result, expected, msg=error_message)
@pytest.mark.task(taskno=4)
def test_adjective_to_verb(self):
input_data = ['Look at the bright sky.',
'His expression went dark.',
'The bread got hard after sitting out.',
'The butter got soft in the sun.',
'Her eyes were light blue.',
'The morning fog made everything damp with mist.',
'He cut the fence pickets short by mistake.',
'Charles made weak crying noises.',
'The black oil got on the white dog.']
index_data = [-2, -1, 3, 3, -2, -3, 5, 2, 1]
result_data = ['brighten', 'darken', 'harden', 'soften',
'lighten', 'dampen', 'shorten', 'weaken', 'blacken']
for variant, (sentence, index, expected) in enumerate(zip(input_data, index_data, result_data), start=1):
with self.subTest(f'variation #{variant}', sentence=sentence, index=index, expected=expected):
actual_result = adjective_to_verb(sentence, index)
error_message = (f'Called adjective_to_verb("{sentence}", {index}). '
f'The function returned "{actual_result}", but the tests '
f'expected "{expected}" as the verb for '
f'the word at index {index}.')
self.assertEqual(actual_result, expected, msg=error_message)