smj007

Flatten 2D vector

Aug 21st, 2025
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. class Vector2D:
  2.  
  3.     def __init__(self, vec: List[List[int]]):
  4.         self.vec = vec
  5.         # outer list
  6.         self.row = 0
  7.         # inner list
  8.         self.col = 0
  9.  
  10.     def next(self) -> int:
  11.         if not self.hasNext():
  12.             return
  13.  
  14.         val = self.vec[self.row][self.col]
  15.         self.col += 1
  16.  
  17.         # skip empty/exhausted rows right here
  18.         while (self.row < len(self.vec)) and self.col >= len(self.vec[self.row]):
  19.             self.row += 1
  20.             self.col = 0
  21.  
  22.         return val
  23.  
  24.  
  25.     def hasNext(self) -> bool:
  26.         # skip empty rows
  27.         while (self.row < len(self.vec)) and self.col >= len(self.vec[self.row]):
  28.             self.row += 1
  29.             self.col = 0
  30.         if self.row < len(self.vec):
  31.             return True
  32.         else:
  33.             return False
  34.  
  35.  
  36. # Your Vector2D object will be instantiated and called as such:
  37. # obj = Vector2D(vec)
  38. # param_1 = obj.next()
  39. # param_2 = obj.hasNext()
Advertisement
Add Comment
Please, Sign In to add comment