fact2.md 1.0 KB
Newer Older
F
feilong 已提交
1 2 3 4 5
# Python 函数递归(1)

使用函数递归的方式可以方便的写出阶乘计算。

```python
F
feilong 已提交
6
# -*- coding: UTF-8 -*-
F
feilong 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

# TODO(You): 请实现递归计算阶乘

if __name__ == '__main__':
    print(fact(998))
```

请选出下面的 Python 递归阶乘实现代码中,<span style="color:red">错误</span> 的选项。

## template

```python
def fact(n):
    if n == 1:
        return 1
    return n*fact(n-1)


if __name__ == '__main__':
    print(fact(998))
```

## 答案

```python
def inner_fact(n, m, r):
    if m == n:
        return r
    return inner_fact(n, m+1, r*m)


def fact4(n):
    return inner_fact(n, 1, 1)
```

## 选项

### A

```python
def fact(n):
    if n == 1:
        return 1
    return n*fact(n-1)
```

### B

```python
def inner_fact(n, r):
    if n == 1:
        return r
    return inner_fact(n-1, r*n)


def fact(n):
    return inner_fact(n, 1)
```

### C

```python
def inner_fact(n, m):
    if m == n:
        return n
    return m*inner_fact(n, m+1)

def fact(n):
    return inner_fact(n,1)
```