r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

1

u/RenewAi Apr 05 '22

Recursion: A function that calls itself and stops calling itself when a certain condition is met, then somehow does a magic wrap up backwards thing that does all the calculations.

The last bit of recursion has stumped me for years. It just doesn't work with my brain for some reason.

3

u/AlSweigart Author: ATBS Apr 05 '22 edited Apr 05 '22

I just got done writing a book on recursion. The reason it's mystifying to you is most likely because the tutorials/instructors who taught it didn't explicitly bring up the call stack.

First: A stack is one of the simplest data structures in computer science. It's like a list, but you can only add or remove things to and from the end of the list. We say you "push" data onto the end (or top) of the stack and "pop" data off the top of stack.

Second: Function calls aren't one-way. When you call a function, the program automatically and behind the scenes your program notes where the execution should return to when the function call returns. This data is called a frame object, and frame objects are pushed to the top of the call stack when a function is called and popped off the top of the stack when the function returns.

So if you have a function a() that calls b() that calls c(), this is how your program knows that when c() returns, it should go back to b(), and when b() returns, it should go back to a(). Here's a brief Python program:

def a():
    print('Start of a()')
    b()
    print('End of a()')
def b():
    print('Start of b()')
    c()
    print('End of b()')
def c():
    print('Start of c()')
    print('End of c()')
a()

When we run it, notice it goes A-B-C-C-B-A:

Start of a()
Start of b()
Start of c()
End of c()
End of b()
End of a()

This is why stacks are called a LIFO or last in, first out. The last thing pushed to the stack is the first thing popped off it.

When we call a(), a frame object (I'll call it a) is pushed to the top of the stack, then when b() is called a frame object (I'll call it b) is pushed and becomes the new top of the stack. Then b() calls c() which creates a c-frame object to push to the top of the stack. When c() returns, the c-frame object is popped off, then when b() returns, the b-frame object is popped off, then when a() returns the a-frame object is popped off and the call stack is empty and our program is back in the global scope, outside of all functions. (Or, if you're in a program written in C which has a main() function, returning from main() means the program terminates.)

One thing to keep in mind: the execution is always in the function call at the top of the stack. This is why when c() returns to b(), the c frame object pops off and the old b frame object under it is now at the top.

It's a bit confusing because the call stack handled behind the scenes. You can't point to a place in your source code where the call stack is. It's either automatically handled by the interpreter or the code for it is added to your program by the compiler.

Now, if you have a recursive function, the function is calling itself. So the call stack has frame objects for the same function but that's okay because remember that the frame objects represent function calls and not functions. Say we have a factorial function:

def fact(n):
    if n == 1:
        return 1
    else:
        return n * fact(n - 1)

When we call fact(3), a new frame object (I'll call it fact-3) is popped to the top of the call stack and the execution enters the fact() function. This ends up running return n * fact(n - 1), but before it can do that, it needs to call fact(2).

A new frame object (I'll call it fact-2) is created and popped to the top of the stack. This is just like a() calling b(), except in this case a and b are the same function: it's fact() calling fact().

Here's the other thing that trips people up: each frame object stores a separate copy of the local variables. Rather than think of the local variables like n as local to the function, they are actually local to a specific function call. This means there are multiple n variables: in the fact-3 frame object n is set to 3 and in the fact-2 frame object n is set to 2. They have the same name, but these are two separate variables storing two separate values.

This is a major point of confusion for people learning recursion. Seriously, people are always thrown off because when you look at the code, you only see one n variable and it's easy to overlook the fact that there's actually one n variable for each function call. This is why recursion looks like magic: you expect fact(5) to do 5 x 4 x 3 x 2 x 1 but all you see is n * fact(n - 1) and people don't know where the full multiplication is taking place.

Anyway, fact(2) has to call fact(1) (creating a fact-1 frame object), which returns 1. When it returns, the fact-1 frame object is popped off the stack. Now we're back in the previous call to fact(), but it's the fact-2 frame object where n is set to 2. The return n * fact(n - 1) now looks like return 2 * 1 because fact(n - 1) returned 1 and the local n variable is 2.

This makes our fact(2) call return 2 * 1, that is, 2, and the program (automatically, behind the scenes) pops off the fact-2 frame object and the execution returns to the fact() function again, but in the context of the fact-1 frame object where the local n variable is (and always has been) set to 3. This time the return n * fact(n - 1) is really return 3 * 2. So this fact(3) function call returns 6 and pops the fact-3 frame object off the call stack.

There's nothing left on the call stack at this point, so the program continues running code from whatever point in the global scope called fact(3) and that fact(3) function call has evaluated to 6.

As for where the 3 x 2 x 1 is taking place, the flow control of fact() is simple enough that we can substitute the function calls with that call's return statement:

fact(3)

  |
  V

(3 * fact(2))

  |
  V

(3 * (2 * fact(1)))

  |
  V

(3 * (2 * (1)))

  |
  V

  6

1

u/RenewAi Apr 05 '22

Oh hey what's up Al? Thanks for writing replying to me! Automate the boring stuff with python was my first python tutorial ever, I bought it on udemy like 6 or so years ago and tried to get all my friends to buy it and learn python with me lol.

You are exactly right about other people not teaching the call stack, it was a huge problem for me. Interestingly enough my work around for not understanding recursion was to use iteration and a stack lol.

I really wish I had your explanation when I first tried to learn it, I would have saved so much time and frustration. I'm going to do some practice problems later tonight but I actually think I fully get it now! What an accomplishment.

I didn't know you had a recursion book, I am definitely going to check it out.

2

u/tube32 Apr 05 '22 edited Apr 05 '22

The best way to imagine recursion is like the movie inception.

Let us consider a recursive function to print from 0 to any given number (n)

1)    def function(n): 
2)       if n==0: #base condition 
3)           print(0)
4)       else:
5)           function(n-1) #recursion
6)           print(n)
7)       return 

Lets first understand the function line by line.

  1. Function declaration, pretty straightforward.

  2. Checks if n is equal to 0 (will explain what a base condition is later)

  3. If second line is True, then print 0

  4. Else

  5. Call the same function, BUT with n-1 as the parameter.

  6. print the current value of n

  7. Return (end of function)

Now say user inputs the value of n as 3.

The function first checks if n==0, which gives false since n=3, so the code moves to the else block.

Now what does the else block say? The else block says call the same function again, but with value 2 (n-1).

The code thinks to itself, "Huh, weird but sure whatever" and proceeds to do so. So now we're back to line number 1, except this time its function(2).

Now one more time at line 2 it checks if n==0, and it gives false so we move to the else block. The else block says, okay since we're here, lets call the bad boy once again with n=1.

The same process repeats for n=1 as well and the function is called for n=0.

Now the magic happens, the if statement at line 2 evaluates to True! The compiler is overjoyed as it was waiting to enter the if block. It finally enters the if block and asks the code, what do I do now? At line 3 the code says, since you have managed to make it so far, go ahead and print(0) on the screen. The compiler happily obliges and moves forward. This time, it skips lines 4 and 5 since the if block was executed and goes directly to line 6, which is a simple return statement.

Now where does the compiler emerge? It emerges back at line 5 BUT for when n=1. Now that its back it goes to line 6 and displays the current value of n (right now 1). Then on to line 7 where the the function ends for n=1.

Where does it emerge now? Again at line 5 but for n=2. Proceeds to follow the same steps as above.

Then finally we're back to line 5 for function(3) what the user originally called, where the function terminates.

A base condition is what tells a recursive function " so hey listen, if this condition is met, just do so and so and return a constant value, DO NOT call yourself again". Without a base condition a function will keep on calling itself repeatedly (equivalent of an infinite loop)

>somehow does a magic wrap up backwards thing that does all the calculations.

>>Now where does the compiler emerge? It emerges back at line 5 BUT for when n=1.

This is the magic backwards part, after the base condition is met, functions start coming out and proceed with the rest of the code, like in this case they continued from line 6.

I am afraid I have over complicated it, recursion is best understood with a visual representation. I hope you atleast got something out of it, I am not so good with explaining stuff over text :/

1

u/RenewAi Apr 05 '22

Thanks for taking the time to reply to me, i'm gonna read over this in a bit.

1

u/Fluffy-Lecture4408 Apr 06 '22 edited Apr 06 '22

Any given number

Okay let's start with -1 >:)

More seriously, recursion is a simpler way to do things that could be done iteratively. I'm not saying it's bad tho. As every recursion ultimately uses a stack (eg. call stacks on functions)

2

u/Technologenesis Apr 05 '22 edited Apr 05 '22

I'm gonna use this recursive addition function as an illustration:

func add(unsigned_int a, unsigned_int b):
    if a == 0:
        return b
    return add(a-1, b) + 1

So you seem to understand the concept of a base case; in this situation, the base case is a == 0. If a is zero, the function doesn't recur; if it's not, it recurs in a way that ensures a will eventually be zero, at which point the function will stop recurring. So imagine calling add(3,4). The calls will happen in this order:

add(3,4)
add(2,4)
add(1,4)
add(0,4)

That's where we hit our base case. Now, this final call will return 4; but obviously 3+4 is not 4. This is where the "magic backwards wrap-up" happens, only it's not magic. The program simply remembers what calculation needs to be done at each stage because you told it in the return value. So, starting at the bottom, we work our way back up:

add(0,4) returns 4;
add(1,4) returns the result of add(0,4)+1 which is 5
add(2,4) returns the result of add(1,4)+1 which is 6
add(3,4) returns the result of add(2,4)+1 which is 7

*EDIT: accidentally mistyped add(3,4) as add(1,4) above

We've reached the top, and now we have our answer. The wrap-up works because the program remembers where it was when it moves from function to function. add(1,4) calls add(0,4), for instance, but the program remembers that once it has the result from add(0,4), it still has to add 1 to it before it has the result for add(1,4).

1

u/RenewAi Apr 05 '22

The program simply remembers what calculation needs to be done at each stage because you told it in the return value.

Thank you for taking the time to reply to me.

That's the exact part that messes me up. Where do is store that info? Like what data structure and where can I see it?

I would like to be able to print the stuff in that step but I never figured out how.

I've compensated for not being able to use recursion by just getting good at iterative solutions using stacks, but it still bothers me to have a gray area lol

2

u/Technologenesis Apr 05 '22

That would be a stack! Specifically the "call stack". Ever noticed how when your program crashes, it shows you all the functions that were called to get to where the crash happened? That's the call stack. Most programming language don't expose the call stack for you to access from the program itself, but under the hood that's what's happening. Every time you call a function, the program remembers where it left off before jumping to that function.

2

u/RenewAi Apr 05 '22

Oh awesome, i'm just gonna figure out how to print out the call stack in a few examples and I think it'll fully click.

Not seeing that really throws me off more than it should lol

I think I actually pretty much get it at this point, just from know the call stack exists!

0

u/[deleted] Apr 05 '22

[deleted]

1

u/RenewAi Apr 05 '22

Thanks for taking the time to reply to me, i'm gonna read over this in a bit.

1

u/ExtraFig6 Apr 06 '22

magic wrap up backwards thing that does all the calculations.

The last bit of recursion has stumped me for years. It just doesn't work with my brain

It does the same thing when you call a different function btw. Are you familiar with callstacks?