简体   繁体   中英

Why do I still get “Terminated due to timeout error” even after using deque instead of list?

I have written the following code to output the number of distinct words from the input and also their number of occurrences for each distinct word according to their appearance in the input.

I used the list append and count method and got the desired output, but some of the test cases didn't execute due to timeout error.

n = int(input())
ar = []
for _ in range(n):
    ar.append(input().rstrip())

def wordOrder(n, ar):    
    w_list =[] #list contains the number of repition of words
    u_list =[] #list eliminates the duplicates while maintaining the same order
    for i in ar:
        if i not in u_list:
            u_list.append(i)
            w_list.append(ar.count(i))
       
    return w_list
    
result = wordOrder(n, ar)
print(len(result))
print(*result, sep=' ')

So, I tried using deque instead of list thinking it might be due to the time complexity issue of O(n) for the list append method. But I am getting the same error even after using deque.

My question is whether the problem is due to the time complexity issue or some other factors? Would be great if someone could explain what kind of techniques to be adapted to avoid timeout error.

Sample Input:

4
bcdef
abcdefg
bcde
bcdef

Sample Output:

3
2 1 1

This code works fine for me

from collections import Counter

a=[]

for i in range(int(input())):

      a.append(input())

x = Counter(a)

print(len(x.keys()))

print(*x.values())

Though just using Counter() luckily works in this problem, it is safe to use OrderedDict() so as to maintain the existing order of the input provided. Therefore, the below code should work fine in all similar situations and it didn't bring any "Timeout error" which is what I wanted.

from collections import Counter, OrderedDict

a=[]

for i in range(int(input())):

      a.append(input())

x = OrderedDict(Counter(a))

print(len(x.keys()))

print(*x.values())

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