Skip to content

Instantly share code, notes, and snippets.

@MushroomMaula
Last active September 9, 2021 21:04
Show Gist options
  • Save MushroomMaula/ed8a9ce80f459dae9692ab828fe09367 to your computer and use it in GitHub Desktop.
Save MushroomMaula/ed8a9ce80f459dae9692ab828fe09367 to your computer and use it in GitHub Desktop.
Useful python snippets
from typing import Sequence
def chunks(l: Collection, n):
"""
Yield successive n-sized chunks from l.
>>> list(chunks([1,2,3,4,5,6], 3))
[[1, 2, 3], [4, 5, 6]]
>>> list(chunks([1,2,3,4,5,6], 5))
[[1, 2, 3, 4, 5], [6]]
"""
for i in range(0, len(l), n):
yield l[i:i + n]
from typing import Sequence
def cycle_until_n(l: Sequence, n: int, start: int = 0):
"""
Cycle the sequence until n is reached
>>> list(cycle_until_n([1, 2, 3, 4], 6))
[1, 2, 3, 4, 1, 2]
"""
for i in range(n):
# stay inside the range of the sequence
index = (start+i) % len(l)
yield l[index]
def map_neighbor(values: Sequence[Any], f: Callable, d: int = 1) -> List[Any]:
"""
Applies f to every values dth neighbor
f(v_0, v_d) f(v_1, v_d+1), ..., f(v_n-d, v_n)
:param values: The values f is applied on
:param f: The callable used on the values needs to take to arguments
:param d: The distance of the indices used, defaults to 1
:return: List containing the resulting values, with length len(values)-1
>>> from operator import sub
>>> values = [1, 2, 3, 4, 5]
>>> f = lambda a, b: abs(sub(a, b))
>>> map_neighbor(values, f, 1)
[1, 1, 1, 1]
>>> map_neighbor(values, f, 2)
[2, 2, 2]
"""
return [f(a, b) for a, b in zip(values[:-d], values[d:])]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment