0

I have been writing a simple version of Conway's Life simulation in python.

First I initialized a two dimensional array using the below code (which I probably learned on this site)

def makearray():
    for i in range(n):
        a.append(['x'] * m)

...and I access the cells in that array by storing, or checking the value of, a[2][5] or what have you.

That has worked nicely. But now I realize I need to make a second array, identical to the first, which will store the results of the evaluation that I do on the first array.

I know that I could just make a second array by repeating the exact same code but instead call the second array b instead of a. BUT, it would be a cooler, cleaner way process things if I simply made this into a 3-dimensional array, and the new dimension that I introduce would only be two units "wide" ... it would just have 0 and 1.

So, echoing the above, I'd like the end result to have my array so that I could check the value of a[1][2][5] ... or a[0][2][5].

But, can you give me tips on how I would do the initialization of that array? similar to the initializing loop I pasted above... but with the extra level? :)

Giant thanks!

2
  • 2
    Have you considered using numpy? First I was reluctant to use another library as a beginner, but it is really comfortable to manipulate arrays with numpy. I am happy that I put the effort into it. Commented Jan 13, 2018 at 12:56
  • in the future, and for any big project, I would probably do just that. but for this thing, I'm trying to pride myself on making a lean little program, so I'd rather keep dependencies out of it... but I appreciate that comment... I do recall that one can do arrays in a more normal feeling way using libraries Commented Jan 13, 2018 at 13:43

1 Answer 1

1

Array containing two matrices of size n

def makematrix(n):
    return [['x'] * n for i in range(n)]

threeD = [makematrix(5), makematrix(5)]

Array containing m matrices of size n

def makematrix(n):
    return [['x'] * n for i in range(n)]

def makearray(m, n):
    return [makematrix(n) for i in range(m)]

threeD = makearray(4, 5)

Array containing two arrays of increasing size

def makearray(n):
    return [['x'] * i for i in range(n)]

threeD = [makearray(5), makearray(5)]
Sign up to request clarification or add additional context in comments.

3 Comments

Have you actually looked at the output of your function?
yeah its what is being asked, he didnt ask for a matrix just arrays
after a little playing, your second one seems to be doing the trick. thanks. I wish I could look at a list comprehension ... in this kind of tangled context... and see it come to life in my head.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.