1
Implement a generator function, chunker
, which takes an iterable and returns a specific piece of size at a time. Resorting to the function like this:
for chunk in chunker(range(25), 4):
print(list(chunk))
should result in the exit:
[0, 1, 2, 3]
[4, 5, 6, 7]
[8, 9, 10, 11]
[12, 13, 14, 15]
[16, 17, 18, 19]
[20, 21, 22, 23]
[24]
I’m struggling once again on this subject about generators in Python. I can run the code, but not with the desired output. I’m not able to create the columns as he asks in the question, I can only count the elements with range()
.
This was my code :
def chunker(iterable, size):
num = size
for item in iterable:
yield item,size
for chunk in chunker(range(25), 4):
print(list(chunk))
That generated this output:
[0, 4]
[1, 4]
[2, 4]
[3, 4]
[4, 4]
[5, 4]
[6, 4]
[7, 4]
[8, 4]
[9, 4]
[10, 4]
[11, 4]
[12, 4]
[13, 4]
[14, 4]
[15, 4]
[16, 4]
[17, 4]
[18, 4]
[19, 4]
[20, 4]
[21, 4]
[22, 4]
[23, 4]
[24, 4]
I was now working on a solution so I wouldn’t have to turn the entry into a list. Good solution
– Miguel
That’s why we’re here :D
– Woss
Anderson notes that I put list(range(25)) on purpose (I know I don’t need it with range), but this way I would implement yours
gerador()
,chunker(list(gerador()), 4)
e.g. Your solution is better regardless of that, my biggest problem is actually having to turn into a list– Miguel