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
#coloumn : 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 is the issue?
CodePudding user response:
Use [::-1]
to reverse each row of the image.
def flip(im, w):
return ''.join(im[i:i w][::-1] for i in range(0, len(im), w))
>>> im = '100010001'
>>> flip(im, 3)
'001010100'
CodePudding user response:
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'