Very simple python solutions

• Solution 1: traverse and swap last 0 and last non 0

``````class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
last0 = 0
for i in range(0,len(nums)):
if (nums[i]!=0):
nums[i],nums[last0] = nums[last0],nums[i]
last0+=1
``````

Solution 2 : one-liner from @toontong: use sort() with customized compare function

``````class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
nums.sort(cmp=lambda a,b: 0 if b else -1)``````

• This is simple but seems to have redundant operations.
Ex: nums = [1, 2, 3] then the line next to the last line will be always executed.

• yep, in your Ex, it will keep swap elements with itself. we can add one more "if (last! = i)" to prevent that, but I'm not sure which one will be quicker. maybe compiler will just ignore something like (a[i] = a[i])

• nums.sort(cmp= lambda a, b: -1 if b == 0 else 0)

• this one is cool

• Mine's pretty simple and very readable.

``````for n in range(len(nums)-1,-1,-1):

if(nums[n] == 0):

nums.append(nums.pop(n))``````

• looks simple but I think we should avoid use pop(n) because it's not efficient

• My python code is simple:

``````def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
for i in range(0,nums.count(0)):
nums.remove(0)
nums.append(0)``````

• may i ask how to understand this syntax?
nums.sort(cmp= lambda a, b: -1 if b == 0 else 0)

• ``````    for i in range(0,nums.count(0)):
nums.remove(0)
nums.append(0)
``````

Why is the range until nums.count(0)?

• ``````    for i in range(0,nums.count(0)):
nums.remove(0)
nums.append(0)
``````

Why is the range until nums.count(0)?

num.count(0) returns the total count of 0 in the list nums. For example is the list is like [1,2,3,0,5,0], num.count(0) returns 2(There are 2 '0' in the list.)

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.