Bug in Weekly Contest Q4 with generator (Python)
84
Sep 12, 2021
Sep 12, 2021

Can someone please help me understand why unpacking the generator object "intervals" with list comprehension gets the correct answer (but TLE), but unpacking it in the for loop gets WA (but not TLE)?

I'm thinking it's an OOP bug, but I really don't understand.

Here's the problem: https://leetcode.com/problems/smallest-missing-genetic-value-in-each-subtree/

class Solution:
    def smallestMissingValueSubtree(self, parents: List[int], nums: List[int]) -> List[int]:
        d = defaultdict(list)
        N = len(parents)
        ans = [0 for x in range(N)]
        
        for i in range(N):
            d[parents[i]].append(i)        
        
        def go(node):
            intervals = [[nums[node], nums[node]]]
            heapify(intervals)
                        
            for child in d[node]:
                intervals = merge(intervals, go(child))
            
            #######why does unpacking the generator give the right answer???
            #with the line below this I get the correct answer, but too slow
            #without the line below I get WA
            intervals = [[x[0], x[1]] for x in intervals]
            
            out = []
            curry = 0
            currx = 1
            mini = None
            for x, y in intervals:
                if x == curry + 1:
                    curry = y
                else:
                    if not mini:
                        mini = curry + 1
                    out.append([currx, curry])
                    currx = x
                    curry = y
                    
            if not mini:
                mini = curry + 1
            
            ans[node] = mini
            
            return intervals
            
        go(0)
        return ans
		```
Comments (0)