Permutations with generators



Hey guys!
For the last couple of days, I've been fighting a war against
generators and they've beaten the crap out of me several times. What I
want to do is implement one that yields every possible permutation of
a given sequence (I had lists in mind, but I could swear that this
would work on strings too...if it worked at all).

Here's what I have so far:

def perm(seq):
"Reshuffles the elements of seq in every possible way"
if len(seq) == 1:
yield seq
else:
for p in perm(seq[1:]):
for i in range(len(seq)):
yield p.insert(i, seq[0])

Basically, I let the recursion reshuffle the elements of the
subsequence that starts from the second element of the original one,
and then I insert seq[0], the first element of the original sequence,
in every position of the shuffled sublist.

Here's what I get when I try to list the permutations of [1, 2, 3, 4]
(print list(perm([1, 2, 3, 4]))):

Traceback (most recent call last):
File "perm.py", line 15, in <module>
print list(perm([1, 2, 3, 4]))
File "perm.py", line 11, in perm
for p in perm(seq[1:]):
File "perm.py", line 13, in perm
yield p.insert(i, seq[0])
AttributeError: 'NoneType' object has no attribute 'insert'

Could somebody please explain to me why my p variable has no type at
all?
For every call to perm(seq), seq should always be of the same type as
the sequence that was used in the first call. Any ideas as to where
seq loses it's type?

Thanks in advance,
Pablo

.



Relevant Pages

  • Re: Permutations with generators
    ... generators and they've beaten the crap out of me several times. ... "Reshuffles the elements of seq in every possible way" ... yield p.insert ... File "perm.py", line 11, in perm ...
    (comp.lang.python)
  • Re: iterator idea
    ... # in the sequence, ... evens, seq = takewhile_exact ... iterators and eventually overflow the call stack. ... while (yield v): ...
    (comp.lang.python)
  • Re: Need help calculating queries & reports
    ... type, NOT a string type since string ... table2 based on the start/ stop sequence is not adding up correctly. ... seq# is a text field and time are numeric fields from table2. ...
    (microsoft.public.access.queries)
  • Re: if does not evaluate
    ... > function which uses yield in order to have the iteration abort ... Calling a "function containing a yield statement", aka a generator, returns ... StopIteration exception. ... sequence) ...
    (comp.lang.python)
  • Re: Sequence numbering
    ... Could you try using a column with a IDENTITY column. ... ClaimNumbers within the DB, but each -inbound- file will contain unique ... declare @Seq BigInt ... Select @Seq as Sequence ...
    (microsoft.public.biztalk.general)