简体   繁体   中英

Python, using dictionaries and sets to keep track of all occurences of a word

I am trying to solve this 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.

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.

I have implemented a solution like this,

# Enter your code here. Read input from STDIN. Print output to STDOUT

n  = int(input())

mySet = set()
myDict = {}

for i in range(n):
    inp = input()[:-1]
    if inp not in mySet:
        mySet.add(inp)
        myDict[inp] = 1
    else:
        myDict[inp] += 1

print(len(mySet))
# print(' '.join(list(map(str, myDict.values()))))
print(*myDict.values())

My strategy is as follows:

If the word is not in mySet , add it to the set and create a value-key pair on myDict with word as key and 1 as value.

If the word is in the set already, then increment the value of that word in the dictionary.

However, half of the test cases are successfull, but the rest are "Wrong Answer". So, I wonder, can anybody point out what do I miss to add to this code?

Your mistake is in inp = input()[:-1] . The [:-1] cuts off the word's last character. I guess you're trying to remove the newline character, but input() is already " stripping a trailing newline ". Demo:

>>> [input() for _ in range(2)]
foo
bar
['foo', 'bar']

Simpler solution, btw:

from collections import Counter

ctr = Counter(input() for _ in range(int(input())))
print(len(ctr))
print(*ctr.values())

And for fun a tricky version of that (also gets accepted):

from collections import Counter

ctr = Counter(map(input, [''] * int(input())))
print(len(ctr))
print(*ctr.values())

Another one:

from collections import Counter
import sys

next(sys.stdin)
ctr = Counter(map(str.strip, sys.stdin))
print(len(ctr))
print(*ctr.values())

This one reads the whole lines, so here the strings do include the newline character. That wouldn't matter if all lines had it, but no, HackerRank commits the cardinal sin of not ending the last line with a newline. So I strip them off every line. Sigh.

In the problem, you don't need to use the set property and the way you are using input ie input()[::-1] is wrong as it is reversing the input which you have entered, ie for the input abc it is storing it as cba .

now to solve problem, as OP has figured out to take unique item use set, and to get the frequency of each word use dictionary. but using set is costly operation and dictionary can be used to get the unique word as it store unique keys which can be used to get the unique elments, and to get the frequency use the same operation as you are doing.

instead of adding key, value in dictionary by dict[key]=value better to update the current dictionary with inbuild method ie dict1.update(dict2) where dict1 is orignal dictionary and dict2 is new dictionary with key and value , dict2={key:value} , by this way you will keep the order of the element in dict.

to get the len of unique word , len of dictionary work ie len(dic) and to get the frequency of each word values need to printed ie print(*dic.values())

n = int(input())
dic  = {}

for _ in range(n):
  w = input()
  if w in dic.keys():
    dic[w]+=1
  else:
    dic.update({w:1})

print(len(dic.keys()))
print(*dic.values())
n=int(input())
word_list=[]
for i in range(n):
    word_list.append(input())
    
New_word_list=[]
for element in word_list:
    if element in New_word_list:
        New_word_list=New_word_list    
    else:
        New_word_list.append(element)

print(len(New_word_list))
for element in New_word_list:
    print(word_list.count(element), end=" ")

Input:

10
cat
dog
dog
rabbit
cat
pig
horse
pig
pig
goat

Results:

6
2 2 1 3 1 1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM