A string is said to be palindrome if the reverse of the string is the same as the string. For example, “naman” is a palindrome, but “ankit” is not a palindrome.
Iterative Method:
- Run a loop from start to half of the length of the string.
- Check the first character to the last character of the string and second to second last one and so on…
- If any character mismatches, the string wouldn’t be a palindrome.
Input : ['naman','ankit','abcdcba','rahul','priya']
Output : [('naman', 'pallindrome'), ('ankit', 'non-pallindrome'), ('abcdcba', 'pallindrome'), ('rahul', 'non-pallindrome'), ('priya', 'non-pallindrome')]
Let’s see the Python code implementation:
# define a function to check string is
# palindrome or not
def check_palindrome(name , result):
c = 0
# run loop from 0 to len // 2
# len // 2 gives integer division
for j in range(0 , len(name) // 2):
# here we check character by charcter
if name[j] != name[(len(name) - 1) - j]:
c = 1
break
if c == 0:
# we use the append method of the list to insert
# the tuple at the last index of the list.
result.append((name , 'pallindrome'))
else:
result.append((name , 'non-pallindrome'))
# main code
if __name__ == "__main__" :
# given input list of strings
name_list = ['naman','ankit','abcdcba','rahul','priya']
# take empty list
result = []
# perform iteration in the list
for name in name_list:
# function call
# pass two arguments
check_palindrome(name , result)
# print the result after coming out of the loop
print(result)
Output:
[('naman', 'pallindrome'), ('ankit', 'non-pallindrome'), ('abcdcba', 'pallindrome'), ('rahul', 'non-pallindrome'), ('priya', 'non-pallindrome')]
Hellow this is my problem what is it code i hope you help me this problem