我的 python 函数的 space 复杂度是多少?

What is the space complexity of my python function?

谁能告诉我这个 python 函数的 space 复杂度是多少? 我相信它是 O(1),但我的朋友告诉我这是 O(N)。

他们说 O(N) 的原因: 您将在 for 循环的每次迭代中创建一个新的 'a'。

我说 O(1) 的原因:每次迭代并转储旧的 'a' 时,你都会创建一个新的 'a'。

def hello(n):
  for i in range(n):
    a = 10

如果这是伪代码,space 复杂度是否相同?

a只是一个变量,这里给a赋整数值,对于这一点,space的复杂度是O(1).

但我认为衡量的关键在于for i in range(n)声明。

python2中,因为range(n)会创建一个有n个元素的列表,所以space的复杂度是O(n)。

python3中,range(n)将return一个迭代器(不创建整个n长列表),所以space 复杂度为 O(1).