Median of medians


In [11]:
n = 5

def median(X):
    return sorted(X)[len(X) // 2]

def median_of_medians(X):
    if len(X) <= n:
        return median(X)
    
    number_of_groups = len(X) // n
    medians = []
    for i in range(number_of_groups):
        medians.append(median_of_medians(X[i * n:n * (i + 1)]))
        
    return median_of_medians(medians)

In [12]:
median_of_medians(list(range(1, 11)))


Out[12]:
8

In [14]:
median_of_medians(list(range(1, 101)))


Out[14]:
63

In [21]:
median([1,2,3,4,5])


Out[21]:
3

In [22]:
median([6,7,8,9])


Out[22]:
8

In [23]:
median([3, 8])


Out[23]:
8

In [24]:
import numpy as np

In [25]:
np.mode([1,1,-1])


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-25-e7db52396475> in <module>()
----> 1 np.mode([1,1,-1])

AttributeError: module 'numpy' has no attribute 'mode'

In [27]:
from collections import Counter

In [32]:
Counter([1,1,-1]).most_common(1)[0][0]


Out[32]:
1

In [34]:
2345 % 10


Out[34]:
5

In [35]:
2345 // 10


Out[35]:
234

In [36]:
def key(x, i):
    return (x // 10 ** i) % 10

In [39]:
key(123, 2)


Out[39]:
1

In [40]:
c = 1000

n = 10
n - 1 + n * (n + 1) / 2


Out[40]:
64.0

In [41]:
n ** 2


Out[41]:
100

In [52]:
a = [.75 ** i for i in range(100000)]
sum(a)


Out[52]:
3.9999999999999987

In [47]:



Out[47]:
3.7747459411621094

In [ ]: