11.6k views
2 votes
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. Each word will always contain less than 10 characters and no spaces. Ex: If the input is:

1 Answer

5 votes

Answer:

  1. n = input("Give your input: ")
  2. word_list = n.split(" ")
  3. count = int(word_list[0])
  4. word_dict = {}
  5. counter = 0
  6. for i in range(1, count):
  7. if(word_list[i] not in word_dict):
  8. word_dict[word_list[i]] = 1
  9. else:
  10. word_dict[word_list[i]] += 1
  11. print(word_dict)

Step-by-step explanation:

The solution code is written in Python 3.

Firstly, we prompt user to input a list of words started with an integer (e.g. 5 apple banana orange apple grape ) (Line 1).

Next, we use the split method to break the input into a list of individual words (Line 3). We extract the first element of the list and assign it to count variable (Line 4).

Create a word dictionary (Line 6) and a counter (Line 7). Create a for loop to traverse through the number from 1 to count (Line 9). If the word indexed by current i-value is not found in the word dictionary, create a new key in the dictionary using the current string and set frequency 1 to it (Line 9-10). Otherwise, use the current string as the key and increment its value by one (Line 11 - 12).

Print the word dictionary and we shall get {'apple': 2, 'banana': 1, 'orange': 1}

User Akhtarvahid
by
3.5k points