CS2016 CS2016 - 1 month ago 7
Python Question

Python variable length 2d arrays

today is my first day learning Python and have a question about 2-dimensional arrays. I need to create a 2 dimensional array but don't know the size of each of them. Is there something similar to the arraylist like in Java? Here's my code so you can see what I mean. It's for day 3 of last year's Advent of Code. So I guess a slight spoiler ahead if you haven't done it and want to see the way I'm thinking of setting it up.

f=open('directions.txt')
houses = [0][0]
rows = 0
column = 0
total = 0
for line in f:
for c in line:
if (str(c) == '^'):
rows += 1
houses[rows][column] += 1
elif (str(c) == '>'):
column += 1
houses[rows][coulumn] +=1
elif (str(c)=='<'):
column -= 1
houses[rows][column-=1] +=1
else:
rows -= 1
houses[rows][column] +=1


Thanks for any help.

Answer

I believe you want something like this

houses = dict()
rows = 0
column = 0
total = 0
for line in f:
    for c in line:
        houses.setdefault(rows,dict())
        houses[rows].setdefault(column, 0)
        if (str(c) == '^'):
            houses[rows][column] += 1
            rows += 1
        elif (str(c) == '>'):
            houses[rows][column] +=1
            column += 1
        elif (str(c)=='<'):
            houses[rows][column] +=1
            column -= 1
        else:
            houses[rows][column] +=1
            rows -= 1
Comments