- 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.
- 微信公眾平臺(tái)與小程序開發(fā):從零搭建整套系統(tǒng)
- 深度學(xué)習(xí)經(jīng)典案例解析:基于MATLAB
- Programming ArcGIS 10.1 with Python Cookbook
- Java虛擬機(jī)字節(jié)碼:從入門到實(shí)戰(zhàn)
- YARN Essentials
- Visual Basic學(xué)習(xí)手冊(cè)
- Python機(jī)器學(xué)習(xí):手把手教你掌握150個(gè)精彩案例(微課視頻版)
- 快人一步:系統(tǒng)性能提高之道
- MATLAB 2020從入門到精通
- 精通Python自動(dòng)化編程
- 微信小程序全棧開發(fā)技術(shù)與實(shí)戰(zhàn)(微課版)
- 從零開始學(xué)UI:概念解析、實(shí)戰(zhàn)提高、突破規(guī)則
- INSTANT Apache Hive Essentials How-to
- 軟件測(cè)試(慕課版)
- 你好!Java