TheAlgorithms-Python/strings/largest_smallest_words.py

47 lines
1.3 KiB
Python
Raw Normal View History

2023-10-10 23:56:16 +08:00
from typing import Tuple, Optional
def find_smallest_and_largest_words(
input_string: str,
) -> Tuple[Optional[str], Optional[str]]:
2023-10-10 23:56:16 +08:00
"""
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[Optional[str], Optional[str]]: A tuple containing the smallest and largest words found.
If no words are found, both values in the tuple will be None.
Example:
>>> find_smallest_and_largest_words("My name is abc")
('My', 'name')
>>> find_smallest_and_largest_words("")
(None, None)
"""
2023-10-10 22:43:27 +08:00
words = input_string.split()
if not words:
return None, None
smallest_word = min(words, key=len)
largest_word = max(words, key=len)
return smallest_word, largest_word
2023-10-10 22:43:27 +08:00
if __name__ == "__main__":
2023-10-10 23:56:16 +08:00
import doctest
2023-10-10 23:56:16 +08:00
doctest.testmod()
input_string = input("Enter a sentence:\n").strip()
2023-10-10 22:43:27 +08:00
smallest, largest = find_smallest_and_largest_words(input_string)
if smallest is not None and largest is not None:
2023-10-10 23:56:16 +08:00
print(f"The smallest word in the given sentence is '{smallest}'")
print(f"The largest word in the given sentence is '{largest}'")
2023-10-10 22:43:27 +08:00
else:
print("No words found in the input sentence.")