ASKSAGE: Sage Q&A Forum - Individual question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Thu, 02 Jun 2011 06:47:42 -0500iterating over a combinatorial classhttp://ask.sagemath.org/question/8144/iterating-over-a-combinatorial-class/It is somewhat annoying that `len` and `next` don't do what you think with combinatorial classes. Is there any more Pythonic (e.g. list comprehension) way to do the following?
prof = [1,3,2,0,0,3]
L = []
P = Permutations(3)
Q = P.__iter__()
for j in range(P.cardinality()):
tp = Q.next()
for i in range(prof[j]):
L.append(tp)
Part of the issue is that I would really rather not use `Q`, since it is "used up" when I'm done. I really want something that is succinct, but I just could not find a way to do it.Thu, 02 Jun 2011 05:35:37 -0500http://ask.sagemath.org/question/8144/iterating-over-a-combinatorial-class/Answer by DSM for <p>It is somewhat annoying that <code>len</code> and <code>next</code> don't do what you think with combinatorial classes. Is there any more Pythonic (e.g. list comprehension) way to do the following? </p>
<pre><code>prof = [1,3,2,0,0,3]
L = []
P = Permutations(3)
Q = P.__iter__()
for j in range(P.cardinality()):
tp = Q.next()
for i in range(prof[j]):
L.append(tp)
</code></pre>
<p>Part of the issue is that I would really rather not use <code>Q</code>, since it is "used up" when I'm done. I really want something that is succinct, but I just could not find a way to do it.</p>
http://ask.sagemath.org/question/8144/iterating-over-a-combinatorial-class/?answer=12404#post-id-12404 sage: L2a = flatten([[perm]*count for perm, count in zip(Permutations(3), prof)])
sage: L2b = sum(([perm]*count for perm, count in zip(Permutations(3), prof)), [])
sage: L == L2a == L2b
True
functional 4tw!Thu, 02 Jun 2011 06:07:42 -0500http://ask.sagemath.org/question/8144/iterating-over-a-combinatorial-class/?answer=12404#post-id-12404Comment by kcrisman for <pre><code>sage: L2a = flatten([[perm]*count for perm, count in zip(Permutations(3), prof)])
sage: L2b = sum(([perm]*count for perm, count in zip(Permutations(3), prof)), [])
sage: L == L2a == L2b
True
</code></pre>
<p>functional 4tw!</p>
http://ask.sagemath.org/question/8144/iterating-over-a-combinatorial-class/?comment=21636#post-id-21636I see what my problem was - I used * with list(p) for each permutation, and tried to use list comprehension without that, but didn't consider not making a list in the first place with the comprehension.Thu, 02 Jun 2011 06:47:42 -0500http://ask.sagemath.org/question/8144/iterating-over-a-combinatorial-class/?comment=21636#post-id-21636