93.7k views
2 votes
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: [start:stop:step], 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

User DMozzy
by
5.4k points

1 Answer

4 votes

Answer:

See Explaination

Step-by-step explanation:

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("")

User Darren Cato
by
6.0k points