简体   繁体   English

没有定义变量的空间复杂度

[英]Space Complexity with no variables defined

What is the space complexity of this code (it finds out how many negative numbers are in nested lists of integers)?这段代码的空间复杂度是多少(它找出嵌套整数列表中有多少个负数)? Is it O(1) since no variables are defined, or is it O(n) due to the list comprehensions?是 O(1) 因为没有定义变量,还是 O(n) 由于列表推导?

def foo(forest: list[list[int]]) -> int:
    return sum([1 for tree in forest for leaf in tree if leaf<0])

Just to confirm as well, this program has a time complexity of O(n 2 ) right?还要确认一下,这个程序的时间复杂度是 O(n 2 ) 对吗?

Thanks!谢谢!

First, what is the n here?首先,这里的n是什么?

I think there are two different variables of importance here, I'll call them M = len(forest) and K = max(len(tree) for tree in forest) .我认为这里有两个不同的重要变量,我将它们称为M = len(forest)K = max(len(tree) for tree in forest)

Then the time complexity would be O(MK).那么时间复杂度就是 O(MK)。

Next, the list you are constructing has a length of O(MK), so its space complexity is the same as the time complexity.接下来,您正在构建的列表的长度为 O(MK),因此其空间复杂度与时间复杂度相同。

You can avoid that by using a generator expression instead of a list comprehension, like so:您可以通过使用生成器表达式而不是列表理解来避免这种情况,如下所示:

return sum(1 for tree in forest for leaf in tree if leaf < 0)

This avoids having to store every value, only generating a single value at a time when calculating the sum, so its additional space complexity would be O(1).这避免了必须存储每个值,在计算总和时一次只生成一个值,因此其额外的空间复杂度将是 O(1)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM