Answer:
- n = input("Give your input: ")
-
- word_list = n.split(" ")
- count = int(word_list[0])
-
- word_dict = {}
- counter = 0
- for i in range(1, count):
- if(word_list[i] not in word_dict):
- word_dict[word_list[i]] = 1
- else:
- word_dict[word_list[i]] += 1
-
- 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}