Python Forum
recursion - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: recursion (/thread-17049.html)



recursion - mcgrim - Mar-26-2019

I am writing a program dealing with recursion, so far the info given is
n, n+1, n+2, n+3. I have to reach 1000.
I have done it by using the list method and the if else method.
The first method returns a completely empty output and the second one
returns the word 'none'.

I am not sure where the error is.

#list method
h=1/1000
a=-0.5
x=math.exp(h*a)
y=math.exp(2*h*a)

L=[1.0,x,y]
for i in range(0,1000):
    L.append(L[-1] + h*a*((23/12)*y -(4/3)*x + (5/12)))
#if/else method

h=1/1000
a=-0.5
x=math.exp(h*a)
y=math.exp(2*h*a)

import sys
 
sys.setrecursionlimit(3000)
 
def recursion(n):
    if n == 1:
        return 1
    elif n == 2:
        return x
    elif n == 3: 
        return y
    elif n==4:
        return y+ h*a*((23/12)*y -(4/3)*x + (5/12))
    
print (recursion(1000))



RE: recursion - ichabod801 - Mar-26-2019

Your list one works. If you are just running it from the command line, you are not seeing anything because there is no print statement. If you run it in interactive mode, you will find that L is full of values just under 1.

Your recursion one starts with 1000. That's not any of the four options, so none of the return statements gets called. That gives you the default return value of None. Note that you are not recursing. Nowhere in recursion do you call recursion. You need to have a terminal state where you return a value, and a recursion state where the function calls itself:

def recurse(n):
    if n >= 108:
        return [108]
    else:
        return [n] + recurse(n + 1)