Python: Check If a String is a Palindrome
Palindrome |
Objectives
- improving the student's skills in operating with strings;
- encouraging the student to look for non-obvious solutions.
Scenario
Do you know what a palindrome is?It's a word which look the same when read forward and backward. For example, "kayak" is a palindrome, while "loyal" is not.
Your task is to write a program which:
- asks the user for some text;
- checks whether the entered text is a palindrome, and prints result.
- assume that an empty string isn't a palindrome;
- treat upper- and lower-case letters as equal;
- spaces are not taken into account during the check - treat them as non-existent;
- there are more than a few correct solutions - try to find more than one.
Test data
Sample input:
Ten animals I slam in a net
Sample output:
It's a palindrome
Eleven animals I slam in a net
Sample output:
It's not a palindrome
Solution Code:
""" method 1 - detailed variables"""
text = input("Enter a text\n")
a_string = text.lower().replace(' ', '')
b_string = a_string[::-1]
while not text:
print("It's not a palindrome")
break
else:
if a_string == b_string:
print("It's a palindrome")
else:
print("It's not a palindrome")
""" method 2 - reversed() function"""
text = input("Enter a text\n")
text = text.lower().replace(" ", "")
rev_text = "".join(reversed(text))
while not text:
print("It's not a palindrome")
break
else:
if text.casefold() == rev_text.casefold():
print("It's a palindrome")
else:
print("It's not a palindrome")
""" methos 3 - for loop """
text = input("Enter a text\n")
def palindrome(string):
if text == "":
print("It's Not a palindrome")
string = string.lower().replace(' ', '')
reversed = ''
for i in range(len(string[::-1])):
reversed += string[::-1]
if string == reversed:
return "It's a palindrome"
else:
return "It's Not a palindrome"
print(palindrome(text))
methos 4 - while loop"""
text = input("Enter a text\n")
def palindrome(string):
while len(string.strip()) ==0:
return "It's Not a palindrome"
string = string.lower().replace(' ', '')
first, last = 0, len(string) - 1
while(first < last):
if(string[first] == string[last]):
first += 1
last -= 1
else:
return "It's Not a palindrome"
return "It's a palindrome"
print(palindrome(text))
Still, there are other solutions, and other ways to make the mentioned solutions better. Can you think about them?
See you in the comments 👀
Remember "Learn Less, Practice More"
0 Comments
Your opinion matters, your voice makes us proud and happy. Your words are our motivation.