Record#
There were no new concepts to learn today, only coding exercises.
The task was to determine whether an English word is a palindrome, meaning it reads the same forwards and backwards. According to the prompt, we need to use the function string.reverse(), which is a string reversal function.
In the code, we also need to meet three requirements: recursion, string slicing, and looping.
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 was difficult. At first, I thought I could directly use string.reverse() to reverse the string, but later I found out that the string doesn't have this method, so I had to look at the correct answer.
Then, I spent quite a while trying to understand string[-1] and string[:-1]. I asked GPT-3 for help, but I didn't understand its explanation. GPT-4 explained it to me later and I 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, representing a 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))