python - Modifying a set while iterating over it -


i iterate on set while i'm deleting items it. there similar questions deleting 1 item @ time or lists, not work case.

the code follows; iterate on set zn , in end of iteration i'm removing few items (the ones belonging set temp). iteration still happening on "original" zn.

how can modify code change set zn while i'm iterating on it?

def cyclotomiccosets(q,n):     n=q^n-1     zn=set(range(n))     cosets=[]     in zn:         tmp=set([])         j in range(n):             tmp.add( i*(q^j) %n)         cosets.append(list(tmp))         zn=zn.difference(tmp) # <------------ not want     return(cosets) 

use while loop , .pop() values process set:

def cyclotomiccosets(q, n):     n = q ^ n - 1     zn = set(range(n))     cosets = []     while zn:         = zn.pop()         tmp = {i * (q ^ j) % n j in range(n)}         cosets.append(list(tmp))         zn -= tmp     return cosets 

note replaced inner for loop set comprehension make little faster , more compact. these introduced in python 2.7 , python 3, in earlier versions of python can use generator expression instead:

tmp = set(i * (q ^ j) % n j in range(n)) 

your original mistake replace zn rather update it:

zn=zn.difference(tmp) 

this did not alter original set using in for loop. rather, creating new set , point zn reference that.

however, cannot modify set while iterating on it, in-place difference not have worked; have use zn -= tmp or zn.difference_update(tmp) lead exceptions instead:

>>> zn = set(range(3)) >>> in zn: ...     zn -= set([2]) ...  traceback (most recent call last):   file "<stdin>", line 1, in <module> runtimeerror: set changed size during iteration 

the corrected code gives:

>>> cyclotomiccosets(3, 5) [[0], [0, 1, 2, 3], [0, 1, 4, 5], [0, 4, 5, 6]] 

alternatively, loop on range(n) instead, , keep set of values you've processed:

def cyclotomiccosets(q, n):     n = q ^ n - 1     cosets = []     seen = set()     in range(n):         if in seen: continue         tmp = {i * (q ^ j) % n j in range(n)}         cosets.append(list(tmp))         seen |= tmp     return cosets 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -