问题
Problem
Link to the problem: https://www.codewars.com/kata/52597aa56021e91c93000cb0/train/python
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
move_zeros([false,1,0,1,2,0,1,3,"a"]) # returns[false,1,1,2,1,3,"a",0,0]
My code:
def move_zeros(array):
list = []
list2 = []
for n in array:
if n is 0:
list2.append(n)
else:
list.append(n)
return list + list2
Sample Tests:
Test.describe("Basic tests")
Test.assert_equals(move_zeros([1,2,0,1,0,1,0,3,0,1]),[ 1, 2, 1, 1, 3, 1, 0, 0, 0, 0 ])
Test.assert_equals(move_zeros([9,0.0,0,9,1,2,0,1,0,1,0.0,3,0,1,9,0,0,0,0,9]),[9,9,1,2,1,1,3,1,9,9,0,0,0,0,0,0,0,0,0,0])
Test.assert_equals(move_zeros(["a",0,0,"b","c","d",0,1,0,1,0,3,0,1,9,0,0,0,0,9]),["a","b","c","d",1,1,3,1,9,9,0,0,0,0,0,0,0,0,0,0])
Test.assert_equals(move_zeros(["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9]),["a","b",None,"c","d",1,False,1,3,[],1,9,{},9,0,0,0,0,0,0,0,0,0,0])
Test.assert_equals(move_zeros([0,1,None,2,False,1,0]),[1,None,2,False,1,0,0])
Test.assert_equals(move_zeros(["a","b"]),["a","b"])
Test.assert_equals(move_zeros(["a"]),["a"])
Test.assert_equals(move_zeros([0,0]),[0,0])
Test.assert_equals(move_zeros([0]),[0])
Test.assert_equals(move_zeros([False]),[False])
Test.assert_equals(move_zeros([]),[])
My output:
- Teste Passed
- [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]
- Teste Passed
- Teste Passed
- Teste Passed
- Teste Passed
- Teste Passed
- Teste Passed
- Teste Passed
- Teste Passed
- Teste Passed
My Question:
I believe it fails because 0.0 is not 0. But I'm struggling to understand how can i write that. I'm begining coding so my code doesn't look pythonic but i guess that's something I must pratice
回答1:
Use:
n == 0 and n is not False
According to https://docs.python.org/3/library/stdtypes.html
There are three distinct numeric types: integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of integers
and
Objects of different types, except different numeric types, never compare equal
回答2:
Just use ==
instead of is
. 0 is 0.0
returns False
, but 0 == 0.0
returns True
.
回答3:
You can use if n is 0 or n == 0.0 and type(n) == float
. (or type(0.0)
instead of float
)
I dont know why if n is 0 or n is 0.0
doesn't work. If anyone does, please comment.
来源:https://stackoverflow.com/questions/61661462/moving-zeros-to-the-end-failing-the-test-in-codewars