Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@ Personal solutions to [**Python** track][python_track] exercises from [**Exercis
4. ["**Currency Exchange**" solution](python/currency-exchange/exchange.py).
5. ["**Meltdown Mitigation**" solution](python/meltdown-mitigation/conditionals.py).
6. ["**Black Jack**" solution](python/black-jack/black_jack.py).
7. ["**Little Sister's Essay**" solution](python/little-sisters-essay/string_methods.py).
<!-- Put next solution item here! -->

[python_version_badge]: https://img.shields.io/badge/Python%203.13-3776AB?logo=python&logoColor=FFD43B
[track_completion_badge]: https://img.shields.io/badge/Track%20completion-4.1%25-604fcd?logo=exercism&logoColor=604fcd&labelColor=e9ecef
[exercises_completed_badge]: https://img.shields.io/badge/Exercises%20completed-6%2F146-604fcd?logo=exercism&logoColor=604fcd&labelColor=e9ecef
[track_completion_badge]: https://img.shields.io/badge/Track%20completion-4.8%25-604fcd?logo=exercism&logoColor=604fcd&labelColor=e9ecef
[exercises_completed_badge]: https://img.shields.io/badge/Exercises%20completed-7%2F146-604fcd?logo=exercism&logoColor=604fcd&labelColor=e9ecef
[python_track]: https://exercism.org/tracks/python
[exercism]: https://exercism.org
29 changes: 29 additions & 0 deletions python/little-sisters-essay/HINTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Hints

## General

- [Python Documentation: String Methods][string-method-docs]
- [Python Documentation Tutorial: Text][tutorial-strings]

## 1. Capitalize the title of the paper

- You can use [string methods][title-method-docs] to capitalize the title properly.

## 2. Check if each sentence ends with a period

- You can use [string methods][endswith-method-docs] to check the ending of a string.

## 3. Clean up spacing

- You can use [string methods][strip-method-docs] to remove whitespace.

## 4. Replace words with a synonym

- You can use [string methods][replace-method-docs] to replace words.

[endswith-method-docs]: https://docs.python.org/3/library/stdtypes.html#str.endswith
[replace-method-docs]: https://docs.python.org/3/library/stdtypes.html#str.replace
[string-method-docs]: https://docs.python.org/3/library/stdtypes.html#string-methods
[strip-method-docs]: https://docs.python.org/3/library/stdtypes.html#str.strip
[title-method-docs]: https://docs.python.org/3/library/stdtypes.html#str.title
[tutorial-strings]: https://docs.python.org/3/tutorial/introduction.html#text
194 changes: 194 additions & 0 deletions python/little-sisters-essay/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
# Little Sister's Essay

Welcome to Little Sister's Essay on Exercism's Python Track.
If you get stuck on the exercise, check out `HINTS.md`, but try and solve it without using those first :)

## Introduction

The `str` class offers [many useful methods][str methods] for working with and composing strings.
These include searching, cleaning, splitting, transforming, translating, and many other techniques.

Strings are [sequences][text sequence] of [Unicode code points][unicode code points] -- individual "characters" or code points (_strings of length 1_) can be referenced by `0-based index` number from the left, or `-1-based index` number from the right.
Strings implement all [common sequence operations][common sequence operations].

They can be iterated through using `for item in <str>` or `for index, item in enumerate(<str>)` syntax.
They can also be concatenated using `<str> + <other str>` or `<str>.join(<iterable>)`.

Strings are _immutable_, meaning the value of a `str` object in memory cannot change.
Functions or methods that operate on a `str` (_like the ones we are learning about here_) will return a new `instance` of that `str` object instead of modifying the original `str`.

Following is a small selection of Python string methods.
For a complete list, see the [str class][str methods] in the Python docs.


[`<str>.title()`][str-title] parses a string and capitalizes the first "character" of each "word" found.
In Python, this is very dependent on the [language codec][codecs] used and how the particular language represents words and characters.
There may also be [locale][locale] rules in place for a language or character set.


```python
man_in_hat_th = 'ผู้ชายใส่หมวก'
man_in_hat_ru = 'мужчина в шляпе'
man_in_hat_ko = '모자를 쓴 남자'
man_in_hat_en = 'the man in the hat.'

>>> man_in_hat_th.title()
'ผู้ชายใส่หมวก'

>>> man_in_hat_ru.title()
'Мужчина В Шляпе'

>>> man_in_hat_ko.title()
'모자를 쓴 남자'

>> man_in_hat_en.title()
'The Man In The Hat.'
```

[`<str>.endswith(<suffix>)`][str-endswith] returns `True` if the string ends with `<suffix>`, `False` otherwise.


```python
>>> 'My heart breaks. 💔'.endswith('💔')
True

>>> 'cheerfulness'.endswith('ness')
True

# Punctuation is part of the string, so needs to be included in any endswith match.
>>> 'Do you want to 💃?'.endswith('💃')
False

>> 'The quick brown fox jumped over the lazy dog.'.endswith('dog')
False
```

[`<str>.strip(<chars>)`][str-strip] returns a copy of the `str` with leading and trailing `<chars>` removed.
The code points specified in `<chars>` are not a prefix or suffix - **all combinations** of the code points will be removed starting from **both ends** of the string.
If nothing is specified for `<chars>`, all combinations of whitespace code points will be removed.


```python
# This will remove "https://", because it can be formed from "/stph:".
>>> 'https://unicode.org/emoji/'.strip('/stph:')
'unicode.org/emoji'

# Removal of all whitespace from both ends of the str.
>>> ' 🐪🐪🐪🌟🐪🐪🐪 '.strip()
'🐪🐪🐪🌟🐪🐪🐪'

>>> justification = 'оправдание'
>>> justification.strip('еина')
'оправд'

# Prefix and suffix in one step.
>>> 'unaddressed'.strip('dnue')
'address'

>>> ' unaddressed '.strip('dnue ')
'address'
```


[`<str>.replace(<substring>, <replacement substring>)`][str-replace] returns a copy of the string with all occurrences of `<substring>` replaced with `<replacement substring>`.

The quote used below is from [The Hunting of the Snark][The Hunting of the Snark] by [Lewis Carroll][Lewis Carroll]

```python
# The Hunting of the Snark, by Lewis Carroll
>>> quote = '''
"Just the place for a Snark!" the Bellman cried,
As he landed his crew with care;
Supporting each man on the top of the tide
By a finger entwined in his hair.

"Just the place for a Snark! I have said it twice:
That alone should encourage the crew.
Just the place for a Snark! I have said it thrice:
What I tell you three times is true."
'''

>>> quote.replace('Snark', '🐲')
...
'\n"Just the place for a 🐲!" the Bellman cried,\n As he landed his crew with care;\nSupporting each man on the top of the tide\n By a finger entwined in his hair.\n\n"Just the place for a 🐲! I have said it twice:\n That alone should encourage the crew.\nJust the place for a 🐲! I have said it thrice:\n What I tell you three times is true."\n'

>>> 'bookkeeper'.replace('kk', 'k k')
'book keeper'
```

[Lewis Carroll]: https://www.poetryfoundation.org/poets/lewis-carroll
[The Hunting of the Snark]: https://www.poetryfoundation.org/poems/43909/the-hunting-of-the-snark
[codecs]: https://docs.python.org/3/library/codecs.html
[common sequence operations]: https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str
[locale]: https://docs.python.org/3/library/locale.html#module-locale
[str methods]: https://docs.python.org/3/library/stdtypes.html#string-methods
[str-endswith]: https://docs.python.org/3/library/stdtypes.html#str.endswith
[str-replace]: https://docs.python.org/3/library/stdtypes.html#str.replace
[str-strip]: https://docs.python.org/3/library/stdtypes.html#str.strip
[str-title]: https://docs.python.org/3/library/stdtypes.html#str.title
[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

In this exercise you are helping your younger sister edit her paper for school. The teacher is looking for correct punctuation, grammar, and excellent word choice.

You have four tasks to clean up and modify strings.

## 1. Capitalize the title of the paper

Any good paper needs a properly formatted title.
Implement the function `capitalize_title(<title>)` which takes a title `str` as a parameter and capitalizes the first letter of each word.
This function should return a `str` in title case.


```python
>>> capitalize_title("my hobbies")
"My Hobbies"
```

## 2. Check if each sentence ends with a period

You want to make sure that the punctuation in the paper is perfect.
Implement the function `check_sentence_ending()` that takes `sentence` as a parameter. This function should return a `bool`.


```python
>>> check_sentence_ending("I like to hike, bake, and read.")
True
```

## 3. Clean up spacing

To make the paper look professional, unnecessary spacing needs to be removed.
Implement the function `clean_up_spacing()` that takes `sentence` as a parameter.
The function should remove extra whitespace at both the beginning and the end of the sentence, returning a new, updated sentence `str`.


```python
>>> clean_up_spacing(" I like to go on hikes with my dog. ")
"I like to go on hikes with my dog."
```

## 4. Replace words with a synonym

To make the paper _even better_, you can replace some of the adjectives with their synonyms.
Write the function `replace_word_choice()` that takes `sentence`, `old_word`, and `new_word` as parameters.
This function should replace all instances of the `old_word` with the `new_word`, and return a new `str` with the updated sentence.


```python
>>> replace_word_choice("I bake good cakes.", "good", "amazing")
"I bake amazing cakes."
```

## Source

### Created by

- @kimolivia

### Contributed to by

- @valentin-p
- @BethanyG
55 changes: 55 additions & 0 deletions python/little-sisters-essay/string_methods.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""Functions to help edit essay homework using string manipulation."""


def capitalize_title(title):
"""Convert the first letter of each word in the title to uppercase if needed.

Parameters:
title (str): Essay title that needs title casing.

Returns:
str: The title string in title case (first letters capitalized).
"""

return title.title()


def check_sentence_ending(sentence):
"""Check the ending of the sentence to verify that a period is present.

Parameters:
sentence (str): A sentence to check.

Returns:
bool: Is the sentence punctuated correctly?
"""

return sentence.endswith('.')


def clean_up_spacing(sentence):
"""Trim any leading or trailing whitespace from the sentence.

Parameters:
sentence (str): A sentence to clean of leading and trailing space characters.

Returns:
str: A sentence that has been cleaned of leading and trailing space characters.
"""

return sentence.strip()


def replace_word_choice(sentence, old_word, new_word):
"""Replace a word in the provided sentence with a new one.

Parameters:
sentence (str): A sentence to replace words in.
old_word (str): The word to replace.
new_word (str): The replacement word.

Returns:
str: Input sentence with new words in place of old words.
"""

return sentence.replace(old_word, new_word)
98 changes: 98 additions & 0 deletions python/little-sisters-essay/string_methods_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import unittest
import pytest
from string_methods import (capitalize_title,
check_sentence_ending,
clean_up_spacing,
replace_word_choice)


class LittleSistersEssayTest(unittest.TestCase):

@pytest.mark.task(taskno=1)
def test_capitalize_word(self):

actual_result = capitalize_title("canopy")
expected = "Canopy"
error_message = (f'Called capitalize_title("canopy"). '
f'The function returned "{actual_result}", '
f'but the tests expected "{expected}" for the title.')

self.assertEqual(actual_result, expected, msg=error_message)

@pytest.mark.task(taskno=1)
def test_capitalize_title(self):

actual_result = capitalize_title("fish are cold blooded")
expected = "Fish Are Cold Blooded"
error_message = (f'Called capitalize_title("fish are cold blooded"). '
f'The function returned "{actual_result}", '
f'but the tests expected "{expected}" for the title.')

self.assertEqual(actual_result, expected, msg=error_message)

@pytest.mark.task(taskno=2)
def test_sentence_ending(self):

actual_result = check_sentence_ending("Snails can sleep for 3 years.")
expected = True
error_message = (f'Called check_sentence_ending("Snails can sleep for 3 years."). '
f'The function returned {actual_result}, '
f'but the tests expected {expected} for a period ending.')

self.assertEqual(actual_result, expected, msg=error_message)

@pytest.mark.task(taskno=2)
def test_sentence_ending_without_period(self):

actual_result = check_sentence_ending("Fittonia are nice")
expected = False
error_message = (f'Called check_sentence_ending("Fittonia are nice"). '
f'The function returned {actual_result}, '
f'but the tests expected {expected} for a period ending.')

self.assertEqual(actual_result, expected, msg=error_message)

@pytest.mark.task(taskno=3)
def test_remove_extra_spaces_only_start(self):

actual_result = clean_up_spacing(" A rolling stone gathers no moss")
expected = "A rolling stone gathers no moss"
error_message = (f'Called clean_up_spacing(" A rolling stone gathers no moss"). '
f'The function returned "{actual_result}", '
f'but the tests expected "{expected}" as a cleaned string.')

self.assertEqual(actual_result, expected, msg=error_message)

@pytest.mark.task(taskno=3)
def test_remove_extra_spaces(self):

actual_result = clean_up_spacing(" Elephants can't jump. ")
expected = "Elephants can't jump."
error_message = ("Called clean_up_spacing(\" Elephants can't jump. \")"
f'The function returned "{actual_result}", '
f'but the tests expected "{expected}" as a cleaned string.')

self.assertEqual(actual_result, expected, msg=error_message)

@pytest.mark.task(taskno=4)
def test_replace_word_choice(self):

actual_result = replace_word_choice("Animals are cool.", "cool", "awesome")
expected = "Animals are awesome."
error_message = ('Called replace_word_choice("Animals are cool.", "cool", "awesome"). '
f'The function returned "{actual_result}", '
f'but the tests expected "{expected}" after the word replacement.')

self.assertEqual(actual_result, expected, msg=error_message)

@pytest.mark.task(taskno=4)
def test_replace_word_not_exist(self):

actual_result = replace_word_choice("Animals are cool.", "small", "tiny")
expected = "Animals are cool."
error_message = ('Called replace_word_choice("Animals are cool.", "small", "tiny"). '
f'The function returned "{actual_result}", '
f'but the tests expected "{expected}", because the word '
'to be replaced is not in the sentence.')

self.assertEqual(actual_result, expected, msg=error_message)
Loading