[Tutor] Code for checking whether an input string is a palindrome or not.

Kent Johnson kent37 at tds.net
Fri Oct 13 18:37:06 CEST 2006


Asrarahmed Kadri wrote:
> Yes, you are right; the code isnt working for 'abcdba';
> So what should I do to rectify it.

Try walking through the code by hand so you understand why it is 
failing. Then maybe you can figure out how to fix it. It's important to 
learn to find and fix errors yourself.

Kent

PS Please reply on the list.

>  
> Thanks,
> Asrar
> 
>  
> On 10/13/06, *Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>> wrote:
> 
>     Asrarahmed Kadri wrote:
>      >
>      > Hi,
>      >
>      > Here is a code that reports whether the string is a palindrome or
>     not. I
>      > have posted it to help people new to programming ( i am also a
>     newbie)
>      > to understand the logic and comment on it.
>      >
>      > Share and expand your knowledge as well as understanding...
>      >
>      > Happy scripting....
>      >
>      > Regards,
>      > Asrar
>      >
> 
>     Others have pointed out that there are easier ways to do this. I'll
>     comment on your code.
> 
>      > Code:
>      >
>      >
>      >
>      > string1 = raw_input("enter a string\n")
>      >
>      > str_len = len(string1)
>      >
>      >
>      >
>      > flag = 0
>      > j = str_len-1
>      >
>      > for i in range(0,(str_len-1)/2):
> 
>     I think there is an off-by-one error here; try 'abcdba' as a test.
> 
>      >  if string1[i] == string1[j]:
> 
>     Negative indices would work well here, you don't need j at all:
>       if string1[i] == string1[-i]:
> 
>     This would also be a good place to use for: / else: but that is a bit
>     more advanced.
> 
>     Kent
> 
>      >   j = j-1
>      >
>      >  else:
>      >   flag = 1
>      >   break
>      > if flag ==0:
>      >      print "The entered string is a PALINDROME"
>      > else:
>      >      print "The entered string is not a PALINDROME"
>      >
>      >
>      > --
>      > To HIM you shall return.
>      >
>      >
>      >
>     ------------------------------------------------------------------------
>      >
>      > _______________________________________________
>      > Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
>      > http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> 
> 
> -- 
> To HIM you shall return.




More information about the Tutor mailing list