Advanced Programming Concepts and Recursion
Algorithms, Programming, and Data Representation · Module 92313 · Chapter 7a
This guide connects memory models, type systems, abstraction, resource ownership, and compilation across C++ and Python, then develops recursion and induction as tools for program design and proof.
Start from memory
Try each question first. Mark it sure, unsure, or guessed.
- What does a Python variable name refer to?
- How does static typing differ from dynamic typing?
- What does a C++ destructor do in RAII?
- What two pieces make a recursive definition terminate?
- What does a phi-node represent in SSA?
Check the short answers
- A name is bound to an object; assignment usually binds another name to the same object. §7.1
- Static type checks happen before execution; dynamic type checks happen as operations run. §7.2
- It releases resources when the owning object’s lifetime ends. §7.4
- A base case and a recursive call that strictly reduces a well-founded measure. §7.6
- It merges values arriving from different control-flow branches. §7.5
How to use this guide
Compare the languages by tracing what each name, object, and call means. For recursion, write the base case and decreasing measure before tracing any calls.
- Day 0: Study §7.1–7.2; solve practice 1–4.
- Day 1: Rebuild §7.3–7.4 from memory; solve practice 5–9.
- Day 3: Study §7.5 and trace compiler stages; solve practice 10–13.
- About day 7: Rebuild §7.6–7.7 and solve practice 14–20.
- About day 14: Complete both exam problems without notes and answer the “Explain it” questions aloud.
- Before the exam: Tick only skills you can demonstrate cold; revisit missed-answer references.
When stuck: state the language and its rules first. For memory, draw names and objects separately. For recursion, trace calls down, returns up, and show the measure decreases.
How the chapter fits together
Programming-language rules shape where values live, how operations are checked, and when resources are released. Abstraction hides details behind interfaces; compilation transforms source through intermediate forms. Recursion applies the same idea of smaller subproblems to algorithms, while induction supplies a matching correctness proof.
Measure · locate values and rules
Names, objects, and lifetime §7.1
name → objectRests on: binding and the runtime’s storage model.
Type rules and dispatch §7.2
check early ↔ check at runtimeRests on: values, operations, and their supported interfaces.
Define · manage change
Interfaces and encapsulation §7.3
public contract · private choiceRests on: separating observable behaviour from implementation.
Ownership and reclamation §7.4
acquire → use → releaseRests on: object lifetime and resource ownership.
Derive · execute and prove
Compilation and SSA §7.5
source → IR → machine codeRests on: syntax, type rules, and control flow.
Recursive reduction and proof §7.6–7.7
base + smaller case + combineRests on: call frames, a decreasing measure, and induction.
| Question | Tool |
|---|---|
| Why did changing one list name affect another? | Draw the names pointing to a shared mutable object (§7.1). |
| When is a type error detected? | Identify static checks, runtime checks, or an external type checker (§7.2). |
| Who releases a resource? | Trace its owner and lifetime (§7.4). |
| Will recursion stop and return the right result? | Prove a decreasing measure and match the code to induction (§7.6–7.7). |
7.1 Memory models and variables
A program manipulates names, values, and objects. Distinguishing them explains aliasing, lifetimes, and the different abstractions exposed by C++ and Python.
In plain words: a name is how code refers to a value or object. In Python, assignment binds a name to an object; two names can refer to the same mutable object. C++ assignment to an ordinary value usually copies it, while a reference or pointer can provide another route to an object.
b = a binds b to the object currently named by aRead it as: “b now refers to the same object as a”. Mutating that shared list is visible through either name; rebinding one name does not rebind the other.Worked trace · shared list
a = [1, 2]creates a list object and bindsato it.b = abindsbto that same list; there are still two names and one list.b.append(3)mutates the list, so both names observe[1, 2, 3].b = [9]rebindsb; now the names refer to different lists.
C++ examples often describe automatic local objects as “on the stack” and dynamic allocations as “on the heap”. These are useful implementation pictures, not a language guarantee that every local occupies a hardware stack. In Python, object storage is managed by the implementation; call frames hold local bindings. Do not infer exact physical placement from the source syntax.
In C++, a pointer stores an address and can be null or invalid; dereferencing an invalid pointer is undefined behaviour. A reference aliases an existing object and cannot be reseated. Python hides raw addresses and pointer arithmetic from ordinary code.
Trap: assignment is not always a deep copy. Check whether the operation copies a value, copies a reference, or mutates an object.
Near miss: two variables holding equal lists need not share one list. Equality compares contents; identity asks whether they are the same object.
Draw names, objects, and aliases in the lab
Recall check · §7.1
- After
b = afor a Python list, how many list objects are there? - Does the phrase “local variables are on the stack” state a portable C++ guarantee?
Check these answers
- One list object, referenced by both names.
- No. It is a common implementation model, not a language guarantee.
7.2 Types and polymorphism
A type system determines which operations are permitted and when errors are detected. Polymorphism lets one piece of code work with different values through shared operations.
In plain words: static typing checks types before a program runs; dynamic typing checks what an operation can do at runtime. Neither means that a language has no type rules.
C++ is statically typed: an expression’s type is established before execution, with limited inference such as auto. Python is dynamically and strongly typed: names can be rebound to values of different types, but incompatible operations still raise errors. Type annotations in Python are primarily for tools and documentation; Python itself does not generally enforce them.
In ad-hoc polymorphism, overloaded functions or operators select among implementations. Parametric polymorphism uses a generic definition, such as a C++ template. Subtype polymorphism lets a derived object be used through a base interface; C++ uses virtual for dynamic dispatch, while Python methods dispatch dynamically by default. Duck typing asks whether an object supports the needed operations, rather than requiring a declared parent class.
Type inference derives types without spelling them out. C++ deduces some types locally; Hindley–Milner systems infer more general types. A Python type checker can infer and check annotations statically, but this is an external analysis rather than Python runtime enforcement.
Trap: “dynamic” does not mean “untyped”, and a Python annotation does not by itself reject a wrong value at runtime.
Near miss: two objects with a speak() method can be used by duck typing even if neither inherits from Animal; the shared operation, not ancestry, makes the call work.
Compare dispatch and type checks in the lab
Recall check · §7.2
- Which polymorphism form uses a single generic definition?
- Does Python enforce a type hint on every call?
Check these answers
- Parametric polymorphism.
- No. External tools may check hints; normal Python execution does not generally enforce them.
7.3 Abstraction and encapsulation
A stable interface lets a component change internally without forcing every caller to change. Encapsulation groups state with the operations that preserve its rules.
In plain words: abstraction presents the useful operation and hides incidental detail. Encapsulation keeps related state and methods together; information hiding limits which implementation details callers should rely on.
C++ access specifiers (public, protected, private) are enforced by the compiler; a class defaults to private members while a struct defaults to public. Python relies more on convention: a leading underscore signals internal use. Double-leading underscores trigger name mangling to reduce accidental clashes; they do not make an attribute inaccessible to determined code.
Modules and packages organize code. Python modules are files; package behavior includes regular packages with __init__.py and namespace packages that may omit it. __all__ affects wildcard imports, not whether a name can be accessed directly. C++ headers declare interfaces and source files commonly contain definitions; namespaces organize names, while unnamed namespaces or internal linkage can limit visibility.
Python permits runtime introspection and monkey patching, which can help testing but can make invariants harder to maintain. C++ class layout and declarations are generally fixed by compilation, though dynamic libraries and polymorphism still allow runtime extension through designed interfaces.
Trap: do not present Python’s double underscore as a security boundary.
Near miss: placing a leading underscore on a name documents “internal”; it does not stop another module from importing or reading it.
Classify interface and implementation choices in the lab
Recall check · §7.3
- What does Python name mangling do?
- What does
__all__control?
Check these answers
- It rewrites a double-leading-underscore attribute name within a class to reduce accidental clashes; it is not access protection.
- The names imported by
from module import *.
7.4 Memory management
Allocated memory and other resources need clear ownership and a release point. The language’s memory model determines which mistakes it can prevent automatically.
In plain words: manual memory management makes the programmer responsible for releasing allocations. Automatic reclamation finds objects that are no longer reachable. RAII ties a resource’s lifetime to an owning C++ object.
In C, malloc/free pair allocation and release; in C++, new/delete exist, but modern C++ usually prefers automatic objects and standard containers. RAII releases resources in destructors when scope ends, including during exception unwinding. std::unique_ptr expresses exclusive ownership; std::shared_ptr shares reference-counted ownership; std::weak_ptr can observe shared objects without keeping them alive and can break ownership cycles.
CPython primarily uses reference counting and supplements it with cyclic garbage collection. Other Python implementations may use different strategies. Unreachable cycles can be reclaimed, but objects retained by live references are not garbage. Garbage collection does not replace deterministic cleanup for files or sockets; use context managers such as with open(...).
Common manual-management errors include leaks, dangling pointers, double frees, and out-of-bounds writes. Automatic collection reduces some lifetime errors but cannot prevent all memory growth or resource misuse.
Trap: a garbage collector cannot free an object that remains reachable through a live reference.
Near miss: two shared_ptr objects can keep each other alive in a cycle; reference counting alone cannot reduce either count to zero.
Trace ownership and reclamation in the lab
Recall check · §7.4
- What lifetime does RAII attach resource cleanup to?
- Why can a shared-ownership cycle resist reference counting?
Check these answers
- The lifetime of the owning object; its destructor releases the resource.
- Each object’s reference count is kept above zero by the other.
7.5 Compilation and execution
Source code is transformed into forms a runtime or processor can execute. Intermediate representations make analysis and optimization easier.
In plain words: a compiler translates a program. An interpreter executes instructions under a runtime. Many real systems combine both, so “compiled versus interpreted” is a spectrum rather than a clean divide.
CPython compiles source to bytecode and its virtual machine executes that bytecode; .pyc files cache compiled code for imports. The bytecode format and runtime details can vary by version and implementation. PyPy uses a tracing JIT for hot paths; Cython can compile selected Python-like code to native extensions.
Static Single Assignment form gives each assigned variable a single definition by creating versions such as x1 and x2. At a control-flow join, a phi-function selects the version supplied by the path taken. The phi is an intermediate representation concept, not necessarily a machine instruction.
Worked merge · SSA
- Start with
x1 = a + b. - If
c > 0, definex2 = x1 + c; otherwise definex3 = x1 − c. - At the join,
x4 = phi(x2, x3)represents the value from the branch that ran. - Use
x4in the following expression.
Trap: Python is not simply “interpreted without compilation”; bytecode compilation is part of ordinary execution.
Near miss: source-level variable x may be assigned more than once, but SSA creates a distinct version for each assignment.
Follow compilation stages and an SSA merge in the lab
Recall check · §7.5
- What problem does a phi-function solve?
- Does a
.pycfile contain native machine code?
Check these answers
- It represents the value selected from different predecessor branches at a control-flow join.
- No. It contains Python bytecode for the relevant implementation and version.
7.6 Recursion and termination
Recursion expresses a solution through smaller instances. A correct design must both reach a directly solved case and return the intended result.
In plain words: every recursive function needs base case(s) and a recursive step that reduces the problem. A well-founded measure, such as a non-negative integer, proves there cannot be an infinite descending chain.
fact(0) = 1fact(n) = n × fact(n − 1) for integer n > 0Read it as: “zero factorial is one; otherwise multiply n by the factorial of one less”.The measure is n; this definition’s stated domain is the non-negative integers.Worked trace · fact(3)
- Calls descend:
fact(3) → fact(2) → fact(1) → fact(0). - The base call returns 1.
fact(1)returns 1;fact(2)returns 2;fact(3)returns 6.- Each waiting call has its own arguments and pending multiplication in its call frame.
With multiple recursive branches, each must reduce a suitable measure. Naive Fibonacci revisits subproblems; memoization stores results so each distinct input is solved once, aside from dictionary and output costs.
F(0)=0, F(1)=1F(n)=F(n−1)+F(n−2) for n≥2Read it as: “each term from n=2 is the sum of the two preceding terms”.The lecture’s code returns n for n≤1; adding a cache avoids recomputing overlapping calls.Recursion suits trees and divide-and-conquer: solve smaller inputs and combine results. Backtracking explores choices depth-first and returns when a branch cannot succeed. In mutual recursion, one measure must decrease across the call cycle. Iteration makes state explicit and can avoid call overhead and stack growth. Primitive recursion restricts recursion form; general recursion is more expressive, as Ackermann’s function illustrates.
Trap: a base case does not guarantee termination if some path skips it or fails to reduce the measure.
Near miss: the call f(n) inside f(n) is recursive syntax but gives no progress toward termination.
Trace recursive calls and prove progress in the lab
Recall check · §7.6
- What measure proves the factorial calls terminate?
- Why is naive Fibonacci inefficient?
Check these answers
- The non-negative argument n strictly decreases to zero.
- It recomputes many identical subproblems; memoization can reuse completed values.
7.7 Induction and recursive algorithms
Induction proves statements about every input size or recursively built structure. Its assumptions mirror how a recursive algorithm uses results for smaller cases.
In plain words: weak induction uses the immediately preceding case; strong induction may use any smaller case; structural induction follows the constructors of a recursive structure.
Worked proof · triangular numbers
- Claim: 1 + … + n = n(n + 1)2 for
n ≥ 1. - Base
n=1: both sides equal 1. - Assume
1 + … + k = k(k+1)/2. - Add
k+1:k(k+1)/2 + (k+1) = (k+1)(k+2)/2. - This is the claim for
k+1, so induction proves it for everyn ≥ 1.
Weak induction assumes the immediately smaller case; strong induction may assume all smaller natural numbers; well-founded induction generalizes this to any relation with no infinite descending chain. The Ackermann function is a classic total computable function that is not primitive recursive. Under the lecture’s recurrence, A(4,1)=65,533, and A(4,2)=265,536−3, which has 19,729 decimal digits. General recursion, lambda-definability, and Turing computability describe equivalent classes of effectively computable functions; practical runtimes still impose resource limits.
Trap: when proving a recursive algorithm, match each code base case to a proof base and each recursive branch to the induction assumption it uses.
Near miss: “the result is true for k, so it is true for k+1” omits the algebra or program step that connects the two cases.
Match recursive code to an induction proof in the lab
Recall check · §7.7
- What does the induction step assume and what does it prove?
- Does Python optimize tail calls?
- How many decimal digits does the lecture’s
A(4,2)have?
Check these answers
- Assume the statement for a smaller case k and prove it for k+1.
- No. Python retains the call frames and enforces a recursion limit.
- 19,729 digits, since
A(4,2)=265,536−3.
Formula map and units
| Rule | Meaning |
|---|---|
name → object | Python name binding; assignment does not imply a deep copy |
| RAII: resource lifetime = owner lifetime | Destructor releases owned resources at object lifetime end |
n! = n × (n−1)!; 0! = 1 | Factorial recursion for non-negative integer n |
1+…+n = n(n+1)/2 | Triangular-number identity, n ≥ 1 |
A(4,2) = 265,536−3 | Lecture’s Ackermann variant; 19,729 decimal digits |
Check every answer: state the language and implementation assumptions; distinguish names, objects, and copies; identify the owner of every resource; trace every recursive path to a base case; align each proof assumption with the smaller case actually used.
Derive it cold
- Draw the bindings and list object before and after mutation and rebinding. §7.1
- Classify overloads, templates, subtype dispatch, and duck typing by their polymorphism form. §7.2
- Trace one resource from acquisition through RAII destruction or smart-pointer release. §7.4
- Show how two branch values meet at an SSA phi-function. §7.5
- Expand
fact(3)to the base case, unwind returns, and name its decreasing measure. §7.6 - Prove the triangular-number formula by induction. §7.7
- Compute
A(4,1)andA(4,2)from the stated recurrence. §7.7
Explain it
- Why can two Python names show a change made through either name?
- Why is stack versus heap often a useful picture but not a source-level guarantee?
- How do ad-hoc, parametric, and subtype polymorphism differ?
- Why is Python name mangling not privacy enforcement?
- How does RAII release resources during exception handling?
- What does a phi-function represent at an SSA control-flow join?
- Why do Fibonacci’s recursive branches need a cache for efficiency?
- Why does tail recursion still use stack space in Python?
Show model answers
- Assignment binds both names to the same mutable object, so mutation is visible through either reference. §7.1
- Compilers and runtimes choose physical storage; language rules specify behavior, not a required hardware stack layout. §7.1
- Separate implementations by operation/type; one generic implementation; or a derived value used through a parent interface. §7.2
- Name mangling changes the stored attribute spelling to avoid accidental clashes but can be accessed deliberately. §7.3
- Scope exit destroys the owner, and its destructor releases its resources even during stack unwinding. §7.4
- It selects the value produced by the predecessor branch that reached the join. §7.5
- Naive recursion recomputes overlapping subproblems; a cache stores completed answers for reuse. §7.6
- Python does not optimize tail calls; each call retains a frame until it returns. §7.7
Mixed practice
Try all 24 problems before opening the answers. State assumptions, draw intermediate states, and justify each result.
- After
a=[1];b=a;b.append(2), what doesacontain? - Classify a C++ function template as ad-hoc, parametric, or subtype polymorphism.
- What does Python’s
__all__affect? - Why can a pair of shared owners cause a reference-counted cycle?
- Put lexing, parsing, semantic analysis, IR, optimization, and code generation in a typical order.
- Give a decreasing measure for factorial on non-negative integers.
- State the base and induction step for proving
1+…+n=n(n+1)/2. - Does
b=a.copy()make a nested list independent at every level? - Classify a virtual method call through a base pointer.
- Can another Python module deliberately access a double-underscore class attribute?
- How does RAII close a file if an exception exits the function?
- What does a phi-function select?
- Trace the return values of
fact(3). - In structural induction on a binary tree, what are the base and step cases?
- Is
int xguaranteed to occupy a physical stack slot in C++? - Does Python’s dynamic typing mean it permits
5 + "hi"? - What access level do members of a C++
classhave by default? - Why must a file still be closed deliberately in Python even though it has garbage collection?
- Does CPython compile source to bytecode before executing it?
- Why is naive Fibonacci exponential while memoized Fibonacci has linear distinct subproblems?
- Under the lecture recurrence, calculate
A(4,1). - For
fact_tail(4,1), what accumulator reaches the base case? - How many decimal digits does
A(4,2)=265,536−3have? - Will Python eliminate the tail-recursive frames?
Show the answers
[1, 2]; both names refer to the mutated list. §7.1- Parametric polymorphism. §7.2
- The names included in
from module import *. §7.3 - Each object’s count is kept positive by the other object’s owning reference. §7.4
- Lexing → parsing → semantic analysis → IR generation → optimization → code generation. §7.5
nstrictly decreases until zero. §7.6- Base n=1; assume the formula for k, then add k+1 and simplify to (k+1)(k+2)2. §7.7
- No. A shallow copy duplicates the outer list but can still share its nested objects. §7.1
- Subtype polymorphism with dynamic dispatch. §7.2
- Yes, by using the mangled name; this is not an access-control boundary. §7.3
- The file object is destroyed during scope exit and its destructor closes the resource. §7.4
- The incoming value from the control-flow branch that executed. §7.5
- Calls: 3,2,1,0; returns: 1,1,2,6. §7.6
- Base: Empty. Step: assume the property for both children and prove it for Node(v,L,R). §7.7
- No. That is a common implementation model, not a C++ guarantee. §7.1
- No; it is dynamically typed but strongly typed, so this unsupported operation raises
TypeError. §7.2 - Private. §7.3
- Garbage collection timing is not a reliable resource-lifetime policy; use a context manager. §7.4
- Yes, normal CPython execution uses compiled bytecode and a virtual machine. §7.5
- Naive recursion recalculates shared subproblems; caching computes each argument once, with constant work per cached entry. §7.6
A(4,0)=A(3,1)=13; thenA(4,1)=A(3,13)=2^16−3=65,533. §7.724. §7.62^65,536has 19,729 digits; subtracting 3 does not change the digit count. §7.7- No. Python retains frames and has a recursion limit. §7.7
Exam-style problems
1 · References, lifetime, and abstraction · 20 minutes
Compare this Python code with a C++ object that owns a file handle.
- Trace
a=[1,2]; b=a; c=a[:]; b.append(3). State the values and identities. (4 marks) - Explain why a Python object is not simply “a value stored in the stack slot of its variable”. (3 marks)
- Describe how RAII releases the C++ file handle on normal return and exception exit. (3 marks)
- Explain why a Python double-underscore attribute is not equivalent to a C++ private member. (2 marks)
Show worked answer
aandbrefer to the same list, now[1,2,3].cis a shallow copy of the outer list and remains[1,2]; the lists are distinct. §7.1- Python names are bindings to objects managed by the runtime. Physical layout depends on the implementation; a call frame holds local bindings, and the language does not expose ordinary raw pointer arithmetic. §7.1
- The owning automatic object is destroyed when its scope exits. Its destructor closes the handle, including during exception unwinding. §7.4
- C++ private access is checked by the compiler. Python name mangling changes a name to reduce accidental clashes but deliberate access remains possible. §7.3
2 · Termination and correctness · 20 minutes
Consider recursive flattening of a nested list, and the triangular-number formula.
- Define a measure that decreases for recursive flattening and give its base case. (3 marks)
- State a structural induction proof shape for correctness on a nested list. (3 marks)
- Prove
1+…+n=n(n+1)/2by induction for n≥1. (4 marks) - Explain why tail-recursive factorial can still hit Python’s recursion limit. (2 marks)
Show worked answer
- Use the number of nested list nodes or total number of elements remaining. Empty list returns empty list; each recursive branch handles a proper sublist or advances past an element. §7.6
- Base: empty input flattens to empty. Step: assume the recursive result is correct for each nested sublist; concatenating scalar elements and those results in order gives the correct flattening. §7.7
- Base n=1 gives 1=1·22. Assume the formula for k. Then the next sum is k(k+1)2+(k+1)=(k+1)(k+2)2, the formula for k+1. §7.7
- Python does not guarantee tail-call optimization, so every recursive call keeps a frame until it returns. §7.7
Slips in the notes
These corrections were checked against the rendered lecture slides and the stated examples.
- Slide 29, monkey-patching example. The displayed assignment
SomeClass.newmethod=lambda self: …is malformed Python. A valid method assignment needs a function definition or a compatible callable, and the formatting should preserve its body. §7.3 - Slide 67, Ackermann digit count. The slide says
A(4,2)is on the order of10^19,000digits. For the displayed recurrence,A(4,2)=2^65,536 − 3, which has 19,729 decimal digits (about 20,000 digits), not 10^19,000 digits. §7.7
Self-check
Tick a skill only in a later session, at least one day after studying, when you can demonstrate it without notes.
Personal study guide based on “lecture7a.pdf” (70 slides, 8 November 2025), written in my own words; no lecture pages or figures are reproduced. Not an official FAU publication; check course details against the current notes. Made by Thanate Amornjiraporn (Focus).