pythonstringpalindrome

Python palindrome program w/o string functions


I'm a beginner in Python. I've written palindrome programs without using string functions.

Question 1: Why does the 1st logic not give me the desired output? Correct me if I'm wrong.

Question 2: In the 2nd program if I skip i += 1 in if statement it should give me the correct result as the for loop automatically increments value of i. Rather it gives me correct output only if I include that statement or else not. What may be the reason for this?

Logic 1:

n = input("eNTER  STRING\n")
length = int(len(n))
n = str(n)

for i in range(0, int(length/2+1)):
   if n[i] != n[-i - 1]:
      break

if i < int(length/2 + 1):
   print("not")
else:
   print("yes")

Logic 2:

n = input("ENTER  STRING\n")
length = int(len(n))

for i in range(0, int(length/2 + 1)):
   if n[i] == n[-i - 1]:
      i += 1
   else:
      break

if i < (length / 2):
   print("not")
else:
   print("yes")

Thanks in advance..


Solution

  • In Logic 1, try if i<int(length/2): instead of if i<int((length/2+1)):

    In Logic 2, even removing i+=1 gives the correct result:

    if n[i] == n[-i-1]:
        pass
    else:
        break
    

    You can also use the following code for the same:

    def reverse(text):
        if len(text) <= 1:
            return text
        return reverse(text[1:]) + text[0]
    
    n = input("ENTER  STRING\n")
    if n==reverse(n):
        print ("It's a palindrome")
    else:
        print ("It's not a palindrome")