Advertisements
Advertisements
प्रश्न
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.
कोड लेखन
Advertisements
उत्तर
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
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
