Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

# Test drop_last e-->\'\'.join([v for v in drop_last(\'combustible\', 5)])-->com

ID: 3607381 • Letter: #

Question

# Test drop_last
e-->''.join([v for v in drop_last('combustible', 5)])-->combus
e-->''.join([v for v in drop_last(hide('combustible'), 5)])-->combus
e-->''.join([v for v in drop_last(hide('combustible'), 3)])-->combusti
e-->''.join([v for v in drop_last(hide('combustible'), 10)])-->c

# Test yield_and_skip
e-->''.join([v for v in yield_and_skip('abbabxcabbcaccabb',lambda x : {'a':1,'b':2,'c':3}.get(x,0))])-->abxccab
e-->''.join([v for v in yield_and_skip(hide('abbabxcabbcaccabb'),lambda x : {'a':1,'b':2,'c':3}.get(x,0))])-->abxccab
e-->''.join([v for v in yield_and_skip(hide('abxcbbacbbbaxbbaab'),lambda x : {'a':1,'b':2,'c':3}.get(x,0))])-->axccaba


def hide(iterable):
for v in iterable:
yield v

Remember, if an argument is iterable, it means that you can call only iter on it, and then call next on the value iter returns (recall for loops do this automatically). There is no guarantee you can call len on the iterable or index/slice it. You may not copy all the values of an iterable into a list (or any other data structure) so that you can perform these operations (that is not in the spirit of the assignment, and some iterables could produce an infinite number of values). You may create local data structures storing as many values as the arguments or the result that the function returns, but not all the values in the iterable(s): in fact, some may be infinite. Remember the "exchange print vs. yield" heuristic for writing generators from the notes

Explanation / Answer

def drop_last(iterable, n):
iterator = iter(iterable)
try:
nlist = [next(iterator) for i in range(n)]
while True:
try:
nlist.append(next(iterator))
element = nlist[0]
nlist = nlist[1:]
yield element
except StopIteration:
break
except StopIteration:
return
def hide(iterable):
for v in iterable:
yield v
print(''.join([v for v in drop_last('combustible', 5)]))
print(''.join([v for v in drop_last(hide('combustible'), 5)]))
print(''.join([v for v in drop_last(hide('combustible'), 3)]))
print(''.join([v for v in drop_last(hide('combustible'), 10)]))


def yield_and_skip(iterable, skip_func):
iterator = iter(iterable)
while True:
try:
a = next(iterator)
yield a
count = skip_func(a)
for i in range(count):
a = next(iterator)
except StopIteration:
break
print(''.join([v for v in yield_and_skip('abbabxcabbcaccabb',lambda x : {'a':1,'b':2,'c':3}.get(x,0))]))
print(''.join([v for v in yield_and_skip(hide('abbabxcabbcaccabb'),lambda x : {'a':1,'b':2,'c':3}.get(x,0))]))
print(''.join([v for v in yield_and_skip(hide('abxcbbacbbbaxbbaab'),lambda x : {'a':1,'b':2,'c':3}.get(x,0))]))

# sample execution

'''

'''

# copy pastable code link: https://paste.ee/p/loolk