Python Grid

Soldato
Joined
30 Dec 2010
Posts
15,549
Location
Over here
Hi All,

I am doing a little coding challenge thing for work and I was wondering if anyone knew the answer to this.

I want to display a 12x12 grid which I have done, the issue is that it displays fine on Jupyter but not on Pycharm. I do not know what work are using to mark the code but I wanted to see if this is something I need to change in my code to make it universal or its a pycharm thing. Have to use standard python, no external libraries.

Python:
grid_size = 12

# Create a 2-dimensional list filled with square brackets
grid = [["[ ]" for x in range(grid_size)] for y in range(grid_size)]

# Display the grid using ASCII characters
for row in grid:
    print(" ".join(row))

The above displays in Jupyter fine i.e [] 12 across x 12 down

In Pycharm it shows like:
[]
[]
[]
[]

edit: Tried on an online python compiler too and it displayed per Pycharm.
 
Last edited:
seems to work fine on an online compiler for me, if that is the correct output anyway!


Are they all running the same Python version?
 
Last edited:
seems to work fine on an online compiler for me, if that is the correct output anyway!


Are they all running the same Python version?

Thank you for that. I have no idea why but it's just suddenly started displaying properly after I put the code inside a function. I really don't understand what has changed!

This is really going to annoy me. It wasn't working on online-python compiler either but I just copied it in again and now it is.



Python:
def draw_grid():
    grid_size = 5
     # Initially did this as two for loops but remembered about list comprehensions.
    grid = [["[ ]"] for row in range(grid_size) for col in range(grid_size)]
    for row in grid:
        print("".join(row))


draw_grid()

# This is displaying as one vertical line


Python:
def draw_grid():
    grid_size=12
#Createa2-dimensionallistfilledwithsquarebrackets

    grid=[["[]"for x in range(grid_size)]for y in range(grid_size)]

#DisplaythegridusingASCIIcharacters

    for row in grid:

        print("".join(row))

draw_grid()


#This is working correctly.



Edit: Oh I see it, I think it's a scope issue because I use row twice in the first example!
No that isn't it..

OK I figured it out but cannot work out why it displayed as it did, the issue was my comprehension.


Python:
grid=[["[]"for x in range(grid_size)]for y in range(grid_size)]

On the incorrect one I added a ']' after the last ", instead of after the first range call. I think this meant I was making a one dimensional list of 12*12.
Python:
grid = [["[ ]"] for row in range(grid_size) for col in range(grid_size)]
 
Last edited:
Back
Top Bottom