# Doing 12/15 without Recursion

#1
``````

def purify(numbers):
for i in numbers:
if (i%2) != 0:
numbers.remove(i)
i=0
return numbers

``````

The largest issue with iterating through a list and then removing an element is that you are at element X or index X, and once you remove it, you are now going to the next element, or index X+1. However, because you’ve removed that element, the element X+1 you want to be evaluating has been shifted back one space. Your program should automatically skip it:

[132]
on index 0 remove that number if it is odd.
[1] is removed
Current list is [32] index 0 == 3, index 1 == 2
Go to index 1 and remove that number if it is odd
2 is even
return list
returns [32]
Odd number is in there, fail

Now really what you should do in this case is access the list using pop and an index (range, len, etc) or be only returning the even numbers to a copy of the list of numbers, however I decided to solve it the lazy way.

Instead of doing all of that, I did the thing I just told you doesn’t work, however at the end of the loop, it resets i to 0.

This means that if you have a list of [12234457980], it removes one, then resets to 0, skips over the 2’s, removes the 3, resets, etc, until the entire list is even and it never triggers the if condition.

This obviously works pretty well for small lists. But if you start iterating on a list of 100 or more, you’re looking at 100! calculations as the worst case scenario 100!/2 as an estimated average, and some range in between the two as realistic.

But you know what? ■■■■ it.

#2

nice and informative, but do you also have a question?

#3

My question was “How do you do this without recursion?” I didn’t see any other questions like it, so I answered it myself. I figured I’d post it here so otherpeople could see.

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.