Advertisement
Guest User

Untitled

a guest
May 13th, 2021
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. def insert(self, where, item):
  2. n = len(self)
  3.  
  4. if item is null: #not to be confused with None
  5. raise Exception("Couldn't find item to insert!")
  6.  
  7. assert n+1 <= LARGEST_PERMISSIBLE_LIST_SIZE #probably like ten million or something
  8.  
  9. if not list.try_to_allocate_more_space(n+1): #usually runs in O(new_size-cur_size) time... Usually
  10. raise Exception("Out of memory!")
  11.  
  12. #set `where` to a sane value if it isn't in this list's conventional range
  13. if where < 0:
  14. where += n #e.g. -3 becomes n-3
  15. if where < 0:
  16. where = 0 #e.g. -100000000 becomes 0
  17. if where > n:
  18. where == n #e.g. 100000000 becomes n
  19.  
  20. for i in range(n, where-1, -1): #iterate backwards from the end of the list to the insertion point
  21. self[i+1] = self[i] #nudge everything forward once
  22.  
  23. #insert item
  24. self[where] = item
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement