Advertisements
Advertisements
Question
range() function in python does not include the stop value. Write a generator function equivalent to range() function that includes the stop value also. The function will take three arguments start, stop and step and will generate the desired list.
Code Writing
Advertisements
Solution
The generator must support both increasing and decreasing sequences and must reject a zero step.
def inclusive_range(start, stop, step=1):
if step == 0:
raise ValueError("step cannot be zero")
if step > 0:
while start <= stop:
yield start
start += step
else:
while start >= stop:
yield start
start += step
Example:
print(list(inclusive_range(1, 5, 2)))
print(list(inclusive_range(5, 1, -2)))
Output:
[1, 3, 5]
[5, 3, 1]shaalaa.com
Is there an error in this question or solution?
