# Runtime error in Python's recursion

I have noticed that whenever I use recursion in Python, even though I get correct output for test cases, I get RE or WA after submission. I changed my code to C++ and used the EXACT SAME logic and it ran just fine. Is there any particular reason as to why this is so?

(I am thinking it might have something to do with recursion limit in python, and hence I changed the recursion limit with `sys.setrecursionlimit(n)`, but to no fruit.)

My code in Python:

``````import sys
sys.setrecursionlimit(100000)

def rundfs(v, visited, graph):
if v not in graph.keys():
return visited
for nv in graph[v]:
if visited[nv] == False:
visited[nv]=True
visited = rundfs(nv, visited, graph)
return visited

def find_disjoint_sets(visited, graph):
dsets = 0
for v in range(len(visited)):
if visited[v] == False:
visited[v] = True
visited = rundfs(v, visited, graph)
dsets+=1
# print visited
return dsets

t = int(raw_input())
while t>0:
flush = raw_input()
n = int(raw_input())
s = int(raw_input())
graph = {}
for i in range(s):
v1, v2 = map(int, raw_input().strip().split(' '))

if v1 in graph.keys():
graph[v1].append(v2)
else:
graph[v1] = [v2]

if v2 in graph.keys():
graph[v2].append(v1)
else:
graph[v2] = [v1]

visited = [False for i in range(n)]
print find_disjoint_sets(visited, graph)
t-=1
``````

Recursion is VERY expensive in python and JAVA. If recursion is deep, then prefer C++ as you get RE:NZEC in python and JAVA due to stack overflow.