I solved a problem using recursion in java as well as python with same logic. In python i got TLE while java solution got accepted. Can anyone explain me why it is so, because i am really confused whether to go with python or java. The question about comparing two string in divide and conquer fashion
Java Solution
static boolean cal(String a,String b)
{
if (a.length()!=b.length())
return false;
if(a.equals(b))return true;
if(a.length()==1)
{
if(a.equals(b))return true;
else return false;
}
if(a.length()%2!=0)return false;
int mid=a.length()/2;
String a1=a.substring(0,mid);
String a2=a.substring(mid);
String b1=b.substring(0,mid);
String b2=b.substring(mid);
return cal(a1,b1)&&cal(a2,b2)||cal(a2,b1)&&cal(a1,b2);
}
Python(3.7.2) solution
def cal(a, b):
if len(a) != len(b):
return False
if a == b:
return True
if len(a) == len(b) and len(a) == 1:
if a == b:
return True
else:
return False
if len(a) % 2 == 0:
mid = len(a) // 2
a1 = a[0:mid]
a2 = a[mid:]
b1 = b[0:mid]
b2 = b[mid:]
return (cal(a1, b1) and cal(a2, b2)) or (cal(a2, b1) and cal(a1, b2))
return False
Run your code with pypy3, don't use "Python 3" because it's slow.
Anyway python itself is very slow and doesn't fit for big complexity problems with low time limit, try to code with Java (And don't use Scanner class to read input because it's slow too, use bufferedReader or FastReader class from here )
And If you will code with c++ in the future, write this line in the begenning of you main
Or just use scanf and printf instead. Hope it helps!