- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
def rec():
print fact(5)
rec()
[新手提问]
Python 脚本。
这个问题想了很久,说一下我目前对递归的理解。
在rec()函数中我又调用了一个函数fact(5),现在流程转到fact(n)函数。
函数调用自身直到基本情况。
其他部分:
5 * fact( 4 )
5 * 4 * fact( 3 )
5 * 4 * 3 * fact( 2 )
5 * 4 * 3 * 2 * fact( 1 )
现在n的值变为0,返回1
我的问题是,为什么 fact(n) 函数返回 120 而不是 1。
def check(x):
if x == 1:
return 10
else:
return 20
print check(1) // Prints 10
print check(3) // Prints 20
我希望你理解我的问题。
谢谢。
最佳答案
这是计算 fact(5)
时堆栈的样子:
fact(5) = 5 * fact(4)
fact(4) = 4 * fact(3)
fact(3) = 3 * fact(2)
fact(2) = 2 * fact(1)
fact(1) = 1 * fact(0)
fact(0) = 1
# no more recursive calls, unwind the stack
fact(1) = 1 * 1 = 1
fact(2) = 2 * 1 = 2
fact(3) = 3 * 2 = 6
fact(4) = 4 * 6 = 24
fact(5) = 5 * 24 = 120
希望对您有所帮助。每个缩进都是 fact(N)
返回的内容。
关于python - 递归:为什么函数返回数字的阶乘而不是返回 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40381573/
我正在做一些关于大 O 表示法的练习题,遇到了这个问题。什么是函数 𝑓(𝑛) = 𝑛^2 + 𝑛 log2(𝑛) + log2(𝑛) 的大 O 阶。展示你的作品。 我的答案是 O(n^2)
是2n吗?只是检查。 最佳答案 术语 B 树的顺序在文献中的定义并不一致。 (例如,参见 terminology section of Wikipedia's article on B-Trees )
我想使用 numpy 创建一个 3 列数组,使得该数组类似于一堆 9x9 2 列数组。这些数组中的每一个都将完全填充有 1、2、3 等。 所以,看立方体的一面,我们看到的是 1,而另一面则是 9。然后
我想将这些数据存储到顺序为 3 (10,20,30,40,50,60,70,80,90) 的 B 树中,我的结果是 并且它与我的书的结果不匹配。可以吗?谢谢:) 最佳答案 这取决于你的意思 Is it
我是 numpy 的新手。创建一个新数组并用一定范围内的随机数填充每个元素的最佳方法是什么? 例如,我想要一个 3×3 数组,其中每个元素都是 0 或 1。 最佳答案 尝试类似的东西 np.rando
我正在尝试学习设计 btree。 以下是开发 5 阶 btree 的值。 1,12,8,2,25,6,14,28,17,7,52,16,48,68,3,26,29,53,55,45,67。 当我插入
我有一个 pandas 数据框,其特征值非常小,数量级为 -322。我正在尝试标准化这些功能,但得到了 ValueError: Input contains NaN, infinity or a va
我是一名优秀的程序员,十分优秀!