diff --git a/.vscode/settings.json b/.vscode/settings.json index 252022b48..712b75631 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -122,5 +122,14 @@ "source.fixAll.ruff": "explicit", "source.organizeImports.ruff": "explicit" } - } + }, + "python.testing.unittestArgs": [ + "-v", + "-s", + "./solutions", + "-p", + "*test.py" + ], + "python.testing.pytestEnabled": false, + "python.testing.unittestEnabled": true } diff --git a/solutions/challenge_39/word_length_counter.py b/solutions/challenge_39/word_length_counter.py new file mode 100644 index 000000000..cd55d969b --- /dev/null +++ b/solutions/challenge_39/word_length_counter.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +A module for calculating the lengths of words in a sentence. +created: 01/07/2025 +@author: Arthur (Mr-Glucose) +""" + +import string + + +def word_lengths(input_sentence: str) -> list[int]: + """ + Takes a sentence and returns a list of word lengths, ignoring punctuation. + + Args: + input_sentence (str): The input sentence. + + Returns: + list: A list of integers representing word lengths. + + Assumptions: + - If the input sentence is empty, the function will return an empty list. + - Punctuation is ignored when calculating word lengths. + - Case sensitivity does not affect word length calculation. + + Examples: + >>> word_lengths("Hello world!") + [5, 5] + >>> word_lengths("Python is awesome.") + [6, 2, 7] + >>> word_lengths("co-op re-enter.") + [4, 7] + >>> word_lengths("") + [] + >>> word_lengths("...?!") + [] + """ + words = input_sentence.translate(str.maketrans("", "", string.punctuation)).split() + return [len(word) for word in words] diff --git a/solutions/tests/challenge_39/test_word_length_counter.py b/solutions/tests/challenge_39/test_word_length_counter.py new file mode 100644 index 000000000..237659efc --- /dev/null +++ b/solutions/tests/challenge_39/test_word_length_counter.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Tests for the word_lengths function. +""" + +import unittest + +from solutions.challenge_39.word_length_counter import word_lengths + + +class TestWordLengths(unittest.TestCase): + def test_multiple_words(self): + self.assertEqual(word_lengths("Hello world!"), [5, 5]) + self.assertEqual(word_lengths("Python is awesome."), [6, 2, 7]) + + def test_single_word(self): + self.assertEqual(word_lengths("Amazing!"), [7]) + + def test_empty_string(self): + self.assertEqual(word_lengths(""), []) + + def test_only_punctuation(self): + self.assertEqual(word_lengths("...?!"), []) + + def test_mixed_content(self): + self.assertEqual(word_lengths("123 and 4567!"), [3, 3, 4]) + + def test_special_characters_in_words(self): + self.assertEqual(word_lengths("co-op re-enter."), [4, 7]) + + +if __name__ == "__main__": + unittest.main()