Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
recursion
#1
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))
Reply
#2
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)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020