Search code examples
pythonautomationslicereverse

Slicing str into specifing chunks reversing said chunks and adding them up back together


I'm currently working on a challange where I need to divide strings by specifing number into chunks reverse them and than glue those reversed chunnks back together.

I came up with way to execute this, however I could't come up with way to automate this task.

def switch (n, txt):
    a = (txt [0:n] [::-1]) #here I devide and reverse the txt
    b = (txt [n:2*n] [::-1])
    c = (txt [2*n : 3*n] [::-1])
    d = (txt [3*n : 4*n] [::-1])
    e = (txt [4*n : 5*n] [::-1])
    f = (txt [5*n : 6*n] [::-1])
    g = (txt [6*n : 7*n] [::-1])
    h = (txt [7*n : 8*n] [::-1])````
    ch = (txt [8*n : 9*n] [::-1])
    i = (txt [9*n : 10*n] [::-1])
    j = (txt [10*n : 11*n] [::-1])
    k = (txt [11*n : 12*n] [::-1])
    l = (txt [12*n : 13*n] [::-1])
    m = (txt [13*n : 14*n] [::-1])

    
    return (a + b + c + d + e + f + g + h + ch + i + j + k + l + m ) #and here I glue it back together

print (switch (3, "Potatos are veges")) #The result should be "topotaa s ergevse"


Solution

  • You can loop using range(start,end,n) to jump n positions between two consecutive interations. In each iteration, you reverse a part of the string:

    def switch(n, txt):
        result = []
        for i in range(0,len(txt),n):
            result.append(txt[i:i+n].lower()[::-1])
        return ''.join(result)
    

    You can also write the loop as a one-liner:

    def switch(n, txt):
        return ''.join(txt[i:i+n].lower()[::-1] for i in range(0,len(txt),n))
    

    Both of these approaches have linear time complexity, because we carefully slice txt[i:i+n] by parts, and the glue it back together only once.