简体   繁体   English

Python Power set,无法找出我的错误

[英]Python Power set , can't figure out my error

My code will crash and run forever: 我的代码将崩溃并永远运行:

def subsets(nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    results = [[]]
    for num in nums:
        for result in results:
            results.extend([result + [num]])
    return results 

While I googled, and find similar solution: 当我用Google搜索时,发现了类似的解决方案:

def subsets(nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    results = [[]]
    for num in nums:
        results.extend([result + [num] for result in results])
    return results

What's the difference here? 这有什么区别?

The critical part is this: 关键部分是:

for result in results:
    results.extend([result + [num]])

Here, you are iterating over the results list. 在这里,您正在遍历results列表。 An iterator is always something living, that does not finish until you actually reached the end. 迭代器永远是活的东西,直到您真正到达终点才结束。 For lists, you can simply imagine this as a pointer that starts at the first element, and then keeps going to the next until it reaches the end. 对于列表,您可以简单地将其想象为一个指针,该指针从第一个元素开始,然后一直指向下一个元素,直到到达末尾。

Except that in your case, you are adding an element (since [result + [num]] is a one-element list) to the results list on every iteration. 除非您有这种情况,否则您每次迭代都会向results列表中添加一个元素(因为[result + [num]]是一个元素列表)。 So as the iterator keeps going forward, you keep adding one element to the end making sure the iterator can never reach the end. 因此,随着迭代器的不断发展,您将向末尾添加一个元素,以确保迭代器永远不会到达末尾。

As a general rule, you should never modify the collection you are currently iterating. 通常,永远不要修改当前正在迭代的集合。 So in this case, you shouldn't modify results while you are iterating the same thing. 因此,在这种情况下,您不应在迭代同一件事时修改results

And that's exactly what the following line in that other solution avoids: 这正是该其他解决方案中避免以下行为的方式:

results.extend([result + [num] for result in results])

This uses a list comprehension and is essentially equivalent to this: 这使用列表推导,基本上等同于以下内容:

tmp = []
for result in results:
    tmp.append(result + [num])
results.extend(tmp)

As you can see, results is not modified while iterating over it. 如您所见, 迭代results不会修改results The tmp list is first created, and then once that's done, the results list is modified by extending it by the whole tmp list. 首先创建tmp列表,然后完成操作,然后通过将results列表扩展整个tmp列表来修改results列表。

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

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