On the whole the function of your function is:
if length of x equals 5 , return True
else if last character of string equals first one return True,
else return False
This kind of condition else condition...else return False is best expressed with or statement which return False only if all conditions are False and returns value of first not-False element. Other choice is any function which does basically same with any sequence. Here test of those alternatives for all branches of original if statement:
def function(x):
if len(x) == 5: return True
else: return x[0] == x[-1]
def funcor(x):
return (len(x)==5) or (x[0] == x[-1])
def funcany(x):
return any((len(x)==5, x[0] == x[-1]))
def funcverbal(sequence):
## sequence[0] is the first element of zero based indexed sequence
## endswith is string specific function so sequence must be string
## if it's length is not 5
return len(sequence)==5 or sequence.endswith(sequence[0])
## function is normal data type in Python, so we can pass it in as variable
def test(func):
print('Testing %s function' % func)
for value in ('12345','annb','ansa','23424242',('1','2','1'), 123, '131'):
try:
print ("%r -> %r" % (value,func(value)))
except:
print ("Failed to call function with " + repr(value))
print(10 * '-'+'Finished testing '+str(func) + 10 * '-')
for thisfunction in (function, funcor, funcany, funcverbal):
test(thisfunction)
(function is hightlighted as reserved word in blue but it is mistake in highlight routine in this website)
In case of the isPalindrome function, the length condition is not arbitrary, but it is necessary to recognize the primitive cases to stop the recursion, in case of 'anna' the palindrome function does:
see if the length of 'anna' is less than 2 (1 or 0), no they are not
compare 'a' with 'a' , continue as they are same
drop out the compared first and last letter and call isPalindrome with 'nn'
see if the length of 'nn' is less than 2 (1 or 0), no they are not
compare 'n' with 'n', continue as they are same
drop out the compared first and last letter and call isPalindrome with ''
see if the length of '' is less than 2 (1 or 0), yes. Return True as we found palindrome.
Here is alternative shorte function of palindrome testing based on the fact that palindrome reversed is same as palindrome.
def isPalindrome(s):
return s==s[::-1]