要解决的问题:编写一个算法,该算法采用一个数组并将所有零移动到末尾,同时保留其他元素的顺序。
经过测试的解决方案:
if !((self.pageViewController.viewControllers?.first as? PageIndexable)?.pageIndex == self.selectedTabIndex) {
self.pageViewController.setViewControllers([viewController(At: self.selectedTabIndex)!], direction: direction, animated: true, completion: nil)
self.tabCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
该解决方案效果很好,但是当我将所有这些迁移到一个函数上时,我的测试失败了,我不确定为什么,因为该解决方案使用jupyter笔记本进行了100%的测试
解决方案已实现:
array = ["a",0,0,"b","c","d",0,1,0,1,0,3,0,1,9,0,0,0,0,9]
newlist=[]
number_of_zero=0
for i in array:
if i==0:
number_of_zero+=1
if i!=0:
newlist.append(i)
print(newlist)
for i in range(number_of_zero):
newlist.append(0)
print(newlist)
有人可以建议我将代码包装到函数中后为什么会失败吗?我的逻辑没有发现任何问题。
答案 0 :(得分:1)
def move_zeros(array):
newlist=[]
zerolist = []
for i in array:
# False == 0 will evaluate to True (but False should stay in place), ignore boolean types
# not isinstance(i, bool) means anything other than True or False
# True and False (like everything else) are objects in python
if not isinstance(i, bool):
# at this point, we can use ==, which will only evaluate to True if an int or float is zero
if i == 0:
# add the zero, but maintain the type (int or float)
zerolist.append(i)
# go to the next iteration
continue
# if the continue statement wasn't executed, everything else will be added here
newlist.append(i)
# append the zero list (with the same types) to the non-zero list
return newlist + zerolist
答案 1 :(得分:1)
这似乎是一个代码战问题,我记得前一段时间已经解决了。解决此问题的技巧是考虑1和0的“真实性”或True
和False
的“数量”。
我的解决方案是使用False
函数附加所有不等于0或bool值的所有值(以捕获isinstance()
值)
然后,您可以计算原始列表与“非零”列表的长度差异。然后求出该差异并将零附加到其上。
def move_zeros(array):
no_zeroes = [x for x in array if x != 0 or isinstance(x, bool)]
solution = no_zeroes + (len(array) - len(no_zeroes))*[0]
return solution
答案 2 :(得分:0)
对零进行剥离,然后通过计算长度差将它们一次性添加进去
arr = ["a",0,0,"b","c","d",0,1,0,1,0,3,0,1,9,0,0,0,0,9]
def move_zeros(array):
nz = [e for e in arr if e is not 0]
return nz+[0]*(len(arr)-len(nz))
print(move_zeros(arr))
产生
['a', 'b', 'c', 'd', 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
答案 3 :(得分:0)
简短
newlist = sorted(array, key=(lambda x: x is 0))
如果您不介意更改原始列表,可以这样做
array.sort(key=(lambda x: x is 0))
请注意,通常我们将使用==
而非is
测试是否相等,但是使用is
可以使我们将0
与False
区分开。这是基于CPython实现预先分配了从-5到256之间的整数这一事实。不幸的是,这意味着0 is 0
的行为是由实现定义的。不过,您仍然可以依靠它,因为在这方面,没有一个主要的Python实现与CPython不一样(Cython,PyPy,IronPython,Jython)。