I want to converting a list to string for an assignment. I can convert 1 row, however my teacher wants us to convert 3 separate rows to make a grid for the game of life. I've tried a bunch of different iterations of my code and the closest I've gotten is printing the top row.
I've added what my teacher wants each line to do so it should be more explainable
def gridToString( grid ):
# create an empty string
mystr = ' '
# for each row in the grid, convert that row
for row in grid:
mystr += int(input(row))
# for each cell in the row, convert the cell
for cell in row:
mystr += int(input(cell))
# add symbol to the string for this cell
# symbol + for cells that hold a zero
if cell == 0:
cell = '+'
# letter O for cells that are non-zero
elif cell == 1:
cell = 'O'
# add a newline to the string at the end of the grid row
print(mystr, '\n')
# return the string representation of the grid
return mystr
lifeGrid = [[1,1,1],
[0,0,0],
[0,0,1]]
# convert the grid to a string
gridStr = gridToString( lifeGrid )
# print the string!
print( gridStr )
print('')
There are several issues in your attempt:
The function should not call
input(), norprint(). The purpose of the function is to convert the matrix that is given as argument to a string and return that string. This operation does not involve any user input, nor output to the terminal. So remove allinput()andoutput()calls.The empty string is
'', not' '.print(mystr, '\n')does not altermystr. Do do what the comment above it says, you should domystr += '\n'Both
mystr += int(input(row))andmystr += int(input(cell))cannot work: the right hand side of these assignments must be strings, so callingint()(which returns an integer) is wrong.mystr += int(input(row))is doing nothing useful.mystrwill get the contents of the row in the loop that follows below this statement, so this statement should just be removed.mystr += int(input(cell))should instead bemystr += str(cell), but see next pointThe code that changes
cellis useless, as after that change there is nothing done with this new value:Moreover, if
cellis not 0, then it is expected to be 1, so no need to check that withelif cell == 1-- it is the only possibility left. So make this anelse.So do:
Or shorter, using
cellas an index:and this replaces the earlier assignment to
mystr.With those points corrected, you would get this:
Now it will work. Your question didn't explain whether the string should have a
\nat the very end. It might be only necessary between lines.Note that it is more pythonic to do it as follows:
Here I left out the final
\n