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
question from:
https://stackoverflow.com/questions/65650364/why-do-i-still-get-terminated-due-to-timeout-error-even-after-using-deque-inst 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…