How to find the smallest and largest word from a string in python. Write Python Program to find the smallest and the largest word from a string.
How to find the smallest and the largest word in a string?
Given a string, locate the smallest and the largest length words in it.
What is the smallest and the largest word in a string?
Input: Welcome to Codebun where you will find the solution to all programming problems
Output:
Smallest word: to
Largest word: programming
Algorithm to find the smallest and the largest word in a string:
• Input a string
• Iterate through the string using a while loop to find the space which will help us to find the length of the word.
• Using if condition checks whether the present word is smaller or greater in length than the word present.
• If smaller assign it one variable and if greater assign it to another new variable.
• Print both the variables.
Python program to find the smallest and the largest word in a string.
def words(str1): word = "" words1 = [] str1 = str1 + " " for i in range(0, len(str1)): if (str1[i] != ' '): word = word + str1[i] else: words1.append(word) word = "" small = large = words1[0] # Find smallest and largest word in the str1 for k in range(0, len(words1)): if (len(small) > len(words1[k])): small = words1[k] if (len(large) < len(words1[k])): large = words1[k] return small, large str1 = "Welcome to Codedec where you will find solution to all programming problems" print("STRING IS:", str1) small, large = words(str1) print("Smallest word: " + small) print("Largest word: " + large)