- Python Data Structures and Algorithms
- Benjamin Baka
- 261字
- 2021-07-09 19:44:59
Recursive functions
Recursion is one of the most fundamental concepts of computer science. In Python, we can implement a recursive function simply by calling it within its own function body. To stop a recursive function turning into an infinite loop, we need at least one argument that tests for a terminating case to end the recursion. This is sometimes called the base case. It should be pointed out that recursion is different from iteration. Although both involve repetition, iteration loops through a sequence of operations, whereas recursion repeatedly calls a function. Both need a selection statement to end. Technically, recursion is a special case of iteration known as tail iteration, and it is usually always possible to convert an iterative function to a recursive function and vice versa. The interesting thing about recursive functions is that they are able to describe an infinite object within a finite statement.
The following code should demonstrate the difference between recursion and iteration. Both these functions simply print out numbers between low and high, the first one using iteration and the second using recursion:

Notice, iterTest, the iteration example, we use a while statement to test for the condition, then call the print method, and finally increment the low value. The recursive example tests for the condition, prints, then calls itself, incrementing the low variable in its argument. In general, iteration is more efficient; however, recursive functions are often easier to understand and write. Recursive functions are also useful for manipulating recursive data structures such as linked lists and trees, as we will see.
- 微服務與事件驅動架構
- 軟件界面交互設計基礎
- Scala Design Patterns
- 跟小海龜學Python
- Python Tools for Visual Studio
- Cassandra Design Patterns(Second Edition)
- NGINX Cookbook
- Mastering Linux Security and Hardening
- 打開Go語言之門:入門、實戰與進階
- Django實戰:Python Web典型模塊與項目開發
- SQL Server 2008中文版項目教程(第3版)
- 零基礎看圖學ScratchJr:少兒趣味編程(全彩大字版)
- C語言程序設計實踐
- 數字媒體技術概論
- HTML5與CSS3權威指南