Purify


#1



Purify


Error: Oops, try again. Your code looks a bit off--it threw a "invalid literal for int() with base 10: ']'" error. Check the Hint if you need help!


I have tried the code at PyCharm and it works just fine! I can't understand why codecademy framework doesn't accept this.


def purify(num):
    print "\nThe number input is: {} and has {}.".format(num, type(num)) # debugging
    lst = list(str(num))
    print "The number, now converted into a list is: {}, and its length is: {}\n".format(lst, len(lst)) # debugging
    even_list = []
    odd_list = []
    # The loop below is to check each individual digit if it's even or odd
    while len(lst) > 0:
        #print len(lst) # debugging
        x = lst[-1]
        x = int(x)
        if x % 2 == 0: #even number
            even_list.append(lst[-1])
            print "Even digit '{}' has been added to the list.".format(x)
            del lst[-1]
        elif x % 2 != 0: #odd number
            odd_list.append(lst[-1])
            print "Odd digit '{}' has been added to the list.".format(x)
            del lst[-1]
    print even_list
purify(123)


#2

def purify(number):
even=[]
for i in number:
if i%2==0:
even.append(i)

return even

print purify([1,2,3])

your code little bit longer, maybe this code will helpful for you.


#3

Thank you for replying 'oztrk.ozlem'!

I realise that my code is a bit chunky, and it's what differentiates an experienced coder I guess from an amateur one.
I was hoping to get some feedback from someone on the code instead of using someone else's just to pass the test though? I would appreciate any help! :slight_smile:

Best,
Alex


#4

Since you have converted the number to a list of strings, you need to make them back into numbers. You also need to remember that print and return are not the same. You need to return.

return ''.join(even_list)

To want to print something you can simply print the function call:

print purify(123)

Seems like you know that your code is a bit chunky. It's always a nice thing to go back to this exercise once you have learned more concepts :slight_smile: and find a way to improve it!

EDIT:
caught some more things.

x = lst[-1]
x = int(x)

can be shortened to

x = int(lst[-1])

And after you fix your print even_list part, when you do

print purify(222444)

output:
>> 444222

It seems like your going through the list backwards. To fix this, change all the -1s in lst[-1] to 0s => lst[0].


#5

Thank you so much 'datfatcat'!!

Yeah, I imagine once I take coding more seriously I will prioritise straight-to-the-point commands.
Thanks again!


#6

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