# 2 lines Python, 2 ways

• ``````def minMoves2(self, nums):
median = sorted(nums)[len(nums) / 2]
return sum(abs(num - median) for num in nums)

def minMoves2(self, nums):
nums.sort()
return sum(nums[~i] - nums[i] for i in range(len(nums) / 2))``````

• that second one is really elegant! <3

• what's the meaning of nuts[~i]? can it be used in c++? thanks

• @kupe The `~` operator is the same as in C++, so `0, 1, 2, ...` get turned into `-1, -2, -3, ...`. But C++ doesn't support negative indexing. In Python, index `-1` means the last element, index `-2` means the next-to-last element, etc.

• @StefanPochmann thx. Excellent.

• Nice one! Pretty much what I had in mind as well.

• `your code is gorgeous as always!`

• I think this problem should definitely be solved using numpy and vectorization. I don't understand why leetcode does not allow numpy.

• leetcode does not allow numpy

Huh? What do you mean? LeetCode does offer NumPy, doesn't it?

• 2 lines Python, 2 ways

I have the following code that runs well on my laptop but in leetcode it says "Line 52: Exception: Type <type 'numpy.float64'>: Not implementedâ€ś

import numpy as np
class Solution(object):
def minMoves2(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
a = np.array(nums)
m = np.median(a)
a = a - m
a = abs(a)
return np.sum(a)

Anyway, your mistake is that your return type is wrong. The specification says you must return an `int`. So just convert it. This gets accepted:

``````import numpy as np

class Solution(object):
def minMoves2(self, nums):
return int(sum(abs(nums - np.median(nums))))
``````

• @StefanPochmann thanks! By the way, why is it running so slow? I assumed vectorization is usually a magnitude faster than other methods.

• @seekerwu70 I tested a little, looks like importing the numpy module is responsible for the large time. (I tested by uselessly adding the import to my non-numpy solution, which made it a lot slower.)

• @StefanPochmann Thanks for your elegant solution. I just want to know what made you think about median? Initially I was thinking exactly same way and only difference was I was taking round(mean) which was obviously failing some test cases.

• @harshaneel Minimizing the total/average distance is just a prominent property of a median. For multi-dimensional cases you can even see it as the definition: https://en.wikipedia.org/wiki/Median#Spatial_median

• So brilliant~

• That second one is simply brilliant

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