0
def checker(string):
    collection=list(string)
    print(collection)
    while string.isalpha()==True:
        copy_collection=collection
        copy_collection.reverse()
        print(copy_collection)
        if copy_collection==collection:
                print("The string is a palindrome")
        else:
            print("The string is not a palindrome")
        break
    
name=input("Enter a string: ") 
checker(name)

I wanted to know if the string input by the user is a palindrome. Most of the solution suggests using [::-1]. Is it possible to do without using that because our lecturer has not taught us that and told us to not go outside the course to write the program.

if copy_collection==collection: I think the problem is here because it will print out "the string is a palindrome" even if it is not.

Thanks in advance.

Godang
  • 3
  • 3

2 Answers2

0

you can convert the list copy_collection into a string and then compare it against the original string. check it out:

def checker(string):
    collection=list(string)
    print(collection)
    while string.isalpha()==True:
        copy_collection=collection
        copy_collection.reverse()
        print(copy_collection)
        #Here the conversion to string
        copy_collection = ''.join(copy_collection)
        print(copy_collection)
        #compare to the vatiable "string"
        if copy_collection==string:
                print("The string is a palindrome")
        else:
            print("The string is not a palindrome")
        break
    
name=input("Enter a string: ") 
checker(name)

output:

Enter a string: somestring
['s', 'o', 'm', 'e', 's', 't', 'r', 'i', 'n', 'g']
['g', 'n', 'i', 'r', 't', 's', 'e', 'm', 'o', 's']
gnirtsemos
The string is not a palindrome

and now a palindrome:

Enter a string: somemos
['s', 'o', 'm', 'e', 'm', 'o', 's']
['s', 'o', 'm', 'e', 'm', 'o', 's']
somemos
The string is a palindrome
robbinc91
  • 548
  • 6
  • 14
0
def checker(string):
  collection=list(string)
  length = len(collection)
  isPalindrom = True
  for i in range(length):
     if collection[i] != collection[length-i-1]:
         isPalindrom = False
         break;

 if isPalindrom :
     print('String is Palindrome')
 else:
     print('String is not Palindrome')
    
name=input("Enter a string: ") 
checker(name)
Muhammad Atif Akram
  • 1,204
  • 1
  • 4
  • 12