Skip to content

Commit 1e19046

Browse files
Create largest_smallest_words.py (#10234)
* Create largest_smallest_words.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update largest_smallest_words.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update largest_smallest_words.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update largest_smallest_words.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update largest_smallest_words.py * Update largest_smallest_words.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent b8f94b1 commit 1e19046

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

strings/largest_smallest_words.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
def find_smallest_and_largest_words(input_string: str) -> tuple:
2+
"""
3+
Find the smallest and largest words in a given input string based on their length.
4+
5+
Args:
6+
input_string (str): The input string to analyze.
7+
8+
Returns:
9+
tuple: A tuple containing the smallest and largest words found.
10+
If no words are found, both values in the tuple will be None.
11+
12+
Examples:
13+
>>> find_smallest_and_largest_words("My name is abc")
14+
('My', 'name')
15+
16+
>>> find_smallest_and_largest_words("Hello guys")
17+
('guys', 'Hello')
18+
19+
>>> find_smallest_and_largest_words("OnlyOneWord")
20+
('OnlyOneWord', 'OnlyOneWord')
21+
"""
22+
words = input_string.split()
23+
if not words:
24+
return None, None
25+
26+
# Handle punctuation and special characters
27+
words = [word.strip(".,!?()[]{}") for word in words]
28+
29+
smallest_word = min(words, key=len)
30+
largest_word = max(words, key=len)
31+
32+
return smallest_word, largest_word
33+
34+
35+
if __name__ == "__main__":
36+
import doctest
37+
38+
doctest.testmod()
39+
40+
input_string = input("Enter a sentence:\n").strip()
41+
smallest, largest = find_smallest_and_largest_words(input_string)
42+
43+
if smallest and largest:
44+
print(f"The smallest word in the given sentence is '{smallest}'")
45+
print(f"The largest word in the given sentence is '{largest}'")
46+
else:
47+
print("No words found in the input sentence.")

0 commit comments

Comments
 (0)