funny generator behaviour

Aaron Brady castironpi at gmail.com
Thu Dec 4 16:05:53 CET 2008


On Dec 4, 7:00 am, Edvin Fuglebakk <Edvin.Fugleb... at ii.uib.no> wrote:
...
> def orderedCombinations(pool, k):
>     """
>     Generator yielding ordered selections of size k with repetition from
> pool.
>     """
>
>     if k == 1:
>         for m in pool:
>             yield [m]
>
>     if k > 1:
>
>         for m in pool:
>             for combo in orderedCombinations(pool, k-1):
>
>                 #insert and pop to avoid copying entire list
>                 combo.insert(0,m)
>                 yield combo
>                 combo.pop(0)

'combo.pop' is the problem.  When the caller saves the iteration
variable, the generator modifies it on the next call.

>>> a= []
>>> b= [0]
>>> a.append( b )
>>> a
[[0]]
>>> b.insert( 0, 1 )
>>> a
[[1, 0]]

If you want your output to have X lists, you need to create X lists.
Perhaps copy is not the most efficient, but you can't have one list
try do be X different lists when viewed from different angles.  Though
that would be cool.



More information about the Python-list mailing list