0

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?

heretoinfinity
  • 1,528
  • 3
  • 14
  • 33
  • 1
    Yes, you should never append to a list you're iterating. You could, however, create a shallow copy of it (`results_iter = list(results)`) and iterate through it, while you append to the original `result` list. – Roberto Jun 24 '18 at 20:16
  • @Roberto, thanks for pointing an easy way of creating a shallow copy of a list. I didn't know using `list()` could be used on a list to creating a list. Other suggestions have involved importing modules. – heretoinfinity Jun 24 '18 at 20:21
  • 1
    Please don't do this: `class Solution(object):` If this is some requirement of some grading system, then strip your question down to a [mcve]. – juanpa.arrivillaga Jun 24 '18 at 20:26
  • @juanpa.arrivillaga, I removed what you requested to strip. – heretoinfinity Jun 24 '18 at 20:34

1 Answers1

3

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

juvian
  • 15,875
  • 2
  • 37
  • 38