Skip to content

Create largest_smallest_words.py #10234

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions strings/largest_smallest_words.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,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.")