Reputation: 3
I'm trying to solve a hackerrank problem in which I have to print the number of occurrences of a word in a list(in order). My code works fine but the problem is that in a few of the test cases my code didn't manage to execute within the time limits. I've tried a few things to make it a bit faster which I will get into in a moment. Here is my code:
ar = [input() for i in listinput]
tup = tuple(dict.fromkeys(ar))
print(len(tup))
for i in tup:
print(str(ar.count(i))+" ", end='')
I've tried to make the list remove elements that have already appeared like so:
ar = [input() for i in listinput]
tup = tuple(dict.fromkeys(ar))
print(len(tup))
for i in tup:
print(str(ar.count(i))+" ", end='')
ar.remove(i)
Which leads me to conclude that using count() might not have been that efficient for this. I'm still not sure though. Basically what do I need to change to make this code execute faster.
Upvotes: 0
Views: 70
Reputation: 101
Using Counter() from collections should be faster. Link to Python library - Collections. (I am not sure if you had to implement the counter for the hackerrank test or if you could just use a library)
Assuming the input of the following format.
ar = [1, 1, 1, 2, 3, 5, 5, 5, 9, 9, 9, 9, 9, 5] # or words
We just have to use the Counter function as,
import collections
ar = [1, 1, 1, 2, 3, 5, 5, 5, 9, 9, 9, 9, 9, 5]
print(collections.Counter(ar))
Output is a Counter object,
Counter({9: 5, 5: 4, 1: 3, 2: 1, 3: 1})
Also, pay attention to the order. You might have to run a loop over the original list and every time you encounter a new word, use the word as a key in the dictionary and set the value of that word from the counter dictionary. Hope this is faster.
Upvotes: 1