In: Computer Science
Python please
Write a function that takes a string as an argument checks whether it is a palindrome. A palindrome is a word that is the same spelt forwards or backwards. Use similar naming style e.g. name_pal. E.g. If we call the function as abc_pal(‘jason’) we should get FALSE and if we call it a abc_pal(‘pop’) we should get TRUE.
Hint: define your function as abc_pal(str). This indicates that string will be passed. Next create two empty lists L1=[] and L2=[] . Also create counter and set it to zero (e.g. i = 0). Now use a while loop e.g. while i < len(str) and use the append method to fill both empty lists i.e. List1.append(str[i]] and for list2 you need to reverse the order of filling i.e. L2 will be filled from the last letter to the first letter of the argument string. Lastly check if L1 is equal to L2 if the string is an anagram, simply use return L1==L2 this will return TRUE or FALSE as the case may be.
Source Code:
Output:
Code in text format (See above image of code for indentation):
#function definition
def abc_pal(str):
#two lists declaration
L1=[]
L2=[]
#counter variable
i=0
#using while append to lists
while(i<len(str)):
L1.append(str[i])
#append in reverse
L2.append(str[-i-1])
i+=1
#if both are equal return true otherwise false
return L1==L2
#read a string from user
name_pal=input("Enter a string: ")
#function call and print return value
print(abc_pal(name_pal))