Q:

A more optimized code in recursion exercise

As a novice programmer doing an exercise in recursion, the following function takes in two numbers and returns a comma-separated string with all the numbers in-between the start and end number, inclusive of both numbers. I used a list, convert it to set and at last convert again to string.The code working but I believe that there is a better way to solve it. Any suggestions?
def numbersInbetween(a, b):
    if a > b:
        return "Invalid"
    elif a == b:
        return str(b) 
    else:
        alist = range(a,b+1,1)
        aset = set(alist)
        aset2 = ','.join(str(s) for s in aset)
        numbersInbetween(a+1, b)
        return aset2

A:

If you are going to use range, there is no need to do recursion at all :-)
def numbersInbetween(a, b):
    if a > b:
        return "Invalid"
    elif a == b:
        return b
    else:
        return "{}, {}".format(a, numbersInbetween(a + 1, b))

print numbersInbetween(1, 10)
# 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

We recursion to generate the string from the next element till the end with this line
return "{}, {}".format(a, numbersInbetween(a + 1, b))

We retain the current number a, and then we call the same function again with a + 1 and b. So the evaluation will be done like this, for the input 1 and 3
{}, {}.format(1, numbersInbetween(2, 3))

and then
"{}, {}".format(1, "{}, {}".format(2, numbersInbetween(3, 3)))

which will become
"{}, {}".format(1, "{}, {}".format(2, 3))

which will become
"{}, {}".format(1, "2, 3")

and that finally becomes
1, 2, 3

