Iterating through set
Thomas Rachel
nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Thu Jul 17 09:22:56 EDT 2014
Am 15.07.2014 02:10 schrieb LJ:
> 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.
>
> Thanks in advance!
>
This sounds like you want to avoid processing of an item as soon as it
is removed.
Then I'd suggest the following:
add = set()
remove = set()
while myset or add:
for item in myset:
if item not in remove:
# process
myset -= remove
myset += add
remove.clear()
add.clear()
Adding happens via add.add(item), removing via remove.add(item).
If there is additionally the need to take care in which order to apply
add/remove, or if it can happen that item X is added and removed in the
same loop run, it gets a bit more complicated.
Then adding would be like
if item in remove:
remove.remove(item)
elif item not in myset and item not in add:
add.add(item)
and removing like
if item in add:
add.remove(item)
elif item in myset:
remove.add(item)
HTH,
Thomas
More information about the Python-list
mailing list