user6840964 user6840964 - 1 month ago 11
Python Question

How do I concat a string of chars together from a matrix in python?

The problem I'm working on is outputting a matrix in a clockwise inwards spiral. My code, right now, does this but the output is a little different than what is expected.

matrix = [
['a','d','g','e','t','c'],
['p','k','h','w','e','f'],
['m','j','y','h','b','n'],
['e','o','j','n','g','y']
]

def spiralPrint(mat):
top = 0
left = 0
right = len(mat[0])-1
bot = len(mat)-1

result = []

while(True):
#TRAVERSE ACROSS TOP ROW
for j in range(left, right+1, 1):
result.append(mat[top][j])

#INC TOP INDEX SO WE DON'T REPEAT
top += 1

#EXIT CONDITION
if top > bot or left > right:
break

#TRAVERSE RIGHTMOST COLUMN
for i in range(top, bot+1, 1):
result.append(mat[i][right])
right -= 1
if top > bot or left > right:
break

#TRAVERSE BOTTOM ROW
for k in range(right, left-1, -1):
result.append(mat[bot][k])
bot -=1

if top > bot or left > right:
break

#TRAVERSE LEFT COLUMN
for p in range(bot, top-1, -1):
result.append(mat[p][left])
if top > bot or left > right:
break
left += 1

return result

print(spiralPrint(matrix))


The output is supposed to look like: adgetcfnygnjoempk...

My output is: ['a', 'd', 'g', 'e', 't', 'c', 'f', 'n', 'y', 'g', 'n', 'j', 'o', 'e', 'm', 'p', 'k', 'h', 'w', 'e', 'b', 'h', 'y', 'j']

How do I output just the chars without the quotes and commas?

Answer

Instead of returning result, do

return ''.join(result)

As the name implies, it joins the contents of list result into one string. The empty string at the beginning means nothing will be put between successive elements. For more details, see the join section here.

You get a list for result rather than a string since you repeatedly append to it, which is a list method. You could concatenate and keep result a string, but using a list then joining together is actually the recommended way of adding characters to a string. So you hit the Pythonic way perhaps by accident.