Python "purify" 12/15 - Practice Makes Perfect (none of my code will run)


#1

Hi,

I have a problem where if I write any code, no matter what the code is, it takes a long time to go through, then finally disallows the code. Pretty sure it isn’t a problem with the code because I made it so the code just wouldn’t work (so I removed half the code so it has like uncompleted statements etc), pretty weird. Never happened before.

Nevertheless, here is my code:

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

I’ve checked other solutions for this excercise and same result for everything. I have tried making a string and adding to it as well.

Thanks!


#2

In an ideal situation, numbers will be a list object, or at the very least, an iterable.

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

>>> purify(1234)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    purify(1234)
  File "<pyshell#1>", line 3, in purify
    for i in numbers:
TypeError: 'int' object is not iterable
>>> 

should raise an exception. A number is not iterable. This rules out your having passed a number else it would have failed right off the bat.

So the problem is somewhere else.

>>> purify("1234")
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    purify("1234")
  File "<pyshell#1>", line 4, in purify
    if i % 2 == 0:
TypeError: not all arguments converted during string formatting
>>> 

That’s an iterable. What happened?

i % 2

will raise an exception since a str character has no modulo. That rules out a string in the inputs, so also not a problem at this point.

You see we’re guessing at what the inputs were that raised this issue in the first place. Let’s find another way to make this function fail…

>>> purify({'1': 1, '2': 2, '3': 3, '4': 4})
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    purify({'1': 1, '2': 2, '3': 3, '4': 4})
  File "<pyshell#1>", line 4, in purify
    if i % 2 == 0:
TypeError: not all arguments converted during string formatting
>>> 

Same as before… Strings do not have a modulo. TypeError.

There is nothing stopping a tuple working in this function…

>>> purify((2,5,9,23,45,1,6,5,7,8,9,8,7,42))
[2, 6, 8, 8, 42]
>>> 

It should work with sets, no problem…

>>> from random import randint
>>> purify(set([randint(i, 10) for i in range(10)]))
[8, 10, 4, 6]
>>> 

We’re at a loss here for how this function failed on your account. Can you reproduce the scenario, perhaps? Then an explanation might come forth.

And just so we can pass a list…

>>> purify([randint(i, 10) for i in range(10)])
[2, 10, 6, 8, 8]
>>> 

#3

reset the exercise and now it works.

Thanks!


#4

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