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))
2 lines Python, 2 ways

@kupe The
~
operator is the same as in C++, so0, 1, 2, ...
get turned into1, 2, 3, ...
. But C++ doesn't support negative indexing. In Python, index1
means the last element, index2
means the nexttolast element, etc.


@seekerwu70 said in 2 lines Python, 2 ways:
leetcode does not allow numpy
Huh? What do you mean? LeetCode does offer NumPy, doesn't it?

@StefanPochmann said in 2 lines Python, 2 ways:
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)

@seekerwu70 Please format your code properly.
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 nonnumpy 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 multidimensional cases you can even see it as the definition: https://en.wikipedia.org/wiki/Median#Spatial_median