Pangram, Longest and Shortest Word Program in Java and Python
Pangram, longest word and shortest word program with algorithm, explanation, Java solution and simple Python solution for ISC practical students.
Question:
Write a program to accept a sentence which may be terminated by either '.', '?' or '!' only. The words may be separated by a single blank space and should be case-insensitive.
Determine whether the sentence is a pangram. A pangram is a sentence that contains every letter of the alphabet at least once.
Display the first occurring longest word and shortest word in the accepted sentence.
Algorithm:
Step 1: Start.
Step 2: Accept the sentence from the user.
Step 3: If the sentence is empty, display INVALID INPUT and stop.
Step 4: Store the last character and check whether it is period, question mark or exclamation mark.
Step 5: Remove the terminating punctuation mark from the sentence.
Step 6: Convert the remaining sentence to uppercase for pangram checking.
Step 7: Create an integer array of size 26 initialized with 0.
Step 8: Scan each character; if it is from A to Z, mark its alphabet position in the array as 1.
Step 9: Check all 26 positions; if every position is 1, the sentence is a pangram.
Step 10: Use StringTokenizer to count words, then run a for loop and extract one word at a time.
Step 11: Store the first word as both longest and shortest; update only on strictly longer or strictly shorter words.
Step 12: Display pangram result, longest word and shortest word.
Step 13: Stop.
Explanation:
The program solves two separate tasks after first validating the sentence. The sentence is accepted only if its last character is a full stop, question mark or exclamation mark. This validation is important because the practical question defines these as the only valid terminators. After validation, the punctuation mark is removed so that word processing is done only on the actual sentence.
For pangram checking, the program converts the sentence to uppercase and uses an integer array of size 26. Each array position represents one alphabet from A to Z. When a letter is found, its position is calculated using ch - 'A' and that array position is marked as 1. After scanning the sentence, the program checks all 26 positions. If any position is still 0, at least one alphabet is missing and the sentence is not a pangram.
For longest and shortest word detection, the program uses StringTokenizer to extract words one by one. The first token is stored as both longest and shortest because there is no earlier word for comparison. For every later word, length comparison is used. The longest word is replaced only when a strictly longer word appears, and the shortest word is replaced only when a strictly shorter word appears. This preserves the first occurring longest and shortest words when there is a tie.
Java Program:
/**
* The class PangramWords accepts a sentence, checks whether it is a pangram,
* and displays the first occurring longest and shortest words.
*
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
* @Question Type : ISC Practical
*/
import java.util.Scanner;
import java.util.StringTokenizer;
class PangramWords
{
String sentence;
PangramWords(String s)
{
sentence = s;
}
boolean isValid()
{
int len = sentence.length();
if(len == 0)
{
return false;
}
char last = sentence.charAt(len - 1);
return (last == '.' || last == '?' || last == '!');
}
boolean isPangram(String text)
{
String upper = text.toUpperCase();
int letters[] = new int[26];
// Mark every alphabet found in the sentence.
for(int i = 0; i < upper.length(); i++)
{
char ch = upper.charAt(i);
if(ch >= 'A' && ch <= 'Z')
{
letters[ch - 'A'] = 1;
}
}
// If any alphabet is missing, the sentence is not a pangram.
for(int i = 0; i < 26; i++)
{
if(letters[i] == 0)
{
return false;
}
}
return true;
}
void displayWords(String text)
{
StringTokenizer st = new StringTokenizer(text);
int n = st.countTokens();
String longest = "";
String shortest = "";
for(int i = 1; i <= n; i++)
{
String word = st.nextToken();
if(i == 1)
{
longest = word;
shortest = word;
}
else
{
// Strict comparison preserves the first occurring longest word.
if(word.length() > longest.length())
{
longest = word;
}
// Strict comparison preserves the first occurring shortest word.
if(word.length() < shortest.length())
{
shortest = word;
}
}
}
System.out.println("LONGEST WORD: " + longest);
System.out.println("SHORTEST WORD: " + shortest);
}
void displayResult()
{
if(isValid() == false)
{
System.out.println("INVALID INPUT");
}
else
{
String text = sentence.substring(0, sentence.length() - 1);
if(isPangram(text) == true)
{
System.out.println("IT IS A PANGRAM");
}
else
{
System.out.println("IT IS NOT A PANGRAM");
}
displayWords(text);
}
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = sc.nextLine();
PangramWords obj = new PangramWords(s);
obj.displayResult();
}
}Equivalent Python Program:
# Read the text input and split or scan it according to the question requirement.
# Loops process each word/character and update counters or result strings.
# Display the final text result after sorting, checking or rearranging is complete.
sentence = input("Enter a sentence: ")
if len(sentence) == 0:
print("INVALID INPUT")
else:
last = sentence[len(sentence) - 1]
if last != '.' and last != '?' and last != '!':
print("INVALID INPUT")
else:
text = sentence[0:len(sentence) - 1]
upper = text.upper()
letters = [0] * 26
for i in range(len(upper)):
ch = upper[i]
if ch >= 'A' and ch <= 'Z':
pos = ord(ch) - ord('A')
letters[pos] = 1
pangram = True
for i in range(26):
if letters[i] == 0:
pangram = False
break
words = text.split()
longest = words[0]
shortest = words[0]
for i in range(1, len(words)):
if len(words[i]) > len(longest):
longest = words[i]
if len(words[i]) < len(shortest):
shortest = words[i]
if pangram:
print("IT IS A PANGRAM")
else:
print("IT IS NOT A PANGRAM")
print("LONGEST WORD:", longest)
print("SHORTEST WORD:", shortest)Output:
Leave a Reply
Your email address will not be published. Comments are reviewed before appearing publicly.