Implement a generator function, chunker
, which gets an iterable and returns a piece of specific size at a time. Using the function like this:
for chunk in chunker(range(25), 4):
print(list(chunk))
should result in the output:
[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 having trouble once again on this subject about generators in Python. I can run the code, but not with the output I want. I am not able to create the columns as it 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]