मराठी

range() function in python does not include the stop value. Write a generator function equivalent to range() function that includes the stop value also.

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
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 8: Exception Handling & Generate Functions - EXERCISE [पृष्ठ १५८]

APPEARS IN

सीबीएसई Computer Science with Python [English] Class 12
पाठ 8 Exception Handling & Generate Functions
EXERCISE | Q 12. | पृष्ठ १५८
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×