Automate the Boring Stuff With Python, Chapter 4 Exercise

I have another simple solution, very similar to other solutions using only for loops. But one thing I seem to did different is that I used two augmented operators, one inside the inside-loop, one outside of it. I thought it would be useful after figuring out what we are asked for.

print(grid[0][0],
      grid[1][0],
      grid[2][0],
      grid[3][0],
      grid[4][0],
      grid[5][0],
      grid[6][0],
      grid[7][0],
      grid[8][0])

Output of Print Statement:

. . O O . O O . .

As you can see, it's the first line of the heart grid. We need to count from 0 to len(grid[0]), -that's the number of items in the first list, you can just type 6 as well. So, all I needed is two operators counting inside each other. The empty print statement is for line-breaks. If we don't use it, it prints out either all characters on the same line, or each character on each line.

Solution:

def printer(grid):
    for m in range(len(grid[0])):
        print()
        for n in range(len(grid)):
            print (grid[n][m],end="")
            n+=1        
    m+=1

Output:

..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....

I'm a newbie too - Using only what the book had covered, and keeping in mind the loop within a loop hint, this is my answer:

for j in range(len(grid[0])):
    for i in range(len(grid)):
        print(grid[i][j],end='')
    print('')

>>> print('\n'.join(map(''.join, zip(*grid))))
..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....

The zip(*grid) effectively transposes the matrix (flip it on the main diagonal), then each row is joined into one string, then the rows are joined with newlines so the whole thing can be printed at once.

Tags:

Python

List