The problem is formulated as follows:
Write a recursive function that, given a string, checks if the string is formed by two halves equal to each other (i.e. s = s1 + s2, with s1 = s2), imposing the constraint that the equality operator == can only be applied to strings of length ≤1. If the length of the string is odd, return an error.
I wrote this code in Python 2.7 that is correct (it gives me the right answer every time) but does not enter that recursive loop at all. So can I omit that call here?
def recursiveHalfString(s):
#@param s: string
#@return bool
if (len(s))%2==0: #verify if the rest of the division by 2 = 0 (even number)
if len(s)<=1: # case in which I can use the == operator
if s[0]==s[1]:
return True
else:
return False
if len(s)>1:
if s[0:len(s)/2] != s[len(s)/2:len(s)]: # here I used != instead of ==
if s!=0:
return False
else:
return recursiveHalfString(s[0:(len(s)/2)-1]+s[(len(s)/2)+1:len(s)]) # broken call
return True
else:
return "Error: odd string"
The expected results are True if the string is like "abbaabba" or False when it's like anything else not similat to the pattern ("wordword")
==is off limits for string length >1, I would assume!=is also not allowed. It's essentiallynot ==.!=operator on strings longer than one character is pretty obviously against the spirit of the task - you could just donot (x != y)instead ofx == yanywhere you want to use==.if s!=0:is always true sincesis a string. So you can never end up in the else part.sis a string. It'll never equal0.0isn't a string.'abcabc'symmetrical by the constraints or do all the nested half strings themselves have to be symmetrical?