Purify


#1



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


#2

And what is the problem? Please provide a short explanation, it's not easy to help if we don't know what is your problem.


You don't understand why this function does not work? Take a look at this code:

def example(l):
  for i in l:
    print i
    l.remove(i)
  return l

print example(['a', 'b', 'c', 'd'])

it will result in this output:

a
c
['b', 'd']

Why? Because when i = 'a' you remove this value from the list, but Python knows that this was value at index 0 and that is should now move to value at index 1. But because 'a' is no longer in the list Python will skip 'b' (which is now at index 0), and later 'd'.


To solve this problem you can create copy of the list and use it to iterate through values:

def example(l):
  copy = []
  for i in l:
    copy.append(i)
  for i in copy:
    print i
    l.remove(i)
  return l

print example(['a', 'b', 'c', 'd'])

And now the output is, as expected:

a
b
c
d
[]

#3

 > purify([1,2,3,4,5,6,7,8,9])
=> [2, 4, 6, 8]
 > purify([1,2,3,4,4,5,6,7,8,9])
=> [2, 4, 4, 6, 8]
 > purify([1,2,3,4,4,5,6,7,7,8,9])
=> [2, 4, 4, 6, 7, 8]

This illustrates what @factoradic is describing. Not logic at work, but placement in the list that may or may not fluke a correct result. In this example, the second 7 slid under the radar.


#4

hi can you take a look at my code please !

def purify(x):
x= [1,2,3]
for num in x:
if (num%2)!=0:
x.remove(num)
return x
print purify


#5

I have explained exactly the same problem in my post. You have to create copy of the x and use it to iterate (in the for loop).


#7

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