forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlargest_smallest_words.py
More file actions
47 lines (34 loc) · 1.36 KB
/
Copy pathlargest_smallest_words.py
File metadata and controls
47 lines (34 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def find_smallest_and_largest_words(input_string: str) -> tuple:
"""
Find the smallest and largest words in a given input string based on their length.
Args:
input_string (str): The input string to analyze.
Returns:
tuple: A tuple containing the smallest and largest words found.
If no words are found, both values in the tuple will be None.
Examples:
>>> find_smallest_and_largest_words("My name is abc")
('My', 'name')
>>> find_smallest_and_largest_words("Hello guys")
('guys', 'Hello')
>>> find_smallest_and_largest_words("OnlyOneWord")
('OnlyOneWord', 'OnlyOneWord')
"""
words = input_string.split()
if not words:
return None, None
# Handle punctuation and special characters
words = [word.strip(".,!?()[]{}") for word in words]
smallest_word = min(words, key=len)
largest_word = max(words, key=len)
return smallest_word, largest_word
if __name__ == "__main__":
import doctest
doctest.testmod()
input_string = input("Enter a sentence:\n").strip()
smallest, largest = find_smallest_and_largest_words(input_string)
if smallest and largest:
print(f"The smallest word in the given sentence is '{smallest}'")
print(f"The largest word in the given sentence is '{largest}'")
else:
print("No words found in the input sentence.")