KeiruaProd

I help my clients acquire new users and make more money with their web businesses. I have ten years of experience with SaaS projects. If that’s something you need help with, we should get in touch!
< Back to article list

some itertools tips

# flatten
# turns an array of arrays into a 1-level array
>>> from itertools import chain
>>> flatten = chain.from_iterable
>>> list(flatten([[1, 2], [3], [4, 5]]))
[1, 2, 3, 4, 5]
# it only removes one level:
>>> list(flatten([[1, 2], [3], [4, 5] ,[6,7,[8]]]))
[1, 2, 3, 4, 5, 6, 7, [8]]

# chunks is now built-in
# https://docs.python.org/3/library/itertools.html#itertools.batched
>>> from itertools import batched
>>> list(batched(range(10), 2))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

some other cool things in peter norvig pytudes: https://github.com/norvig/pytudes/blob/main/ipynb/Advent-2020.ipynb

it’s always interesting how he manages to abstract away cool things, like

def data(day: int, parser=str, sep='\n') -> list:
    "Split the day's input file into sections separated by `sep`, and apply `parser` to each."
    with open(f'data/advent2020/input{day}.txt') as f:
        sections = f.read().rstrip().split(sep)
        return list(map(parser, sections))