Home > database >  Getting a range of numbers with recursion using python
Getting a range of numbers with recursion using python

Time:09-04

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.

CodePudding user response:

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.

  • Related