gpt4 book ai didi

python - 将零移动到末尾 : Why does my Python Code fail the test in CodeWars?

转载 作者:行者123 更新时间:2023-12-05 07:09:31 25 4
gpt4 key购买 nike

问题

问题链接: https://www.codewars.com/kata/52597aa56021e91c93000cb0/train/python

编写一个算法,接受一个数组并将所有零移动到末尾,同时保留其他元素的顺序。

move_zeros([false,1,0,1,2,0,1,3,"a"]) # 返回[false,1,1,2,1,3,"a",0 ,0]

我的代码:

def move_zeros(array):
zero_count = array.count(0)
array1 = list(filter(lambda a: a != 0, array)) + [0 for i in range(zero_count)]
return array1

示例测试:

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([]),[])

运行后我的输出:

  • 测试通过

  • 测试通过

  • 测试通过

  • ['a', 'b', 无, 'c', 'd', 1, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 应该等于 ['a', 'b', None, 'c', 'd', 1, False, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

  • [1, None, 2, 1, 0, 0, 0] 应该等于 [1, None, 2, False, 1, 0, 0]

  • 测试通过

  • 测试通过

  • 测试通过

  • 测试通过

  • 测试通过

  • 测试通过

我的问题:

为什么我的答案没有通过 2 个测试?

最佳答案

在 python 中,与整数相比,值 TrueFalse 的行为等同于 10 .请参阅 The standard type hierarchynumbers.Integral 下的部分.这意味着在计算零时,False 也将被计算在内,并且在 lambda 中:

lambda a: a != 0

a != 0 的比较将过滤掉 0False。纠正此问题的一种方法是将计数修改为过滤器,并检查 a 不是 bool 值的两个 lambda:

def move_zeros(array):
zero_list = list(filter(lambda a: a == 0 and not isinstance(a, bool), array))
array1 = list(filter(lambda a: a != 0 or isinstance(a, bool), array)) + zero_list
return array1

关于python - 将零移动到末尾 : Why does my Python Code fail the test in CodeWars?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61521549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com