I recently tried to submit my solution for one of codeforces problem. I successfully solved the question and tried various test cases and the code was working correctly in my local machine. The time constraint was 2 seconds in the problem. I tried to submit the solution but it said time limit exceed.
HERE IS THE CODE (My implementation)
def find(u):
if parent[u] == u:
return u
parent[u] = find(parent[u])
return parent[u]
n,m = map(int,input().split())
parent = [i for i in range(n+1)]
ans = [0 for i in range(n+1)]
for i in range(1,m+1):
grp = [int(i) for i in input().split()][1:]
if len(grp) == 0:
continue
x = find(grp[0])
for i in grp[1:]:
parent[find(i)] = x
for i in range(1,n+1):
ans[find(i)] += 1
ans = " ".join(map(str,[ans[find(u)] for u in range(1, n + 1)]))
print(ans)
Then I did some changes in the code and it was successfully submitted on codeforces.
SECOND IMPLEMENTATION:
from sys import stdin
from sys import stdout
def find(u):
if parent[u] == u:
return u
parent[u] = find(parent[u])
return parent[u]
n, m = map(int, stdin.readline().split())
parent = [i for i in range(n+1)]
ans = [0 for i in range(1+n)]
for i in range(1,m+1):
grp= [int(u) for u in stdin.readline().split()][1:]
if(len(grp)==0):
continue
x = find(grp[0])
for i in grp[1:]:
parent[find(i)] = x
for i in range(1,n+1):
ans[find(i)]+=1
pprintit = ' '.join(map(str, [ans[find(u)] for u in range(1, n + 1)]))
stdout.write('%s' % pprintit)
My Question is:
Is stdin faster than input() because just by changing the I/O methods I could submit the solution
I am using python 3.7.
Thank You in advance.