[Tutor] Basic Question
Mats Wichmann
mats at wichmann.us
Thu Sep 9 15:57:24 EDT 2021
On 9/9/21 12:50 AM, Osmaan Mysorewala via Tutor wrote:
> Hello,
>
> I'm trying to write a python program to create the game of life (Here's the
> wikipedia link to how the game of life works:
> https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). Right now it works
> only for the first iteration but then the new_arr becomes something
> completely wrong the second time I run the function. I think something is
> logically wrong with the neighbors function (other than how badly the
> if-statements are written). For reference, I'm eventually trying to put it
> on a display so that's why there's some display stuff in the comments
> there. Here's the code:
As you work through the jobs of collections full of mutable objects,
shallow and deep copies, etc - and this is definitely part of the Python
learning experience, and a trap not just for beginners at Python,
experienced heads get into trouble too - here are some other things you
might think about:
There's not really a good reason to use a pair of globals to store two
generations of the Conway "board". The use of globals is frowned upon
in many cases just because it's so easy to get into trouble keeping
track of what the state of things is. Instead, you could think of a
flow like this:
def main():
# do setup things - figure out boundaries, #generatrions, etc.
# create first generation datastructure
# loop for generations:
# board = advance(board)
# optionally call a board-printing routine
# (if you have a need to print, good idea to separate out the logic)
def advance(obj):
# calculate the next generation from obj
return newobj
def neighbors(point):
# do what's needed to figure out neighbors info
See - no globals!
You almost never want to write this if you don't actually _need_ the index:
for i in range(len(new_arr)):
print(new_arr[i])
because new_arr is iterable already, you sould prefer:
for point in new_arr:
print(point)
There *are* times when you want to work with the index.
As a design matter, you're storing a populated matrix, which is not
wrong, but since the states are completely binary, you could store
something sparse instead - like keep a list of the points that are "on",
only. You easily know that if a point is not in that list, then it's
off, so you didn't need to explicitly store the other value anywhere.
That's just a different design to a solution, you certainly don't have
to use it!
For the original poster, and other Python newcomers, it's not unheard of
that writing a program for Comway is a job interview question... and
you'll be asked to make it efficient, too, not just working. It's
probably worth leaving yourself a note to come back to this problem much
later, when you're a lot more experienced in Python, and seeing if you
would work a new solution differently given your new knowledge :) It's
good practice!
More information about the Tutor
mailing list