简体   繁体   中英

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.

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.

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 int s and float s by defining an appropriate __eq__ method which is ultimately what is used when you call 0 == 0.0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM