Emily Stapler
Emily Stapler

Reputation: 13

Printing a full Matrix with coordinates python 3

import random
grid = []
n=m=5
NG = [random.randint(0,n-1) for x in range(n)]
for i in range(5):
        grid.append((i,NG[i]))
Matrix = {(x,y):"-" for x in range(n) for y in range(m)}
point1 = (1, 2)
for i in range(len(grid)):
    Matrix[grid[i]] = "Q"
for i in range(0, len(grid)):
      for j in range(i, len(grid)):
            print(Matrix[(i,j)], end=' ')
      print()

output

Q - - - - 
- - Q - 
- - - 
- Q 
- 

I need everything to be filled in therefore if it is a 5x5 matrix all 25 spaces are occupied. If the coordinate is in Matrix then it gets a "Q" else it gets a "-"

Upvotes: 0

Views: 326

Answers (2)

Gerges
Gerges

Reputation: 6499

You can also do it like this:

dashes = [['Q' if (j, i) in grid else '-' for  i in range(5)] for j in range(5)]

print('\n'.join(''.join(dash) for dash in dashes))

---Q-
-Q---
Q----
--Q--
Q----

Upvotes: 0

anurag0510
anurag0510

Reputation: 763

The issue is with your j loop :

for j in range(i, len(grid)):

as i increases it will decrease the row by one every time. As suggested by Lafexlos, you should use this instead to get the desired output :

range(len(grid))

which will keep your row size in tacked.

Upvotes: 1

Related Questions