Execution speed question

alex23 wuwei23 at gmail.com
Fri Jul 25 06:52:56 EDT 2008


On Jul 25, 7:57 pm, Suresh Pillai <stochash... at yahoo.ca> wrote:
> The nodes in my network may be ON or OFF.  The network starts off with
> all nodes in the OFF state.  I loop through the nodes.  For each node
> that is OFF, I consider some probability of it turning ON based on the
> states of its neighbours.  I MUST GO THROUGH ALL NODES BEFORE DECIDING
> WHICH ONES TO TURN ON.
>
> So my question is whether it is faster to
>
> 1. loop through a list of ALL nodes and check for OFF nodes using ifs

I'd recommend using 'filter' and list comprehensions.

>>> import random
>>> class Node:
...     def __init__(self):
...             self.on = False
...     def toggle(self):
...             self.on = random.choice([True, False])
...
>>> nodes = [Node() for i in range(0, 10000)]
>>> for node in nodes:
...     node.toggle()
...
>>> off_nodes = filter(lambda x: not x.on, nodes)
>>> len(off_nodes)
5050





More information about the Python-list mailing list