Python solution following correct pattern


  • 0
    V

    I have looked at a bunch of solutions that don't seem to conform to the proper pattern. I believe this is the correct pattern for iterators (at least in Python). You can call hasNext() any amount of times and get the same result (in other words it is idempotent). Also, next() by convention should raise StopIteration if you're trying to get next and there's nothing left.

    class Vector2D(object):
    
        def __init__(self, vec2d):
            """
            Initialize your data structure here.
            :type vec2d: List[List[int]]
            """
            self.vec2d = vec2d
            self.arr_ptr = 0
            self.sub_arr_ptr = 0
            self.next_tuple = None
            
    
        def next(self):
            """
            :rtype: int
            """
            if self.hasNext():
                row, col = self.next_tuple
                val = self.vec2d[row][col]
                self.next_tuple = None
                return val
                    
            else:
                raise StopIteration()
            
    
        def hasNext(self):
            """
            :rtype: bool
            """
            if self.next_tuple is not None:
                return True
            
            while self.arr_ptr < len(self.vec2d):
                while self.sub_arr_ptr < len(self.vec2d[self.arr_ptr]):
                    self.next_tuple = (self.arr_ptr, self.sub_arr_ptr)
                    self.sub_arr_ptr += 1
                    return True
                self.sub_arr_ptr = 0
                self.arr_ptr += 1
               
            return False
         
    

Log in to reply
 

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