Iterate with two variables

1

I have the following code:

def hasPalin(string):
    begin = 0
    end = len(string)-1
    result = ""
    while(begin < len(string)/2):
        if (string[begin] == string[end]):
            result += string[begin]
        else:
            break
        begin += 1
        end -= 1
    return result

Would it be possible to turn this while into a for ? That is, iterate over 2 variables, one being an increment, and another a decrease.

I did not test, but I'm pretty sure it's possible to do this in java, where I increment one variable, while decrementing another.

    
asked by anonymous 09.08.2017 / 20:59

2 answers

2

Yes, it is possible to iterate with two variables in python with for . For this you can use the function zip which returns a tuple like this:

for var1, var2 in zip(colecao1, colecao2):

What in your case was something like:

tam = len(string)

for begin, end in zip(range(0,tam), range(tam-1,-1,-1)):

Where the first range constructs the increasing values and the second range constructs the decreasing values.

If the idea of the algorithm was to check a sub-palindrome, and taking advantage of its logic can do:

def hasPalin(string):
    result = ""
    tam = int(len(string)/2)

    #Primeiro range de 0 até metade e o segundo do fim até metade
    for begin, end in zip(range(0,tam), range(len(string)-1,tam-1,-1)): 
        if string[begin] == string[end]:
            result += string[begin]
        else:
            return result #devolver o subpalíndromo. É diferente logo pode parar aqui

    return string #se chegou aqui a frase é totalmente um palíndromo e devolve o original

print(hasPalin("casaca")) #""
print(hasPalin("osctso")) #"os"
print(hasPalin("abcddcba")) #"abcddcba"
    
09.08.2017 / 22:00
2

When I arrived with the zip, Isac had already replied, but I will try to make a contribution with a slightly more pythonic way for the function you want:

def haspalin(_str):
    p=''
    for i in range(len(_str)-1):
        if _str[i] != _str[::-1][i]:
            return p 
        else:
            p+=_str[i]
    return _str        

print(haspalin('atabcdefata'))
ata
print(haspalin('ataxxxxxxxxxata'))
ataxxxxxxxxxata
  

Edited, Explanation:

_str[::-1][i]: Invert the string, then an iteration is done in the original string by comparing through the id%% of the loop for each character of the original string with the character of the corresponding index in the inverted string, if they are equal, it is added to the variable i , when the first non matching character is found, the function is 'aborted', returning the variable p .

View running on repl.it.

    
09.08.2017 / 22:55