jarvis_II
jarvis_II copied to clipboard
Created elegant solution for puzzle 22_interleave
I think this new solution is very clean and self documenting.
- Used lazy generators as much as possible.
- Runtime is about 20% faster than solution 0 (checked with
timeitover 1000000 samples). - Very "flat" solution.
@paulolemus
Encouraged by some of your code, I tried some experiments... the results are discussed below:
%%timeit from itertools import chain, tee
with open('interleave.txt') as fin:
line_a = map(int, fin.readline().split(';'))
line_b = map(int, fin.readline().split(';'))
interweaved = tuple(num for num in chain(*zip(line_a, line_b)))
deltas = (a - b for a, b in zip(interweaved, interweaved[1:]))
even_deltas = (delta for delta in deltas if delta % 2 == 0)
# -----------
# on my machine... ditching num for num saved 10 microseconds, see below:
%%timeit from itertools import chain, tee
with open('interleave.txt') as fin:
line_a = map(int, fin.readline().split(';'))
line_b = map(int, fin.readline().split(';'))
interweaved = tuple(chain(*zip(line_a, line_b)))
deltas = (a - b for a, b in zip(interweaved, interweaved[1:]))
even_deltas = (delta for delta in deltas if delta % 2 == 0)
# -----------
# on my machine... using tee to create a matching generator instead of
# creating a tuple and then duplicating the tuple basically saved no time
# but prolly saves memory.
# Using next() allows us to pop off the first element, see below:
%%timeit from itertools import chain, tee
with open('interleave.txt') as fin:
line_a = map(int, fin.readline().split(';'))
line_b = map(int, fin.readline().split(';'))
interweaved1, interweaved2 = tee(chain(*zip(line_a, line_b)))
next(interweaved2)
deltas = (a - b for a, b in zip(interweaved1, interweaved2))
even_deltas = (delta for delta in deltas if delta % 2 == 0)
# -----------
# on my machine... ditching the second comprehension and doing the
# modulo comparison upfront saves about five microseconds... see below:
%%timeit from itertools import chain, tee
with open('interleave.txt') as fin:
line_a = map(int, fin.readline().split(';'))
line_b = map(int, fin.readline().split(';'))
interweaved1, interweaved2 = tee(chain(*zip(line_a, line_b)))
next(interweaved2)
deltas = (a - b for a, b in zip(interweaved1, interweaved2) if (a - b) % 2 == 0)
@chalmerlowe Thanks for introducing me to tee, I've seen it a couple times but never looked into it.
I'll also remove that num for num in portion, I totally forgot I could pass the generator directly!