Module: (Python) Subroutines. recursion


Problem

1/12

Recursion. What is this?

Theory Click to read/hide

Recursion

A procedure or function may contain a call to another procedure within it. Including, the subroutine can call itself. In this case, the computer doesn't care. He also, as always, consistently executes the commands that he met from top to bottom.

If you remember mathematics, then there you can meet the principle of mathematical induction. It is as follows:
some statement is true for every natural n if
    1. it is valid for n = 1 and
    2. from the validity of the statement for any arbitrary natural n = k it follows that it is true for n = k + 1.

In programming, this technique is called recursion.
 
Recursion is a way of defining a set of objects in terms of the set itself, based on given simple base cases.

Recursive is a procedure (function) that calls itself directly or through other procedures and functions.
 
Example
def Rec(a):
    if (a>0): Rec(a-1)
    print(a)

Schematically, the work of recursion can be represented by a flowchart



The Rec() procedure is executed with parameter 3. Then, inside the procedure with parameter 3, the procedure with parameter 2 is called, and so on, until the procedure with parameter 0 is called. When the procedure with parameter 0 is called, the recursive call will no longer occur and the procedure with parameter 0 will print the number 0 and exit. Then control is transferred back to the procedure with parameter 1, it also finishes its work by printing the number 1, and so on. before the procedure with parameter 3. 

All called procedures are stored in memory until they complete their work. The number of concurrent procedures is called recursion depth.
 

Problem

Using the parsed procedure, add the necessary lines to the main program.
Understand why the program gives such a response.