share sharing seems to be working
[p2pool.git] / p2pool / util / math.py
1 from __future__ import division
2
3 def median(x, use_float=True):
4     # there exist better algorithms...
5     y = sorted(x)
6     if not y:
7         raise ValueError("empty sequence!")
8     left = (len(y) - 1)//2
9     right = len(y)//2
10     sum = y[left] + y[right]
11     if use_float:
12         return sum/2
13     else:
14         return sum//2
15
16 def shuffled(x):
17     x = list(x)
18     random.shuffle(x)
19     return x
20
21 def shift_left(n, m):
22     # python: :(
23     if m >= 0:
24         return n << m
25     return n >> -m
26
27 def clip(x, (low, high)):
28     if x < low:
29         return low
30     elif x > high:
31         return high
32     else:
33         return x
34
35 def nth(i, n=0):
36     i = iter(i)
37     for _ in xrange(n):
38         i.next()
39     return i.next()