3.19. My Range ¶
Our range
function is broken at the labs. So, we need a new one!
Unfortunately, there are no for
statements left. We have to do it
recursively. Can you help us?
Your goal is to write a function named my_range that takes three integers as input and returns a list of integers. It should works in the same way range function works.
You cannot use the \(\color{purple}{\texttt{range()}}\) function
and for
statements.
You can refer the textbook for recursion.
Sample I/O:
>>> my_range(3, 10, 1)
[3,4,5,6,7,8,9]
>>> my_range(3, 9, 2)
[3,5,7]
def my_range(start,stop,step):
if(stop < start):
return []
else:
return [start] + my_range(start + step, stop, step) # note that left side is always a list and right side will be list even it is empty.