It's not brilliant. This accomplishes the same thing without being hard to understand: from itertools import islice iterator = iter(array) try: while True: yield list(islice(iterator, 3)) except StopIteration: pass
Sure, there are many ways to do it, but I think the author was going for speed here.
Brilliant or insane code?
11–20 of 114 posts
Re: Brilliant or insane code?
#12It does not rely on an implementation detail, that is how iterators work. He's just supplied the same iterator to a function which consumes iterators... that's exactly the expected behaviour.
"The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip([iter(s)]n)."
Re: Brilliant or insane code?
#13It does not rely on an implementation detail, that is how iterators work. He's just supplied the same iterator to a function which consumes iterators... that's exactly the expected behaviour.
Re: Brilliant or insane code?
#14Earlier quoted context omitted.
Sure, there are many ways to do it, but I think the author was going for speed here.
I'd be surprised if my way is slower. Any time you unpack into a function such as zip() python has to create an intermediary list to store all the results before calling the function.
The OP's question of is this genius or bad is clear in that regard: it is bad, due to not being the proper optimization direction, but it is interesting.
Re: Brilliant or insane code?
#15Earlier quoted context omitted.
Sure, there are many ways to do it, but I think the author was going for speed here.
I'd be surprised if my way is slower. Any time you unpack into a function such as zip() python has to create an intermediary list to store all the results before calling the function.
http://docs.python.org/2/library/itertools.html#itertools.iz...
Re: Brilliant or insane code?
#16 i = iter(array)
return zip(i, i, i)
There you go. All but neceessary magic gone with just one line more.Re: Brilliant or insane code?
#17 The left-to-right evaluation order of the iterables is guaranteed. This makes
possible an idiom for clustering a data series into n-length groups using
zip(*[iter(s)]*n).
http://docs.python.org/2/library/functions.html#zipRe: Brilliant or insane code?
#18may save a few keystrokes some rainy day. good post.
Re: Brilliant or insane code?
#19This is in the zip documentation as the way of solving this problem. Sort of surprised the author didn't look up the documentation before writing what is otherwise a very good post. The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n). http://docs.python.org/2/library/functions.html#zip
I've updated the post with this, another commenter pointed it out. Thanks!
Re: Brilliant or insane code?
#20i = iter(array) return zip(i, i, i) There you go. All but neceessary magic gone with just one line more.