Python generator solution using yield from


  • 0
    W

    Using generator can be useful. Because of the recursive nature of nestedList, we need to use yield from clause. It seems that OJ forbids yield from clause in python, but anyways I think it is a decent solution.

    def __init__(self, nestedList):
        def gen(L):
            for i in L:
                if i.isInteger():
                    yield i.getInteger()
                else:
                    yield from gen(i.getList())
        def count(L):
            c = 0
            for i in L:
                if i.isInteger():
                    c += 1
                else:
                    c += count(i.getList())
            return c
        self.size = count(nestedList)
        self.used = 0
        self.it = gen(nestedList)
    
    def next(self):
        next(self.it)
        self.used += 1
    
    def hasNext(self):
        return self.used < self.size

Log in to reply
 

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