Arrange Sentences by Number of Words Program in Java and Python
Arrange sentences by word count with algorithm, explanation, Java solution and simple Python solution for ISC students.
Question:
Accept a paragraph of text consisting of sentences terminated by full stop, exclamation mark or question mark. Assume that there can be a maximum of 10 sentences. Arrange the sentences in increasing order of their number of words.
Algorithm:
Step 1: Start.
Step 2: Accept the paragraph as a string.
Step 3: Scan each character and build the current sentence until a terminating punctuation mark is found.
Step 4: Store each completed sentence in a sentence array and reset the temporary sentence string.
Step 5: For every stored sentence, use tokenization to count its words and store the count in a parallel array.
Step 6: Use nested loops to compare word counts of two sentences.
Step 7: If a later sentence has a smaller count, swap both the sentence strings and their count values.
Step 8: After sorting, display each sentence with its stored word count.
Step 9: Stop.
Explanation:
The program first separates the paragraph into individual sentences. A temporary string stores characters until a full stop, question mark or exclamation mark is found.
Two parallel arrays are used: one array stores the sentence text and the other stores the number of words in that sentence. The same index connects a sentence with its count.
Word counting is done by tokenizing each sentence. The token counter gives the number of words without manually counting spaces.
Sorting must swap both arrays together. If only the sentence is swapped and the counter is not, the displayed count would no longer belong to the correct sentence.
The nested sorting loop compares count values and moves sentences with fewer words toward the beginning. The final loop prints the sorted sentence and its word count.
The program treats each sentence as a separate unit, then counts the words in every sentence. This is different from sorting individual words. Sentence boundaries are detected using punctuation marks, while word counts are usually obtained by tokenizing or scanning spaces. Once every sentence has a count, sorting is performed using those counts as keys. The original sentence text must travel with its count during swapping, otherwise the count and sentence would become mismatched. This makes the program a useful example of sorting related pieces of data together.
Java Program:
/**
* The class sortParagraph inputs a paragraph and arranges the
* sentences in ascending order of their number of words
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/
import java.util.*;
class sortParagraph
{
// Function to count no. of words in every sentence
int countWords(String s)
{
StringTokenizer str = new StringTokenizer(s," .,?!");
int c = str.countTokens();
return c;
}
// Function to sort the sentences in ascending order of their no. of words
void sort(String w[], int p[])
{
int n = w.length, t1 = 0;
String t2 = "";
for(int i=0; i<n-1; i++)
{
for(int j=i+1; j<n; j++)
{
if(p[i]>p[j]) // for descending use p[i]<p[j]
{
t1 = p[i];
p[i] = p[j];
p[j] = t1;
t2 = w[i];
w[i] = w[j];
w[j] = t2;
}
}
}
printResult(w,p); // Calling function for printing the result
}
void printResult(String w[], int p[]) // Function to print the final result
{
int n = w.length;
for(int i=0; i<n; i++)
{
System.out.println(w[i]+"\t=\t"+p[i]);
}
}
public static void main(String args[])
{
sortParagraph ob = new sortParagraph();
Scanner sc = new Scanner(System.in);
System.out.print("Enter a paragraph : "); //Inputting a paragraph
String pg = sc.nextLine();
StringTokenizer str = new StringTokenizer(pg,".?!");
int count = str.countTokens(); //Counting no. of sentences in the paragraph
if(count > 10)
System.out.println("A maximum of 10 sentences are allowed in the paragraph");
else
{
String sent[] = new String[count]; //Array to store the sentences separately
int p[] = new int[count]; //Array to store no. of words of each sentence
for(int i=0; i<count; i++)
{
sent[i] = str.nextToken().trim(); // Saving sentences one by one in an array
p[i] = ob.countWords(sent[i]); // Saving no. of words of every sentence
}
ob.sort(sent,p);
}
}
}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.
paragraph = input("Enter a paragraph: ")
sentences = []
current = ""
for i in range(len(paragraph)):
ch = paragraph[i]
if ch == '.' or ch == '?' or ch == '!':
if current.strip() != "":
sentences.append(current.strip())
current = ""
else:
current = current + ch
counts = []
for i in range(len(sentences)):
words = sentences[i].split()
counts.append(len(words))
for i in range(len(sentences) - 1):
for j in range(i + 1, len(sentences)):
if counts[i] > counts[j]:
temp = counts[i]; counts[i] = counts[j]; counts[j] = temp
t = sentences[i]; sentences[i] = sentences[j]; sentences[j] = t
print("OUTPUT:")
for i in range(len(sentences)):
print(sentences[i] + " = " + str(counts[i]))Output:
Leave a Reply
Your email address will not be published. Comments are reviewed before appearing publicly.