Calculate median of a matrix I am solving interview questions from here.


  Problem : Given a N cross M matrix in which each row is sorted, find the overall median of the matrix. Assume N*M is odd.
  
  Note: No extra memory is allowed.
  For example:

 Matrix=     [1, 3, 5]
             [2, 6, 9]
             [3, 6, 9]

  
  A = [1, 2, 3, 3, 5, 6, 6, 9, 9]
  Median is 5. So, output is 5.


This is my approach:

def find_median( A):
    """Returns the median value from given list"""
    for i in range(1,len(A)):
        A[0].extend(A[i])

    return (sorted(A[0])).pop(len(A[0])/2)


Test Cases:               

assert find_median([[1,3,5],[2,5,9],[3,6,11]]) == 5
assert find_median([[0,1,1],[2,6,10],[3,5,9]]) == 3
assert find_median([[1,3,4,12,14],[1,6,9,10,15],[0,1,3,3,4]]) == 4


I am able to solve the problem but I wanted to know is there a better approach to solve this problem?
Follow PEP8


A is a bad variable name, use say matrix.
You should remove the space in-front of the function argument.
You should put spaces after ,.
You don't need the () surrounding sorted.
You could add some space around your division.

You can use // rather than / to make your code Python 2 and Python 3 compatable.
You don't need to use pop, normal indexing will work too.




def find_median(matrix):
    """Returns the median value from given matrix"""
    for i in range(1, len(matrix)):
        matrix[0].extend(matrix[i])
    return sorted(matrix[0])[len(matrix[0]) // 2]




Your code doesn't work as the challenge asks, if you add print(matrix) before return you'll see:

[[1, 3, 5, 2, 6, 9, 3, 6, 9], [2, 6, 9], [3, 6, 9]]