Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving specific number (without sort) to the left of list

Tags:

python

list

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]
like image 759
NIMI Avatar asked Jan 31 '21 20:01

NIMI


3 Answers

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 0s. 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 0s from the list.

like image 159
Moinuddin Quadri Avatar answered Oct 19 '22 23:10

Moinuddin Quadri


output = []
for i in nums:
    if i == 0:
        output.insert(0, 0)
    else:
        output.append(i)
output
like image 20
locriacyber Avatar answered Oct 19 '22 23:10

locriacyber


sorted(nums, key=lambda i: i != 0)
# or
sorted(nums, key=bool)
like image 42
dukkee Avatar answered Oct 19 '22 23:10

dukkee