Share my Python solution with `yield`. Just for fun.


  • 1
    R

    using python keyword yield to create a generator.

    class NestedIterator(object):

    def __init__(self, nestedList):
        """
        Initialize your data structure here.
        :type nestedList: List[NestedInteger]
        """
        self._gen = self.gen(nestedList)
        self.res = None
        
    def gen(self, a):
        for x in a:
            if x.isInteger():
                yield x.getInteger()
            else:
                for y in self.gen(x.getList()):
                    yield y
                    
    def next(self):
        """
        :rtype: int
        """
        return self.res
    
    def hasNext(self):
        """
        :rtype: bool
        """
        try:
            self.res = self._gen.next()
        except Exception as e:
            return False
        return True

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.