0

Is it possible to use the 'if' statement under the 'return' statement in the recursive function call? If not, what are the other technics/ways to compensate for it? for example:

def is_palindrome(s, count=0):

   if count == int(len(s)/2):
       return True

   return is_palindrome(s,count+1) if s[count] == s[len(s)-(count+1)]

res = is_palindrome("rever")
print(res)
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Side-note: You should use `if count == len(s) // 2:`, not `if count == int(len(s)/2):`. The former directly performs integer-only floor division, the latter performs floating point division then uses the `int` constructor to truncate off the decimal component (slower, and for divisors other than powers of 2, or sufficiently huge integers, potentially inaccurate). – ShadowRanger Nov 24 '21 at 22:57
  • see this [related Q&A](https://stackoverflow.com/a/66568186/633183) – Mulan Nov 25 '21 at 05:36

1 Answers1

1

You can use conditional expression A if COND else B; this evaluates to A when COND is True, and B otherwise.

def is_palindrome(s, count=0):
    if count == len(s) // 2:
        return True
    return is_palindrome(s, count + 1) if s[count] == s[-(count + 1)] else False

print(is_palindrome('rever')) # True
print(is_palindrome('never')) # False

In this case, using and is simpler:

def is_palindrome(s, count=0):
    if count == len(s) // 2:
        return True
    return s[count] == s[-(count + 1)] and is_palindrome(s, count + 1)

If you are worried if you would make unnecessary calls for is_palindrome, it is not true; and is short-circuited, meaning that is_palindrome(...) is evaluated only when s[count] == s[-(count + 1)] is True.

j1-lee
  • 13,764
  • 3
  • 14
  • 26
  • 3
    Possible, but `return s[count] == s[-(count+1)] and is_palindrome(s, count+1)` would be clearer. – chepner Nov 24 '21 at 22:44
  • @chepner Yes, that was my first version of the answer, but I edited it because the OP seemed to want `if` somewhere. Perhaps it's better to provide that as well. – j1-lee Nov 24 '21 at 22:51
  • @chepner ... and I did so! Thanks for the suggestion. – j1-lee Nov 24 '21 at 23:02