Boolean word palindroma in Python

0

Could someone give me an explanation about why this Palindromas words reoccurrence software does not work in Python?

def palindromo(cadena):

      num_letras = len(cadena) - 1       # te da el numero da caracteres -1
      for i in range(len(cadena) // 2):  # repite el loop 2 veces

        if cadena[i] != cadena[num_letras]:  # si la pimera y ultima letra != entoces la funcion es falsa(0!=3) 
                                             # si la segunda y la ultima letra != la funcion es falsa (1 != 3) 

          return False                       #si se cumple la condicion enntonces la funcion es falsa
        else:                                #de lo contrario:
          num_letras = num_letras - 1        #le restas 1 a num_letras(por que?) 

      return True                            #esto devuelve toda la funcion como verdadera


    palabra = "abba"                 
    if palindromo(palabra):
      print ("es palindromo")
    else:
      print ("no es palindromo")

This is the line (fourth line) that I do not fully understand:

 if cadena[i] != cadena[num_letras]:  

If I'm not mistaken, this tells me that it reviews 0! = 3 and 1! = 3 right? Then why does not it work ... * My specific question is if the only thing the if does is this * for example:

word = abba:

a! = a, b! = a

if the condition is met the word is not palindrome

    
asked by juan 04.11.2018 в 05:47
source

1 answer

0

I just tried your code and it works perfectly, it seems to me that you have to have it wrong, try copying the code that I write here, it is correctly indented:

def palindromo(cadena):

    num_letras = len(cadena) - 1       # te da el numero da caracteres -1
    for i in range(len(cadena) // 2):  # repite el loop 2 veces

        if cadena[i] != cadena[num_letras]:  # si la pimera y ultima letra != entoces la funcion es falsa(0!=3) 
                                             # si la segunda y la ultima letra != la funcion es falsa (1 != 3) 

            return False                       #si se cumple la condicion enntonces la funcion es falsa
        else:                                #de lo contrario:
            num_letras = num_letras - 1        #le restas 1 a num_letras(por que?) 

    return True                            #esto devuelve toda la funcion como verdadera

palabra = "anitalavalatina"
if palindromo(palabra):
    print ("es palindromo")
else:
    print ("no es palindromo")

With respect to the fourth line that you already mention your specific question, the if simply compares 2 things in that case 2 characters and question, they are different, if they are going to enter the return False which means that no it was a palindrome, if they are the same, decrease num_letras in 1 and continue the iteration of the cycle for .

    
answered by 04.11.2018 в 07:33