Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #107962

Code Opinion - Enumerate

Newsgroups comp.lang.python
Date 2016-05-01 20:17 -0700
Message-ID <0a2a0652-85c2-4283-a3c4-3ca8bc4e5481@googlegroups.com> (permalink)
Subject Code Opinion - Enumerate
From Sayth Renshaw <flebber.crue@gmail.com>

Show all headers | View raw


Looking at various Python implementations of Conway's game of life.

I came across one on rosetta using defaultdict.

http://rosettacode.org/wiki/Conway%27s_Game_of_Life#Python

Just looking for your opinion on style would you write it like this continually calling range or would you use enumerate instead, or neither (something far better) ?

import random
from collections import defaultdict
 
printdead, printlive = '-#'
maxgenerations = 3
cellcount = 3,3
celltable = defaultdict(int, {
 (1, 2): 1,
 (1, 3): 1,
 (0, 3): 1,
 } ) # Only need to populate with the keys leading to life
 
##
## Start States
##
# blinker
u = universe = defaultdict(int)
u[(1,0)], u[(1,1)], u[(1,2)] = 1,1,1
 
for i in range(maxgenerations):
    print "\nGeneration %3i:" % ( i, )
    for row in range(cellcount[1]):
        print "  ", ''.join(str(universe[(row,col)])
                            for col in range(cellcount[0])).replace(
                                '0', printdead).replace('1', printlive)
    nextgeneration = defaultdict(int)
    for row in range(cellcount[1]):
        for col in range(cellcount[0]):
            nextgeneration[(row,col)] = celltable[
                ( universe[(row,col)],
                  -universe[(row,col)] + sum(universe[(r,c)]
                                             for r in range(row-1,row+2)
                                             for c in range(col-1, col+2) )
                ) ]
    universe = nextgeneration

Just finished watching ned batchelders talk and wondering how far I should take his advice.

http://nedbatchelder.com/text/iter.html

Thanks

Sayth

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Code Opinion - Enumerate Sayth Renshaw <flebber.crue@gmail.com> - 2016-05-01 20:17 -0700
  Re: Code Opinion - Enumerate Sayth Renshaw <flebber.crue@gmail.com> - 2016-05-01 20:37 -0700
  Re: Code Opinion - Enumerate Stephen Hansen <me+python@ixokai.io> - 2016-05-01 22:24 -0700
    Re: Code Opinion - Enumerate Sayth Renshaw <flebber.crue@gmail.com> - 2016-05-01 23:28 -0700
  Re: Code Opinion - Enumerate Sayth Renshaw <flebber.crue@gmail.com> - 2016-05-02 00:52 -0700

csiph-web