CodeWars Kata Move zeros to end of list

133 views Asked by At

Hey guys so I've almost solved this kata but my code keeps failing this one test. Any ideas?

def move_zeros(array):
    n = len(array)
    count = 0
    
    for i in range(n):
        if array[i] is not 0:    
            if type(array[i]) != int or type(array[i]) != float:
                array[count] = array[i]
                count += 1
            else:
                array[count] = array[i]
                count += 1
            
    while count < n:
        array[count] = 0
        count += 1
    return array

This is the failed test:

[9, 0.0, 9, 1, 2, 1, 1, 0.0, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0] should equal [9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0].

I assume its that float value throwing it off so I try and account for it with the second if statement, but to no avail.

2

There are 2 answers

1
Exelian On

Don't use the is not when comparing numbers. This is not the intended usage. Instead use the == comparison operator.

is and is not or used to compare actual objects, not literals.

5
Ryan Schaefer On

Diving deeper into why this won't work because of use of is:

is checks that the objects literally refer to the same object. All numbers are objects in python but the int object for 0 is different from the float object for 0.0.

Under "the hood", these objects allow for equality between ints and floats by defining an appropriate __eq__ method which is ultimately what is used when you call 0 == 0.0.