fork(3) download
  1. from bisect import bisect
  2.  
  3. class SnapshotArray:
  4. def __init__(self, length):
  5. self.snap_id = 0
  6. self.snaps = {}
  7. self.values = {}
  8.  
  9. def set(self, index, value):
  10. if not (snaps := self.snaps.setdefault(index, [])) or snaps[-1] != self.snap_id:
  11. snaps.append(self.snap_id)
  12. self.values.setdefault(index, {})[self.snap_id] = value
  13.  
  14. def snap(self):
  15. self.snap_id += 1
  16. return self.snap_id - 1
  17.  
  18. def get(self, index, snap_id):
  19. if snaps := self.snaps.get(index):
  20. return self.values[index][bisect(snaps, snap_id) - 1]
  21. return 0
  22.  
  23. a = SnapshotArray(3)
  24. a.set(0, 5)
  25. print(a.snap())
  26. a.set(0, 6)
  27. print(a.get(0, 0))
Success #stdin #stdout 0.03s 9732KB
stdin
Standard input is empty
stdout
0
5