Word Order in Python - HackerRank solution

Solution for hackerRank problem Word order in python

Problem :

You are given n words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification.

Note: Each input line ends with a "\n" character.

Constraints:

1 <= n <= 105.

The sum of the lengths of all the words do not exceed 106.

All the words are composed of lowercase English letters only.

Input Format

The first line contains the integer, n .

The next n lines each contain a word.

Output Format

Output 2 lines.
On the first line, output the number of distinct words from the input.
On the second line, output the number of occurrences for each distinct word according to their appearance in the input.

Sample Input

4

bcdef

abcdefg

bcde

bcdef

Sample Output

3

2 1 1

Explanation

There are 3 distinct words. Here, "bcdef" appears twice in the input at the first and last positions. The other words appear once each. The order of the first appearances are "bcdef""abcdefg" and "bcde" which corresponds to the output.

Procedure

1. Start.

2. Get the number of words, n as input from user.

3. Get n number of words from user and store it in a list.

4. Create an empty dictionary, d.

5. Loop through each word in the list

=> if i is in dictionary.keys

     =>increment the value of the key

=> else

    => d[i] = 1

6. loop through key, values in the dictionary

=> print the values

7. End.

Code :

n = int(input())

l=[]

for i in range(n):

    s = str(input())

    l+=[s]

word = {}

for i in l:

    if i in word.keys():

        word[i] += 1

    if i not in word.keys():

        word[i] = 1

print(len(word))

count = []

for i,j in word.items():

    count += [j]

count = list(map(str, count))

print(" ".join(count))

        

Comments

Popular posts from this blog

Finding the percentage in python - HackerRank solution

HackerRank challenges with solutions (Rearrangement, Formula, Word sorting, Numbers, Sentence)

What's your name, Tuple - HackerRank solution in python