官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 新闻| 孝义市| 土默特左旗| 长兴县| 贵溪市| 永安市| 双城市| 柏乡县| 尉犁县| 黔江区| 如皋市| 肃宁县| 玛沁县| 青川县| 九江市| 大兴区| 江孜县| 新和县| 县级市| 报价| 营口市| 大渡口区| 巴林左旗| 汝城县| 乌鲁木齐市| 望城县| 安康市| 上高县| 淄博市| 池州市| 信宜市| 南雄市| 中江县| 印江| 永吉县| 乌苏市| 永年县| 鹤岗市| 内乡县| 古浪县| 西峡县|