Brilliant or insane code?
stavros.io
Brilliant or insane code?
1–10 of 114 posts
Re: Brilliant or insane code?
#2Brilliant and insane?
Re: Brilliant or insane code?
#3Brilliant and insane?
Hah, yep, I hadn't considered it can be both.
Re: Brilliant or insane code?
#4Insane, 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?
#5It'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:
passRe: Brilliant or insane code?
#6It'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?
#7I 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?
#8It 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?
#9We all love short and fast. But this is definitely an interesting approach. I'd love to see similar approaches to problems if you guys can point out to some.
Re: Brilliant or insane code?
#10It'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.