Python using cache


  • 0
    W

    initialize cache so stores peeked value. So every next and peek and hasNext operation will check the cache first. If nothing in cache, just operate on the iterator.

    def __init__(self, iterator):
        self.it = iterator
        self.cache = None
    
    def peek(self):
        if self.cache:
            return self.cache
        self.cache = self.it.next()
        return self.cache    
    
    def next(self):
        if self.cache: 
            temp = self.cache
            self.cache = None
            return temp
        return self.it.next()
    
    def hasNext(self):
        if self.cache:
            return True
        return self.it.hasNext()

  • 0
    W

    Actually there is a bug in this code, but the OJ test cases did not identify the bug. You can try to identify it.

    What if the peeked value is 0? This is problematic because python treats 0 as False. Sorry about the mistake, but I think it is worthwhile to point that out.

    if self.cache ----->  if self.cache == None

Log in to reply
 

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