-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
78 lines (70 loc) · 1.92 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def bytes2human(n, format="{value}{symbol}"):
"""
>>> bytes2human(10000)
'9K'
>>> bytes2human(100001221)
'95M'
"""
symbols = ('B','K','M','G','T','P','E','Z','Y')
prefix = {}
for i, s in enumerate(symbols[1:]):
prefix[s] = 1 << (i+1)*10
for symbol in reversed(symbols[1:]):
if n >= prefix[symbol]:
value = float(n) / prefix[symbol]
return format.format(value=str(value)[:4], symbol=symbol) #locals()
return format.format(symbol=symbols[0], value=n)
def simp(L):
O = [ [] ]
for i in range(len(L)):
if i+1 in range(len(L)) and L[i]+1 == L[i+1]:
O[-1].append(L[i])
else:
O[-1].append(L[i])
O.append([])
del O[-1] # always empty
return O
def simp(L):
"""
>>> simp([1,2,3, 7,8,9, 42])
[[1,2,3], [7,8,9], [42]]
"""
from itertools import zip_longest
O = [ [] ]
for cur, next in zip_longest(L, L[1:], fillvalue=object()):
if cur+1 == next:
O[-1].append(cur)
else:
O[-1].append(cur)
O.append([])
del O[-1] # always empty
return O
def to_interv(Ll):
from copy import deepcopy
Ll = deepcopy(Ll)
for l in Ll:
if len(l) > 2:
del l[1:-1]
return Ll
def natural_exp_format(x):
if x < 0:
return '-' + natural_exp_format(-x)
s = format(x, 'e')
base, exp = s.split('e')
exp = int(exp)
if -3 <= int(exp) <= 3:
a,b = base.split('.')
if int(exp) > 0:
for i in range(int(exp)):
a += b[0]
b = b[1:]
elif int(exp) < 0:
for i in range(-int(exp)):
if a:
b = a[-1] + b
a = a[:-1]
else:
b = '0' + b
return a + '.' + b
else:
return s