Live data from Hacker News

Brilliant or insane code?

stavros.io

1–10 of 114 posts

Re: Brilliant or insane code?

#4
Insane, because it relies on the zip implementation detail. If you cared about a measly factor of 4 in performance you wouldn't be using python anyway.

Re: Brilliant or insane code?

#5
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

Re: Brilliant or insane code?

#6
post #5

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.

Re: Brilliant or insane code?

#7
I think the code is pretty ok, except for the stupid name, docstring and that it is a method and not a free function.

    def chunks(seq, n):
        "groups the elements of the seq into a list of n-sized chunks."
        return zip(*[iter(seq)]*n)

Re: Brilliant or insane code?

#8
It 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?

#10
post #6
post #5

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.

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.
Post reply on HN