Reputation: 17
This is a question from one exam. Lets say we have a function, def palindrome (s), and we call it. If it is a palindrome, the function should return True.
def palindrome(s):
...
palindrome("radar")
In order to check if it is a palindrome, i tried to reverse the string in order to see if it was the same. I used s.find(s[::-1])
.
The alternatives from the exam was:
return bool(s.find(s[::-1]))
return not(bool(s.find(s[::-1]
I don't understand the difference between these two alternatives, can someone explain?
Upvotes: 0
Views: 223
Reputation: 1048
The equality operator '==' returns True or False
def palindrome(s):
reverse_str = s[::-1]
return s == reverse_str
palindrome("radar")
True
The find() method finds the first occurrence of the specified value or returns -1 if the value is not found.
def palindrome(s):
reverse_str = s[::-1]
return s.find(reverse_str)
palindrome("radar")
0
Upvotes: 1
Reputation: 5121
return bool(s.find(s[::-1]))
This is just the same as your solution. The only difference is it gets casted to a boolean type.
The bool() method converts a value to Boolean (True or False) using the standard truth testing procedure.
return not(bool(s.find(s[::-1]))
Just the same as previous solution but the result gets flipped. Why flip it? When found the result will be 0, when not found the result will be -1. This results in False (0) and True(-1). So it's weird that when found it gives False and when not found it gives True. That's why it's flipped.
Upvotes: 0