Write python generators below(yield): The group generator takes an iterable and
ID: 3832044 • Letter: W
Question
Write python generators below(yield):
The group generator takes an iterable and an int (call it n) as parameters: it produces lists of n values: the first list contains the first n values from the iterable; the second list contains the second n values from the iterable, etc. until there are fewer than n values left to put in the returned list. For example for i in gropu('abcdefghijklm',4): print(i,end='') prints ['a','b','c','d'] ['e','f','g','h'] ['i','j','k','l']. Hint: call iter and next directly, building a list with n values,so it doesn’t violate the conditions for using iterables.
Explanation / Answer
def group(iterable,n):
count = 0
lis = []
it = iter(iterable)
while True:
try:
lis.append(next(it))
count += 1
if count == n:
yield lis
lis = []
count = 0
except:
return
for val in group('abcdefghijklm', 4):
print val
# code link: https://paste.ee/p/R7JBI
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.