[Python-ideas] collections.Counter should implement fromkeys

Abe Dillon abedillon at gmail.com
Wed Jun 27 16:36:26 EDT 2018


Consider the following update function for conway's game of life:

from collections import Counter

def update(live: Set[Tuple[Integer, Integer]]):
    counts = Counter.fromkeys(live, 0) + Counter(itertools.chain(neighbors(*
cell) for cell in live))
    flip = {cell for cell, count in counts.items() 
            if (cell in live and not 1<count<4) 
            or (cell not in live and count==3)}
    live ^= flip

around = frozenset(filter(any, itertools.product(range(-1,2), range(-1,2))))
def neighbors(r: Integer, c: Integer):
    return (((r+dr)%height, (c+dc)%width) for dr, dc in around)

The problem is, Count.fromkeys isn't implemented. I propose that it work 
exactly as it does for dict, otherwise it's difficult to add items to a 
Counter when you want them to start off at zero or some other count.

The best solution I came up with is to, more confusingly, count live cells 
once extra and adjust the rules accordingly:

def update(live: Set[Tuple[Integer, Integer]]):
    counts = Counter(itertools.chain(live, *(neighbors(*cell) for cell in 
live)))
    flip = {cell for cell, count in counts.items() 
            if (cell in live and not 2<count<5) 
            or (cell not in live and count==3)}
    live ^= flip

around = frozenset(filter(any, itertools.product(range(-1,2), range(-1,2))))
def neighbors(r: Integer, c: Integer):
    return (((r+dr)%height, (c+dc)%width) for dr, dc in around)


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180627/749be38f/attachment-0001.html>


More information about the Python-ideas mailing list