Write a Python program to find smallest and largest word in a given string


The program takes an input string and finds the smallest and largest word in the string. Here's a step by step explanation of the code:

  • The first line takes the input string and stores it in the "str" variable. The next line prints the original string.
  • The next line creates an empty string variable "word" and an empty list "all_words".
  • The next line appends a space character to the end of the input string so that the final word in the string can be processed correctly.
  • The next part of the code uses a for loop to iterate over each character in the string. If the current character is not a space, the character is added to the "word" variable. If the current character is a space, the current "word" is added to the "all_words" list, and the "word" variable is reset to an empty string.
  • After processing all the characters in the string, the "small" variable is initialized to the first word in the "all_words" list, and the "large" variable is initialized to the same value.
  • The next part of the code uses another for loop to iterate over each word in the "all_words" list. If the length of the current word is smaller than the length of the "small" variable, the current word becomes the new value for "small". If the length of the current word is larger than the length of the "large" variable, the current word becomes the new value for "large".
  • The final two "print" statements output the smallest and largest words in the input string to the console.

Source Code

str = "Tutor Joes Computer Education"
print("Original Strings : ",str)
word = ""
all_words = []
str = str + " "
for i in range(0, len(str)):
	if(str[i] != ' '):
		word = word + str[i]
	else:
		all_words.append(word) 
		word = ""
 
small = large = all_words[0]
 
#Find smallest and largest word in the str  
for k in range(0, len(all_words)):
	if(len(small) > len(all_words[k])):
		small = all_words[k]
	if(len(large) < len(all_words[k])):
		large = all_words[k]
print("Smallest word: " + small)
print("Largest word: " + large)

Output

Original Strings :  Tutor Joes Computer Education
Smallest word: Joes
Largest word: Education


Example Programs