In this problem, I take two strings from the user, the first string being s and the second string being t. If t is the reverse of s, I print "YES" else I print "NO".
Here is my code which gives me expected outputs:
s = input()
t = input()
if t == s[::-1]:
print("YES")
else:
print("NO")
But I found another approach that I am curious to understand, but the slicing part is making me confused. Here the code goes:
print("YNEOS"[input()!=input()[::-1]::2])
Trying to find a good explanation, so StackOverflow is what came to my mind before anything else.
CodePudding user response:
Let's first extract the parts of that expression that concern the input/output and the string reversal. We then get this solution:
s = input()
t = input()
trev = t[::-1]
result = "YNEOS"[s != trev::2]
print(result)
The focus of the question is on the expression "YNEOS"[s != trev::2]
Now we get to the "trick" that is performed here. The expression s != trev
can be either False
or True
. This boolean value becomes the first part in the slicing. You'd expect to have the start index of the slice at this position. But the boolean value will also work, as booleans are a subclass of integers, and False
is 0
and True
is 1. So the above expression evaluates to either:
"YNEOS"[0::2]
or
"YNEOS"[1::2]
The 2
serves as the step, and so "YNEOS"[0::2]
will take the characters at indices 0, 2 and 4 ("YES"
), while "YNEOS"[1::2]
takes the characters at indices 1 and 3 ("NO"
).
I hope this clarifies it.