Recursion in computer science

What is recursion?

In math, recursion is a common concept. It means that a function is defined in terms of itself. For example, the factorial function is defined:
f(n) = n * f(n-1)
f(0) = 1

f(n) is defined in terms of function f () with a smaller number n-1. f (n - 1) is defined in terms of function f (n-2), a much smaller number n-2. The process of defining can continue until f(0) is defined as the value 0.

A recursion always has 3 parts:

  1. A base case
  2. A general case
  3. Finite number of calls to reach the base case from the general case.

In the case of factorial function, the base case is f(0) = 1, the general case is f(n)=n * f(n-1). After calling the f() function with smaller number for n times, it reaches the base case f(0).

In math, a function is a relationship from a set of possible inputs to a set of possible outputs where each input is related to one output. In computer science, the term function means a sequence of statements given an identifier to perform a specific task. This looks very different from the concept of function in math. But it works in similar way: a function usually takes several parameters as input and returns a value as the output, i.e. transform the input to output. A function may call other functions to perform its task. it also can call itself. The following section shows the definition of a function and the process of calling itself to reach the base case.

Python Program

# define the function factorial
#     it takes one parameter n as input
#     it returns the factorial of n by
#       calling itself with smaller n and finally reaching the base case 0
def factorial(n):
    if 0 == n:    # the base case
        return 1
    else:
        return n * factorial(n-1)  # the general case

# call function factorial to calculate the factorial of 0
print(factorial(0))
# call function factorial to calculate the factorial of 5
print(factorial(5))
# call function factorial to calculate the factorial of 10
print(factorial(10))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值