本文介绍了将零点移动到底:CodeWars中的测试失败了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题
问题链接: 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]
我的代码:
def move_zeros(array):
list = []
list2 = []
for n in array:
if n is 0:
list2.append(n)
else:
list.append(n)
return list + list2
样本测试:
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([]),[])
我的输出:
- Teste通过了
- [9,0.0,9,1,2,1,1,0.0,3,1,9,9,0,0,0,0,0,0,0,0]应该等于[ 9,9,1,2,1,1,1,3,1,9,9,0,0,0,0,0,0,0,0,0,0]
- Teste通过了
- Teste通过了
- Teste通过了
- Teste通过了
- Teste通过了
- Teste通过了
- Teste通过了
- Teste通过了
- Teste通过了
- 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
我的问题:
我相信它会失败,因为0.0不是0.但是我正在努力理解我该怎么写.我正在开始编码,因此我的代码看起来不像pythonic,但是我想那是我必须要实践的事情
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
推荐答案
使用:
n == 0 and n is not False
根据 https://docs.python.org/3/library/stdtypes .html
和
这篇关于将零点移动到底:CodeWars中的测试失败了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!