Search code examples
pythonstringreverse

Flipping a matrix-like string horizontally


The goal of this function is to flip a matrix-like string horizontally.

For example the string: '100010001' with 2 rows and three columns would look like:

1 0 0
0 1 0
0 0 1

but when flipped should look like:

0 0 1
0 1 0
1 0 0

So the function would return the following output: '001010100'

The caveat, I cannot use lists or arrays. only strings.

The current code I have written up, I believe, should work, however it is returning an empty string.

def flip_horizontal(image, rows, column):

   horizontal_image = ''
   for i in range(rows):

       #This should slice the image string, and map image(the last element in the 
       #column : to the first element of the column) onto horizontal_image.
       #this will repeat for the given amount of rows

       horizontal_image = horizontal_image + image[(i+1)*column-1:i*column]
    
   return horizontal_image

Again this returns an empty string. Any clue what the issue is?


Solution

  • The range function can be used to isolate your string into steps that represent rows. While iterating through the string you can use [::-1] to reverse each row to achieve the horizontal flip.

    string = '100010001'
    output = ''
    prev = 0
    
    # Iterate through string in steps of 3
    for i in range(3, len(string) + 1, 3):
    
      # Isolate and reverse row of string
      row = string[prev:i]
      row = row[::-1]
    
      output = output + row
      prev = i
    
    

    Input:

    '100
     010
     001'
    

    Output:

    '001
     010
     100'