0

I tried writing a code for a recursive function that takes x value as an input parameter and print an x-digit strictly increasing number. For example x = 6 gives output 67891011.

l = []


def recfun(x):
    if x == 12:
        for i in range(0,len(l)):
            l[i] = str(l[i])
        print(l)
        return int("".join(l))
    else:
        l.append(x)
        x += 1
        recfun(x)


x = int(input('Enter a number: '))
y = recfun(x)
print(y)

I know this won't work for other values except 6. But the returned value printed displays None.

Input:

Enter a number: 6

Output:

['6', '7', '8', '9', '10', '11']
None

Kindly suggest some way to overcome this.

Gustav Rasmussen
  • 3,720
  • 4
  • 23
  • 53

3 Answers3

0

You have if-else statements. Since there is a chance that it might go to else when if the condition fails, you have to add return there as well!

l = []
def recfun(x):

    if x == 12:
        for i in range(0,len(l)):
            l[i] = str(l[i])
        print(l)
        ans = (int("".join(l)))
        return ans
    else:
        l.append(x)
        x+=1
        return recfun(x) #return here


x = int(input('Enter a number: '))
y = recfun(x)
print(y)

Enter a number: 3
['3', '4', '5', '6', '7', '8', '9', '10', '11']
34567891011
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22
0

As you have assign return value to y but your recursion doesn't return anything replace recfun(x) to return recfun(x) in else statement

Cheris Patel
  • 56
  • 1
  • 4
0

You are not returning in the function.

Modified code:

l = []
def recfun(x):

    if x == 12:
        for i in range(0,len(l)):
            l[i] = str(l[i])
        print(l)
        ans = (int("".join(l)))
        return ans
    else:
        l.append(x)  #comes here for the input 6
        x+=1
        return recfun(x)


x = int(input('Enter a number: '))
y = recfun(x)
print(y)

S VAIBHAVE
  • 62
  • 6