heretoinfinity
heretoinfinity

Reputation: 1746

Expansion of list comprehension leading to infinite loop in listing power sets

I have been trying to solve the problem of listing power sets on Question 78 on Leetcode. I ran into a solution that uses list comprehensions and it works. I tried expanding it and following through with the Python documentation to make sure I get the correct syntax but I seem to be getting into an infinite loop.

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

The code in the solution is:

    def subsets(nums):
        nums.sort()
        result = [[]]
        for num in nums:
            result += [i + [num] for i in result]
        return result 

The code with my change is:

  def subsets(nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    result = [[]]

    for num in nums:
      for list_ in result:
        result.append([num] + list_)
    return result

I think that in each iteration of the for list_ in result: loop, the result is getting bigger and so I wouldn't get to the end of it but why is it not the same case with the list comprehension? What am I missing?

Upvotes: 0

Views: 338

Answers (1)

juvian
juvian

Reputation: 16068

Because first [i + [num] for i in result] is resolved, and then once that is computed, the result += part happens, which is different from yours where you append 1 by 1. The other solution appends all at once so there is no issue

Upvotes: 3

Related Questions