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

Write python generator: There are always positive values for those parameters. d

ID: 3833013 • Letter: W

Question

Write python generator:

There are always positive values for those parameters.

def slice_gen(iterable, start, stop, step):
pass

The slice gen generator takes one iterable and a start, stop and step values (all int, with the same meanings as the values in a slice: Istart:stop:stepl, except start and stop must be non-negative and step must be positive, raise an AssetionError exception if any is not. It produces all the values in what would be the slice (without every putting all the values in a list and slicing it. For example for i in slice gen ('abcdefghijk', 3,7,1) print (i, end prints the 4 values: 'd', 'e', f', and IgI: the 3rd, 4th 5th, and 6th values (start counting at the oth value) Hint: you may use the range class and its in operator. Even if the iterable is infinite, this generator decorator should work and produce a finite number of values.

Explanation / Answer

def slice_gen(iterable, start, stop, step):
it = iter(iterable)
if start < 0 or stop < 0 or step <= 0:
raise AssertionError
count = -1
nextI = start
while True:
count += 1
try:
item = next(it)
if count == stop:
break
elif count == nextI:
nextI = nextI + step
yield item
except:
return
for i in slice_gen('abcdefghijk', 3, 7, 1):
print(i, end='')
print("")

# code link: https://paste.ee/p/7Uox9

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote