-5
class Solution(object):
    def moveZeroes(self, nums):
        nums.sort(key =lambda x : 1 if x == 0 else 0)
        return nums

My function looks like above. I don't seem to understand how code key =lambda x : 1 if x == 0 else 0 works.

I also tried to change the lambda function to:

def getKey(item):
    if item == 0:
        return 1
    else:
        return 0

But don't seem to understand how key=1 or 0, affects the result.

NSP
  • 1,193
  • 4
  • 15
  • 26
Peter Tsung
  • 915
  • 2
  • 10
  • 20
  • https://wiki.python.org/moin/HowTo/Sorting#Key_Functions – DeepSpace Nov 27 '17 at 09:19
  • 1
    Sorting with a key means sorting using the value given by the key function as the indication of where to place the item. In this case, `0` is before `1`, so all the items that produce key `0` will be placed earlier than all the items that produce key `1`. – khelwood Nov 27 '17 at 09:19
  • think of the `key` as a "mapping" of your original data to something else (in this case `1`s and `0`s). These `1`s and `0`s are then sorted as you would imagine and then the mapping is reversed to reveal the initial objects but this time sorted. – Ma0 Nov 27 '17 at 09:19
  • @khelwood Thanks you guys, i have tried to write the answer below. – Peter Tsung Nov 27 '17 at 09:34
  • @Ev.Kounis Thanks you guy, i have tried to write the answer below. – Peter Tsung Nov 27 '17 at 09:34
  • Possible duplicate of [What is key=lambda](https://stackoverflow.com/questions/13669252/what-is-key-lambda) – khelwood Nov 27 '17 at 09:38

2 Answers2

1

Inspired by @khelwood and @Ev. Kounis, i tried to wrote the answer myself.

the lambda function could rewrite like below:

def getKey(item):
    if item == 0:
        return 1
    else:
        return 0

when i us a map function like :

a = [1, 2, 0, 2, 0]
print map(getKey, a)

It results [0, 0, 1, 0, 1]

And then the sort function will sort the original list based on the output above. Let's recall the moveZeroes function:

class Solution(object):
    def moveZeroes(self, nums):
        nums.sort(key =lambda x : 1 if x == 0 else 0)
        return nums

print Solution().moveZeroes([1, 2, 0, 2, 0])
output: [1, 2, 2, 0, 0]
Peter Tsung
  • 915
  • 2
  • 10
  • 20
1

Just to bring a little clarification. key is applied to your data before the element's are sorted. Typically you put things like len which is giving a usefull measure to compare the elements against each other.

However in this case it's exploiting that functionality, basically giving 0 the highest key value of 1 and the rest just get's a value 0 which brings all the 0s to the end of the list. That's why the list is actually not sorted after that operation, just the 0s stick at the end

nums.sort(key =lambda x : 1 if x == 0 else 0)
user1767754
  • 23,311
  • 18
  • 141
  • 164