Last active
October 29, 2018 16:01
-
-
Save alexer/b6a434ec04ffa146d2ae953a3c82e10d to your computer and use it in GitHub Desktop.
"Should Be in the STDlib" - aka. my helper library, which has outgrown it's original name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Really useful in some situations, but you can see how often it's actually been used, since cmp() doesn't even exist anymore... | |
sign = lambda v: cmp(v, 0) | |
clamp = lambda v, minv, maxv: min(max(v, minv), maxv) | |
# These are a bit of a misnomers, since below/above suggests lt/gt, while these are le/ge | |
clamp_below = lambda v, maxv: min(v, maxv) | |
clamp_above = lambda v, minv: max(v, minv) | |
div_ceil = lambda dividend, divisor: (dividend - 1) // divisor + 1 | |
# Just for symmetry | |
div_floor = lambda dividend, divisor: dividend // divisor | |
align_up = lambda dividend, divisor: div_ceil(dividend, divisor) * divisor | |
align_down = lambda dividend, divisor: div_floor(dividend, divisor) * divisor | |
def chunk(data, chunksize): | |
islice = itertools.islice | |
it = iter(data) | |
return iter(lambda: tuple(islice(it, chunksize)), ()) | |
def collapse(*args): | |
if len(args) == 1: | |
args = args[0] | |
items = iter(args) | |
value = next(items) | |
for item in items: | |
assert item == value, 'Expected all values to be identical; %r != %r' % (item, value) | |
return value | |
# These were borrowed, since I saw their usefullness, but I haven't really ended up using them at all | |
# from pyrtsa @ #python.fi @ ircnet, https://gist.github.com/1310524 | |
take = lambda l, n: l[slice(n, None) if n < 0 else slice(n)] | |
drop = lambda l, n: l[slice(n) if n < 0 else slice(n, None)] | |
# do not take/drop if n is negative | |
take_head = lambda l, n: take(l, max(n, 0)) | |
take_tail = lambda l, n: take(l, -max(n, 0)) | |
drop_head = lambda l, n: drop(l, max(n, 0)) | |
drop_tail = lambda l, n: drop(l, -max(n, 0)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment