jarvis_II icon indicating copy to clipboard operation
jarvis_II copied to clipboard

Created elegant solution for puzzle 22_interleave

Open paulolemus opened this issue 8 years ago • 2 comments

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 timeit over 1000000 samples).
  • Very "flat" solution.

paulolemus avatar Apr 13 '18 05:04 paulolemus

@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 avatar Apr 13 '18 06:04 chalmerlowe

@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!

paulolemus avatar Apr 13 '18 07:04 paulolemus