+ 3
Guys it's Hackerrank problem say 'Word Order' my code passing 5 test cases but for remaining 3 tests it's showing timeout
2 Réponses
+ 2
Thanks Zuke
+ 1
Does this help?
from collections import Counter
n = int(input())
words = []
for i in range(n):
words.append(input())
counter = Counter(words)
print(len(counter))
print(*counter.values())
Also, no need to list() a set, you can just do len(set(...))
The reason your solution times out is because you're doing l.count(i), for each i in l; that means it's gonna go through n elements of l, then for each again traversing through l to get their count. That's n² operations. You're better off going through the list once holding the result in a dictionary.
counter = dict.fromkeys(l, 0)
for key in l:
counter[key] += 1