I need to check whether the string is a palindrome or not (without conditions and loops) and print '0' if the string is palindrome and '-1' if it is not a palindrome.
I am unsure what to do after reversing the string by string[::-1]
.
How to compare both strings to check palindrome without any loops or conditions?
(PS. I am not supposed to use any loops or conditions(including if,else))
As you asked for an explanation, I am writing an answer for you.
But be aware, except in very particular cases (such as golf code), I strongly discourage this practice.
If you want to not use if
else
, you could simply "trick it", using the fact that True
converts to 1
implicitly and False
to 0
in some cases.
You can use it in two ways :
Access elements in an array converts the bool
to int
, let's construct an array with the right element at the right index :
[-1,0][string==string[::-1]]
If string==string[::-1]
evaluates to True
(this is a palyndrome) then the second element of the array will be accessed. Otherwise, the first one.
Another solution, is to find a "function" which converts 1
to 0
, and 0
to -1
. The easy one is f(x) = x - 1
Which leads to :
(string == string[::-1]) - 1
Keep in mind, my comment was more a joke than a real solution, you should probably not use it in the real world !
PS: By "no conditions", I suspect it to mean "without comparing letters one by one", but I do think a
if string == string[::-1]:
print(0)
else:
print(-1)
is totally acceptable.