Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon.

Pages: 1-

Recursion question

Name: Anonymous 2022-09-22 9:36

Sup /prog/. I'm at my wits end. I cannot figure out how this recursive function in python works for the life of me. Will anyone help me out?

def calc_sum(n):
if n==1:
return 1
else:
return n+calc_sum(n-1)

print(calc_sum(3)) # prints 6??

Name: Anonymous 2022-09-22 12:12

calc_sum(3)=3+calc_sum(2)=3+2+calc_sum(1)=3+2+1=6

Name: Anonymous 2022-09-22 17:53

>>2
I get the general idea. I don't get where the 3,2,1 are stored. Which variable is is?

Name: Anonymous 2022-09-22 19:40

>>3
nigger

Name: Anonymous 2022-09-22 20:09

>>3
They're stored in the stack as arguments to function calls who have yet not returned.

Name: Anonymous 2022-09-23 6:28

>>5
How does the value persist between different function calls? The only way to make it work is a global variable, and I don't use that here.

Name: Anonymous 2022-09-23 19:28

>>6
Due to the inner working of the interpreter, probably.
In the line
return n+calc_sum(n-1)
you're not seeing the interpreter creating a list like ["+", "n", "calc_sum(n-1)"] then mapping it with eval to [add_function, 3, 3], which of course uses the same process on calculating that last 3, and then calls apply to return 6.

Name: Anonymous 2022-09-24 11:43

>>6
stack

Name: Anonymous 2022-09-24 17:45

>>7
How do I learn those things? They were not in the book.

Name: Anonymous 2022-09-24 17:46

>>8
Stack the data structure? I am not sure how this relates, I am not using a stack anywhere.

Name: Anonymous 2022-09-24 18:58

>>9
Which book? Have you read SICP today?

Name: Anonymous 2022-09-25 7:08

Name: Anonymous 2022-09-27 1:56

>>6
the function calls are nested, and the deepest one finishes first
calc_sum(3)=3+calc_sum(2)=3+2+calc_sum(1)=3+2+1=6
calc_sum(3) -> = calc_sum(2) -> calc_sum(1) = return 1
return 2+1
return 3+3

Name: Anonymous 2022-09-27 2:12

See if you can write one that does half it's sum forward and half counting backward

eg calc_sum(7) = 7+5+3+1 +2 +4 +6

Name: Anonymous 2022-09-27 2:24

def calc_sumF(n, tot):
if n==1:
return 1+tot
else:
return calc_sum(n-1, tot+n)

print(calc_sumF(3, 0)) # prints 6??

Name: Anonymous 2022-09-27 5:54

def calc_sumF1(n, tot):
if n==1:
return 1+tot
else:
return calc_sumF2(n-1, tot+n)

def calc_sumF2(n, tot):
if n==1:
return 1+tot
else:
return n + calc_sumF1(n-1, tot)

Name: Anonymous 2022-09-27 5:55

>>13
Where are the deeper calls stored? Does python.exe automatically do this because it's recursion?

Name: Anonymous 2022-10-02 8:27

>>17
Simple answer is in a chunk of RAM, but probably in the L1-L3 cache

Don't change these.
Name: Email:
Entire Thread Thread List