Purify


#1

Hi guys,
My code will not pass the assignment, but does print out only the even numbers.
Also I dont get why n%2 ==0 works. The == operates shows if two operands are completely equal right?
Any help is appreciated!

def purify(numbers):

for n in numbers:

  if n%2 == 0:
       return n
   else:
       numbers.remove(n)

return numbers

numbers = [1,2,3,4,5]
print purify(numbers)


#2

Oops, try again.
Your function crashed on [4, 5, 5, 4] as input because your function throws a "'int' object is not iterable" error.

is the error


#3

Hi,

Let's start by analyzing your code, to see what the problem could be:

You should know that you only put return, when you want to end the function at that point. So what you actually do here is, to return the next n, which is n%2 == 0, and stop after that. :confused:

What you are doing here is, to remove all odd numbers, by modifying the list itself.
You could do that, but if you read the instructions:

Do not directly modify the list you are given as input; instead, return a new list with only the even numbers. :frowning:

What you could do instead is, to define a new list, at the beginning of the function and only append the list, when the number is even, and do nothing when it's odd. At the end of the function you could return the whole list, and it should work :smiley:


#4

Fist of all, after write "def "name function", you have to create an empty "list" for result.
You must add result of iteration of list "numbers" into "list" that you have created.
You have a condition ! The function condition is " When some of number, in numbers, will split into two without residue. Add it to the result.
And finally - return you result !

However, you think correctly. I think you need to work with theory.

def purify(numbers):
    res=[]
    for i in numbers:
        if i % 2 ==0:
            res.append(i)
    return res

#5

Thanks for the help!


#6

You're welcome ^^
Hope you understood all of it :slightly_smiling:


#7

My code: :smiley:

def purify (numeros):
resultado = 0
numeros_pares = []
for i in numeros:
if i%2 == 0:
resultado -= i
numeros_pares.append(i)
return numeros_pares

Test

print purify([2,4,5,7])