Last active
December 11, 2015 11:48
-
-
Save mecab/4595806 to your computer and use it in GitHub Desktop.
A custom iterators for me :D
This file contains 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
import itertools | |
import math | |
def defer(l, num_defer=1): | |
""" | |
>>> [x for x in defer([0, 1, 2, 3])] | |
[[0, 1], [1, 2], [2, 3]] | |
>>> [x for x in defer([0, 1, 2, 3], 2)] | |
[[0, 2], [1, 3]] | |
""" | |
its = itertools.tee(l, 2) | |
for current, next in itertools.izip(its[0], itertools.islice(its[1], num_defer, None)): | |
yield [current, next] | |
def diffs(iter_of_iter): | |
""" | |
>>> for x in diffs([[0, 1, 2], [1, 2, 3], [3, 4, 5]]): | |
... print x | |
[1, 1, 1] | |
[2, 2, 2] | |
""" | |
for current, next in defer(iter_of_iter): | |
yield itertools.imap(lambda x: x[1] - x[0], itertools.izip(current, next)) | |
def pow2sum(l): | |
""" | |
>>> pow2sum([1, 2, 3]) | |
14 | |
""" | |
return sum((x ** 2 for x in l)) | |
def speeds2(iter_of_iter): | |
""" | |
>>> for x in speeds2([[0, 0, 0], [1, 0, 0], [2, 2, 2]]): | |
... print x | |
1 | |
9 | |
""" | |
return (pow2sum(x) for x in diffs(iter_of_iter)) | |
def speeds(iter_of_iter): | |
""" | |
>>> for x in speeds([[0, 0, 0], [1, 0, 0], [2, 2, 2]]): | |
... print x | |
1.0 | |
3.0 | |
""" | |
return (pow2sum(x) ** 0.5 for x in diffs(iter_of_iter)) | |
def _test(): | |
import doctest | |
doctest.testmod() | |
if __name__ == "__main__": | |
_test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment