Python palindrome program not working

后端 未结 7 783
后悔当初
后悔当初 2021-01-26 12:49

I\'ve written a simple program in python which checks if the sentence is palindrome. But I can\'t figure out why isn\'t it working. The results is always False. Does anyone know

相关标签:
7条回答
  • 2021-01-26 13:43

    The best way to check a word is palindrome or not in Python is as below:

    var[::] == var[::-1]
    

    But, it is very important to understand that Python creates a new copy of string when you do var[::-1] Python internally don't know if the reverse will result in same string or not. So, it's coded in a way where it creates a new copy of it. So, when you try var[::1] is var[::-1] you will get FALSE.

    For example:

    var = "RADAR" var1 = var[::] var is var1 True var2 = var[0:6:1] var is var2 True var3 = var[::-1] var is var3 False var4 = var[-1:-6:-1] var is var4 False var1 'RADAR' var2 'RADAR' var3 'RADAR' var4 'RADAR'

    Here you can see when you move forward, it doesn't creates the copy of "RADAR", it uses the same reference. Because PY internally understand this operation will result in same string object. But, when you move in backward direction, the result can be different. For example, if I do the same operation for "Ethans", then the reverse of it will not be same. So, PY is not aware what will be the result of reversed string and it creates the new copy of it.

    Therefore, reversed string is returning false value with 'is' operator.

    One more interesting point to note here. See below example:

    var = "abc" var1 = "abc" var is var1 True var = "Ethans Baner Pune" var1 = "Ethans Baner Pune" var is var1 False

    We know string is immutable and follows Singleton DP, then why the second case is returning FALSE??

    This is because PY don't want to compromise on SPEED and PERFORMANCE. If you write a very long string and it's already present in memory, PY should refer to same string. But, finding that long string will take very long time and performance will be decreased. So, rather than referring to existing string, PY instead create a new one. We have also understood this for integers, where it only follow Singleton DP approach till limited value(256).

    Let's see one more example:

    var = "abcdefgh" var1 = "abcdefgh" var is var1 True var = "abcd efgh" var1 = "abcd efgh" var is var1 False

    0 讨论(0)
提交回复
热议问题