Getting a range of numbers with recursion using python

Question:

I’m struggling with this question. Basically, I need to create a recursive function that takes a start, end, and range as parameters:

ex. recurs(6,10,range(4,17)) should return: [6,7,8,9,10]

I’ve figured my base case out but I’m struggling with the rest of the logic. I’ve coded something but it isn’t outputting anything. Here is my code and any advice would be appreciated:

def recurs(start, end, nums):
    if not nums:
        return []
    elif(nums[0] >= start) and (nums[0] <= end):
        return nums[0] + recurs(start, end, nums[1:])

Calling recurs(4,9,range(1,10)) is not returning anything.

Asked By: Sam Jones

||

Answers:

Try this :

def recurs(start, end, nums):
    status  = True
    while status:
        # print("nums is :", nums)
        if not len(nums):
            return []
        elif(nums[0] >= start) and (nums[0] <= end):
            ret_val = [nums[0]] + recurs(start, end, nums[1:])
            # print("Retval is :", ret_val)
            return ret_val
        else:
            nums = nums[1:]


ret = recurs(6,10, list(range(4,17)))
print(ret)

Output :

[6, 7, 8, 9, 10]

You can uncomment the print lines and see the flow. You would understand the problem with code you tried.

Answered By: Prashant Kumar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.