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


Groups > comp.lang.python > #74451

Re: Iterating through set

From Roy Smith <roy@panix.com>
Newsgroups comp.lang.python
Subject Re: Iterating through set
Date 2014-07-14 20:30 -0400
Organization PANIX Public Access Internet and UNIX, NYC
Message-ID <roy-482EE7.20305214072014@news.panix.com> (permalink)
References <d70b2c77-d3d5-42f8-9c8e-d25ef78b3963@googlegroups.com>

Show all headers | View raw


In article <d70b2c77-d3d5-42f8-9c8e-d25ef78b3963@googlegroups.com>,
 LJ <luisjosenovoa@gmail.com> wrote:

> Hi All.
> 
> I'm coding a Dynamic Programming algorithm to solve a network flow problem. 
> At some point in the algorithm I have to iterate through a set of nodes, 
> while adding and/or removing elements, until the set is empty. I know a 
> regular set() object does not work in a case like this, so I wonder if anyone 
> knows of an efficient pythonic way to handle this.


You've already figured out that you can't alter a set while you're 
iterating over it.  Which means you basically have two choices:

1) Build a new set while you're iterating over the first one, then 
delete the first set.  This might make sense if you expect there will be 
a large number of items (relative to the size of the original set) added 
or deleted.

2) Keep lists, of those items which need adding or deleting, and do them 
in bulk, after the iteration is completed.  Then, delete the lists.  
This makes sense if you expect the number of add/deletes will be small.

Either way is O(n) in the size of the set, so which you pick is a 
second-order optimization.

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


Thread

Iterating through set LJ <luisjosenovoa@gmail.com> - 2014-07-14 17:10 -0700
  Re: Iterating through set Roy Smith <roy@panix.com> - 2014-07-14 20:30 -0400
  Re: Iterating through set Chris Kaynor <ckaynor@zindagigames.com> - 2014-07-14 18:08 -0700
  Re: Iterating through set Thomas Rachel <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915@spamschutz.glglgl.de> - 2014-07-17 15:22 +0200

csiph-web