[Tutor] permutations?

Alan Gauld alan.gauld at btinternet.com
Thu Dec 2 09:38:07 CET 2010


"Alex Hall" <mehgcap at gmail.com> wrote

> Alright, I have it working. Now the problem is that it does not 
> throw
> out reversals. I tried to do this myself with a couple loops, but I
> get index errors. My total list of permutations is called l.
>
> for i in range(0, len(l)):
> r=l[i]; r.reverse()

You don''t need to specify the 0, its the default.
But you don't need to use indexing either.

for r,i in enumerate(l): r.reverse()

> for j in range(0, len(l)):
>  print l[j], r, i, j

Here you are comparing the reversed item to every item in the
list, including the ones you have already reversed, including the
item itself. So you will always find a match when i==j...

Using the in operator and list slicing would be easier

if r in l[i:]: l.remove(r)

but...

>  if r==l[j]: l.remove(r)

Its never a good idea to remove items from a list you are iterating
over, its like the old cartoon of the guy cutting down the tree branch
he is sitting on. If you must do it I'd use a while loop and manually
manage the indexing. Or operate on a copy of the list.

> longer exists. However, should the loop not re-evaluate len(l) each
> time,

No because the loop uses range() - a function in its own right and
range evaluates len() when first called and then return a sequence
to the loop based on that. The loop does not use len()

You can find an example of this type of thing at the end of the 
Branching
topic of my tutorial.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/


HTH,




More information about the Tutor mailing list