Issue with my code

Dave Angel davea at davea.name
Tue Feb 5 14:43:47 EST 2013


On 02/05/2013 02:20 PM, maiden129 wrote:
> On Tuesday, February 5, 2013 1:56:55 PM UTC-5, marduk wrote:
>> On Tue, Feb 5, 2013, at 01:38 PM, maiden129 wrote:
>>
<Snipping double-spaced googlegroups trash>
>
> when I removed "s.remove(i), it starts to repeat the number of occurrences too
>
> many times like this:
>
> 2 occurs 3 times.
> 2 occurs 3 times.
> 3 occurs 3 times.
> 3 occurs 3 times.
> 2 occurs 3 times.
> 2 occurs 3 times.
> 5 occurs 1 time.
> 3 occurs 3 times.
> 3 occurs 3 times.
> 4 occurs 1 time.
> 3 occurs 3 times.
> 3 occurs 3 times.
> 1 occurs 1 time.
> 2 occurs 3 times.
> 2 occurs 3 times.
>
> How can I stop this?
>

As MRAB pointed out, don't delete items from a list you're iterating 
over.  It can make the iterator go nuts.  He suggests the collections 
module.

But if you want to do it by hand, one approach is to reverse the two 
loops.  Iterate over the characters in CheckS list, examining the entire 
s list for each one and figuring out how many times the character occurs.

Another approach is to build a dict, or a defaultdict, to keep counts 
for each of the characters in CheckS.

-- 
DaveA



More information about the Python-list mailing list