Record#
Today there is no new knowledge to learn, only coding exercises.
The task is to determine whether an English word is a palindrome, meaning it reads the same forwards and backwards. According to the prompt, the function we need to use is string.reverse(), which is a string reversal function.
In the code, we also need to meet three requirements: recursion, string slicing, and loops.
The basic logic of the code is as follows:
- User inputs a word.
- Check if the word is a palindrome.
- Print "yes" or "no".
Today's task is difficult. At first, I thought I could directly use string.reverse() to reverse the string, but later I found out that the string does not have this method, so I had to look at the correct answer.
Then, I spent a long time trying to understand string[-1] and string[:-1]. I asked GPT-3 for help, but I didn't understand. After GPT-4 explained it to me, I finally understood. string[-1] can be understood as the index of the string, representing the last character in the string. And string[:-1] is the usage of string slicing, indicating the range of values, from 0 to the second-to-last character.
CODE#
def radar(vstr):
if len(vstr) <= 1:
return True
elif vstr[0] != vstr[-1]:
return False
return radar(vstr[1:-1])
while True:
vstr = input("Input > ")
print(radar(vstr))
Translation: