mirror of
https://hub.njuu.cf/TheAlgorithms/Python.git
synced 2023-10-11 13:06:12 +08:00
Update largest_smallest_words.py
This commit is contained in:
parent
b345ea586f
commit
b1ceb138f3
@ -1,14 +1,23 @@
|
||||
"""
|
||||
To find the smallest and largest word in the sentence
|
||||
Example
|
||||
if the input string is
|
||||
My name is abc
|
||||
then the output will be
|
||||
The smallest word in the given string is be
|
||||
The largest word in the given string is output
|
||||
"""
|
||||
from typing import Tuple, Optional
|
||||
|
||||
def find_smallest_and_largest_words(input_string):
|
||||
def find_smallest_and_largest_words(input_string: str) -> Tuple[Optional[str], Optional[str]]:
|
||||
"""
|
||||
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)
|
||||
"""
|
||||
words = input_string.split()
|
||||
if not words:
|
||||
return None, None
|
||||
@ -19,11 +28,14 @@ def find_smallest_and_largest_words(input_string):
|
||||
return smallest_word, largest_word
|
||||
|
||||
if __name__ == "__main__":
|
||||
input_string = input("Enter a string here:\n").strip()
|
||||
import doctest
|
||||
doctest.testmod()
|
||||
|
||||
input_string = input("Enter a sentence:\n").strip()
|
||||
smallest, largest = find_smallest_and_largest_words(input_string)
|
||||
|
||||
if smallest is not None and largest is not None:
|
||||
print(f"The smallest word in the given string is {smallest}")
|
||||
print(f"The largest word in the given string is {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 string.")
|
||||
print("No words found in the input sentence.")
|
Loading…
x
Reference in New Issue
Block a user