RecursionError: maximum recursion depth exceeded while calling a Python object
请参见最后几步的输出:
...
age 990 age 991 age 992 age 993 age 994 age 995 Traceback (most recent call last): [Previous line repeated 993 more times] File "C:\Users\29358\PycharmProjects\Python_workspace-main\4 ddm_course\02_Python inner function\RecursionABC.py", line 7, in deltaYear print('age',age) RecursionError: maximum recursion depth exceeded while calling a Python object
def tower_of_hanoi(n, source, auxiliary, target): if n == 1: print(f"Move disk 1 from {source} to {target}") return tower_of_hanoi(n-1, source, target, auxiliary) print(f"Move disk {n} from {source} to {target}") tower_of_hanoi(n-1, auxiliary, source, target)
# 示例用法 tower_of_hanoi(4, 'A', 'B', 'C')
输出结果:
Move disk 1 from A to B Move disk 2 from A to C Move disk 1 from B to C Move disk 3 from A to B Move disk 1 from C to A Move disk 2 from C to B Move disk 1 from A to B Move disk 4 from A to C Move disk 1 from B to C Move disk 2 from B to A Move disk 1 from C to A Move disk 3 from B to C Move disk 1 from A to B Move disk 2 from A to C Move disk 1 from B to C
C++:
cpp
#include <iostream>
void tower_of_hanoi(int n, char source, char auxiliary, char target) { if (n == 1) { std::cout << "Move disk 1 from " << source << " to " << target << std::endl; return; } tower_of_hanoi(n-1, source, target, auxiliary); std::cout << "Move disk " << n << " from " << source << " to " << target << std::endl; tower_of_hanoi(n-1, auxiliary, source, target); }
int main() { int n = 3; // 汉诺塔的盘子数 tower_of_hanoi(n, 'A', 'B', 'C'); return 0; }