0

im facing this question, and I was hoping some of you might help out:

Write a function that accepts an iterable and a positive number n. The function returns a new iterator that gives values from the original in tuples of length n. Pad missing values with 'None' if needed for the very last tuple.

for example:

for x in bunch_together(range(10),3): print(x)

return values are

(0, 1, 2) (3, 4, 5) (6, 7, 8) (9, None, None)

This is what I come up with so far:

def bunch_together(iterable,n):
    tup = tuple()
    for item in iterable:
        for i in range(n):
            tup += (i,)
        yield tup

but this obviously doesn't work because I didnt accounted for the range at all(the output as of now looks something like this:

(0, 1, 2)
(0, 1, 2, 0, 1, 2)
(0, 1, 2, 0, 1, 2, 0, 1, 2)
...#(goes on)

I could either create a generator of build an iterator (as in building a class composed of init iter and next) Thanks for the help!

Hadar
  • 658
  • 4
  • 17
  • Note that [the duplicates](https://stackoverflow.com/q/24527006/364696) are actually more complicated than your case (they're trying to avoid filler values). Since you're fine with filler values, [the `grouper` recipe from the `itertools` docs](https://docs.python.org/3/library/itertools.html#itertools-recipes) is basically exactly what you need. – ShadowRanger Feb 19 '19 at 21:07

1 Answers1

0

Try initializing tuple inside for loop

def bunch_together(iterable,n):

    for k in range(0,len(iterable),n):
        tup = tuple()
        for i in range(k,k+n):
            tup += (iterable[i] if i<len(iterable) else None,) # condition to check overflow
        yield tup

for x in bunch_together(range(10),3): 
    print(x)

Output

(0, 1, 2)
(3, 4, 5)
(6, 7, 8)
(9, None, None)
mad_
  • 8,121
  • 2
  • 25
  • 40