python中階乘函數的空間複雜度應該是多少?python中簡單階乘函數的空間複雜度
def fact(n):
product = 1
for i in range(2, n+1):
product = product * i
return product
此相同的想法在其它語言如C將導致O(1)的空間複雜性,但對於本實施例中會範圍(2,N + 1)導致的O(n)的空間複雜度的空間複雜度?
python中階乘函數的空間複雜度應該是多少?python中簡單階乘函數的空間複雜度
def fact(n):
product = 1
for i in range(2, n+1):
product = product * i
return product
此相同的想法在其它語言如C將導致O(1)的空間複雜性,但對於本實施例中會範圍(2,N + 1)導致的O(n)的空間複雜度的空間複雜度?
在py2.x中range
返回一個列表,所以你的for循環實際上遍歷該列表。就內存而言它是O(N)
。
您可以使用xrange
這裏一次返回一個項目。
幫助上xrange
:
xrange(start, stop[, step]) -> xrange object
Like range(), but instead of returning a list, returns an object that
generates the numbers in the range on demand. For looping, this is
slightly faster than range() and more memory efficient.
這也取決於它的Python你使用。
在Python 3,範圍爲發電機,像老的xrange在python 2.
因此,如果您使用python 2.
使用的xrange代替範圍 – SheetJS
使用這將是O(n)的如果您使用的是'python2'或'python3',則分別使用'xrange'或'range'。對於n> 20,n! – rnbcoder
不適合64位整數。因此,變量「產品」的空間複雜性根本不是恆定的,並且不會遠離O(n)。 – Sebastien