I want to just move the zero's to left and don't want to sort the list.
For example, if my list is like:
nums = [1, 10, 20, 0, 59, 63, 0, 8, 0]
Here's the output which I desire after moving all the Zero's to left:
output = [0, 0, 0, 1, 10, 20, 59, 63, 8]
Here's the code I tried:
class Solution:
def moveZeroes(self, nums):
c = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[i], nums[c] = nums[c], nums[i]
c += 1
return nums
print(Solution().moveZeroes(nums))
This code gives me output as:
[1, 10, 20, 59, 63, 8, 0, 0, 0]
But my desired output is:
[0, 0, 0, 1, 10, 20, 59, 63, 8]
You can use sorted()
with key as bool
to achieve this as:
>>> nums = [1, 10, 20, 0, 59, 63, 0, 8, 0]
>>> sorted(nums, key=bool)
[0, 0, 0, 1, 10, 20, 59, 63, 8]
It will work for 0
s. In order to make it more generic for any number, you can define key as lambda x: x!=left_num
:
>>> left_num = 0
>>> sorted(nums, key=lambda x: x!=left_num)
[0, 0, 0, 1, 10, 20, 59, 63, 8]
As an alternative, here's a less Pythonic (but efficient) version of it using list.count()
:
>>> nums = [1, 10, 20, 0, 59, 63, 0, 8, 0]
>>> left_num = 0
>>> [left_num]*nums.count(left_num) + [n for n in nums if n!=left_num]
[0, 0, 0, 1, 10, 20, 59, 63, 8]
Here I am finding the count of zeroes in the list (say n
), and assigning n
zeroes in the start of new list. To get the rest of the unsorted list, I am using list comprehension to filter out the 0
s from the list.
output = []
for i in nums:
if i == 0:
output.insert(0, 0)
else:
output.append(i)
output
sorted(nums, key=lambda i: i != 0)
# or
sorted(nums, key=bool)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With