Our Range class, from Section 2.3.5, relies on the formula max(0, (stop start +
ID: 3879057 • Letter: O
Question
Our Range class, from Section 2.3.5, relies on the formula max(0, (stop start + step 1) // step) to compute the number of elements in the range. It is not immediately evident why this formula provides the correct calculation, even if assuming a positive step size. Justify this formula, in your own words
IN SECTION 2.3.3
class Range:
2 ”””A class that mimic s the built-in range class.”””
3
4 def init (self, start, stop=None, step=1):
5 ”””Initialize a Range instance.
6
7 Semantics is similar to built-in range class.
8 ”””
9 if step == 0:
10 raise ValueError( step cannot be 0 )
11
12 if stop is None: # special case of range(n)
13 start, stop = 0, start # should be treated as if range(0,n)
14
15 # calculate the effective length once
16 self. length = max(0, (stop start + step 1) // step)
17
18 # need knowledge of start and step (but not stop) to support getitem
19 self. start = start
20 self. step = step
21
22 def len (self):
23 ”””Return number of entries in the range.”””
24 return self. length
25
26 def getitem (self, k):
27 ”””Return entry at index k (using standard interpretation if negative).”””
28 if k < 0:
29 k += len(self) # attempt to convert negative index
30
31 if not 0 <= k < self. length:
32 raise IndexError( index out of range )
33
34 return self. start + k self. step
Explanation / Answer
Solution:
Python’s support range class that contains three parameters: the one-parameter form, range(n), that generates a sequence of integers from 0 up to but not including n. A two-parameter form, range(start,stop) generates integers from start up to, but not including, stop. A three-parameter
form, range(start, stop, step), generates a similar range as range(start, stop), but with increments of size step rather than 1.
When a single parameter is sent, as in range(n), it serves as the stop value ( the second parameter); the value of start is effectively 0 in that case.
def range(start, stop=None, step=1):
if stop is None:
stop = start
start = 0
When range(n) is invoked, the actual parameter n will be assigned to formal parameter start.
The formula max(0, (stop start + step 1) // step) computes the number of elements in the range because this formula computes range for both positive and negative step sizes. When we simply take the starting value of the range plus k times the step size, for example, k=0, we return the start value.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.