Purify


#1



Oops, try again. Your function fails on purify([4, 5, 5, 4]). It returns [4, 5, 4] when it should return [4, 4].

it supposes to kill all "5" ....

Replace this line with your code. 

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


#2

The remove is called while there is an iterator on the variable. Never do that as it would lead to inconsistencies in processing and data. May I recommend using pop() instead of remove?


#3

I suggest you do something like this.

result = []
def purify(x):
    for item in x:
        if item % 2 == 0:
            result.append(item)
    return result
print purify([4, 5, 5, 4])

The output for the above will be:

[4, 4]

#4

Thank you for your reply, and I'm still confused

Q : " for item in x: " this one is iteration, isn't it ?

Thanks for your advise.
But I still get the same outcome. " Oops, try again. Your function fails on purify([4, 5, 5, 4]). It returns [4, 5, 4] when it should return [4, 4]. "

def purify(x):
for item in x:
if item % 2 != 0:
x.pop( x.index(item) )
return x


#5

Thank you bro, it works !


#6

You're welcome.

Have fun coding! :slight_smile:


#7

def purify(x):
y = []
for item in x:
if item % 2 == 0:
y.append(item)
return y
print purify([1,2,3,4,5,6,7,8,9])

this wiil also work


#8

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