Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to find the smallest word in a sentence
Welcome to this tutorial on writing a Python program to find the smallest word in a sentence. Whether you are a beginner or intermediate Python programmer, this guide will help you learn text manipulation using Python's built-in functions.
Problem Statement
Given a sentence, we need to find the word with the fewest characters. In case of a tie, we'll return the first occurring smallest word.
Using min() with key Parameter
The most efficient approach uses the min() function with a key parameter to compare word lengths ?
def find_smallest_word(sentence):
# Split the sentence into words
words = sentence.split()
# Find the smallest word using min() with len as key
smallest_word = min(words, key=len)
return smallest_word
# Test the function
sentence = "Python programming is fun and rewarding"
result = find_smallest_word(sentence)
print(f"The smallest word is: '{result}'")
The smallest word is: 'is'
Using a Loop Approach
We can also iterate through words manually to find the smallest one ?
def find_smallest_word_loop(sentence):
words = sentence.split()
# Initialize with first word
smallest_word = words[0]
# Compare each word
for word in words:
if len(word) < len(smallest_word):
smallest_word = word
return smallest_word
# Test the function
sentence = "I love coding in Python"
result = find_smallest_word_loop(sentence)
print(f"The smallest word is: '{result}'")
The smallest word is: 'I'
Handling Edge Cases
Let's create a more robust version that handles empty strings and punctuation ?
import string
def find_smallest_word_robust(sentence):
if not sentence.strip():
return None
# Remove punctuation and split
clean_sentence = sentence.translate(str.maketrans('', '', string.punctuation))
words = clean_sentence.split()
if not words:
return None
return min(words, key=len)
# Test with different cases
test_cases = [
"Hello, world! How are you?",
"I am fine.",
"",
" ",
"Programming is fun!"
]
for sentence in test_cases:
result = find_smallest_word_robust(sentence)
print(f"'{sentence}' ? {result}")
'Hello, world! How are you?' ? I 'I am fine.' ? I '' ? None ' ' ? None 'Programming is fun!' ? is
Comparison of Methods
| Method | Time Complexity | Readability | Best For |
|---|---|---|---|
min() with key |
O(n) | High | Simple, clean code |
| Loop approach | O(n) | Medium | Learning purposes |
| Robust version | O(n) | Medium | Production code |
Conclusion
The min() function with key=len parameter provides the most concise solution for finding the smallest word. For production code, consider handling edge cases like empty strings and punctuation removal.
