Marcelino Velasquez
Marcelino Velasquez

Reputation: 87

CodeWars Kata Move zeros to end of list

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.

Upvotes: 0

Views: 171

Answers (2)

Ryan Schaefer
Ryan Schaefer

Reputation: 3120

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.

Upvotes: 1

Exelian
Exelian

Reputation: 5888

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.

Upvotes: 1

Related Questions