How can I write code to find a palindrome in python without using string functions?

0 votes

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..

Jan 16 in Python by ariaholic
• 7,340 points
4,181 views

1 answer to this question.

0 votes

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")
answered Jan 16 by charlie_brown
• 7,720 points

Related Questions In Python

0 votes
1 answer

How can I write a program to add two numbers using functions in python?

def add(a,b):      return a + b #when i call ...READ MORE

answered May 20 in Python by Mohammad
• 3,170 points
535 views
+1 vote
1 answer
–1 vote
2 answers

How to find the size of a string in Python?

following way to find length of string  x ...READ MORE

answered Mar 29 in Python by rajesh
• 1,210 points
111 views
0 votes
1 answer

How can I define a multidimensional array in python using ctype?

Here's one quick-and-dirty method: >>> A = ((ctypes.c_float ...READ MORE

answered Oct 9, 2018 in Python by ariaholic
• 7,340 points
464 views
+4 votes
6 answers
0 votes
1 answer

Removing surrounding whitespace

Try the strip() function:  s = s.strip() If you ...READ MORE

answered May 4, 2018 in Python by Nietzsche's daemon
• 4,260 points
56 views
0 votes
1 answer

How to correctly return an a dictionary as an output in zappier code using python?

David here, from the Zapier Platform team. ...READ MORE

answered Dec 3, 2018 in Python by charlie_brown
• 7,720 points
146 views
+2 votes
3 answers

How can I play an audio file in the background using Python?

down voteacceptedFor windows: you could use  winsound.SND_ASYNC to play them ...READ MORE

answered Apr 3, 2018 in Python by charlie_brown
• 7,720 points
2,468 views