[Tutor] 2 problems in a small script

Aditya Lal aditya.n.lal at gmail.com
Fri Oct 12 08:25:40 CEST 2007


Hi Dick,

You are deleting from the SAME list that you are traversing. This results in
problems. You should just create a new list for the elements that are
well-formed.

astr = ...
lstA = ...

def wellFormed(word) :
  for ch in word :
     if ch not in astr :
        return False
  return True

final = []
for word in lstA :
  if wellFormed(word) :
     final.append(word)

You can also look at documentation for filter function (which is now handled
via list comprehension).

finalList = filter( wellFormed, lstA )

or

finalList = [ word for word in lstA if wellformed(word) ]

HTH
Aditya


On 10/12/07, Dick Moores <rdm at rcblue.com> wrote:
>
> Please see the code and it's output here:
> <http://www.rcblue.com/Python/buggy_For_Web.py>
>
>
> I'm attempting to eliminate the elements (strings) of lstA that are
> not well-formed in that they contain at least one character that is
> not in the string astr.
>
> Problems:
> 1) If lstA[n] is removed, lstA[n+1] is skipped--isn't examined at
> all, and remains in the final form of lstA whether well-formed or not.
>
> Using print statements is as far as my debugging skills go, so you
> can see of bunch of them in the code. I did try to use winpdb for the
> first time, but haven't figured it out yet. Ulipad now has it built
> in, so I'd like to learn to use it it..
>
> 2) I'm not able to get the "for char in wordWithCommas:" loop to stop
> examining a wordWithCommas after it's word has been removed. I've
> tried "continue" and "break" in various places to no avail.
>
> I'd appreciate some help.
>
> Thanks,
>
> Dick Moores
> Win XP, Python 2.5.1
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Aditya
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071012/f6db3998/attachment.htm 


More information about the Tutor mailing list