54,945 views
1 vote
1 vote
Write a program that reads a list of words. Then, the program outputs those words and their frequencies. The input begins with an integer indicating the number of words that follow. Assume that the list will always contain less than 20 words. Ex: If the input is: 5 hey hi Mark hi mark the output is: hey 1 hi 2 Mark 1 hi 2 mark 1

User Colemik
by
3.1k points

2 Answers

7 votes
7 votes

Final answer:

To solve this problem, you can use a Python dictionary to store the words and their frequencies. Iterate through the words, update their frequencies in the dictionary, and then print the word-frequency pairs.

Step-by-step explanation:

To solve this problem, you can use a dictionary in Python to store the words and their frequencies. First, you'll read the integer indicating the number of words that follow. Then, using a for loop, you can iterate through the words and update their frequencies in the dictionary. Here's a code example:

num_words = int(input())
frequencies = {}
for _ in range(num_words):
word = input()
if word in frequencies:
frequencies[word] += 1
else:
frequencies[word] = 1
for word, frequency in frequencies.items():
print(word, frequency)
User UltraCommit
by
3.2k points
5 votes
5 votes

Sample Output

5 hey hi Mark hi mark

hey 1

hi 2

Mark 1

hi 2

mark 1

Explanation

#include <iostream>

#include <vector>

#include <string>

using namespace std;

int main() {

/* Type you code here. */

//Define a vector

//to store the words.

vector <string> words_list;

//Define a vector to store

//the frequencies of the words.

vector <int> frequency_list;

//Declare the

//required variables.

string curr_word;

int num_words;

//Read and store the total

//number of words to be read.

cin >> num_words;

//Run the loop to read

//and store the words

for(int i=0; i<num_words; i++)

{

//Read and store

//the current word.

cin >> curr_word;

//Push the current

//word into the vector.

words_list.push_back(curr_word);

}

//Run the loop to find the

//frequency of each word.

for(int i=0; i<num_words; i++)

{

//Read the word present at

//the i'th position in the vector.

curr_word = words_list.at(i);

int count = 0;

//Run the loop to find the

//frequency of the current word.

for(int j=0; j<num_words; j++)

{

if(words_list.at(j) == curr_word)

{

count++;

}

}

//Insert the frequency

//of the current word.

frequency_list.push_back(count);

}

//Run the loop to display

//the word and its frequency.

for(int i=0; i<num_words; i++)

{

cout << words_list.at(i)

<< " " << frequency_list.at(i)

<< endl;

}

//Return from the

//main() function.

return 0;

}

User Legionar
by
3.8k points