Today i faced a problem of successful hack attempt and these are my code. The code in C++ ran in time and gave T.L.E. in Python.Both code have same logic.
IN C++:
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n,arr[205];
cin>>n;
for(int i = 1; i <= n; i++) cin>>arr[i];
for(int i = 1; i <= n; i++) {
int x = arr[i];
int count = 1;
while (arr[x] != arr[i]){
count += 1;
x = arr[x];
}
cout<<count<<"\t";
}
cout<<endl;
}
}
IN PYTHON:
# cook your dish here
for _ in range(int(input())):
n = int(input())
p = [int(x) for x in input().split()]
ans = []
for i in p:
x = i
count = 1
while p[x-1] != i:
count += 1
x = p[x-1]
ans.append(count)
print(*ans)
use pypy3 instead of python and also add fast io
import sys
input=sys.stdin.readline