Advertisement
alex0sunny

hash_pointers

Sep 19th, 2021
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. M = 100003
  2.  
  3.  
  4. class Node:
  5.     def __init__(self, uid, v, next_item=None):
  6.         self.value = [uid, v]
  7.         self.next_item = next_item
  8.  
  9.  
  10. def __search_prev_cur__(uid, head):
  11.     if not head:
  12.         return None, None
  13.     if head.value[0] == uid:
  14.         return None, head
  15.     node = head
  16.     while node.next_item and node.next_item.value[0] != uid:
  17.         node = node.next_item
  18.     if node.next_item and node.next_item.value[0] == uid:
  19.         return node, node.next_item
  20.     return None, None
  21.  
  22.  
  23. def put(uid, v, head):
  24.     _, node = __search_prev_cur__(uid, head)
  25.     if node:
  26.         node.value[1] = v
  27.     else:
  28.         head = Node(uid, v, next_item=head)
  29.     return None, head
  30.  
  31.  
  32. def get(uid, head):
  33.     _, node = __search_prev_cur__(uid, head)
  34.     return node.value[1] if node else False, head
  35.  
  36.  
  37. def delete(uid, head):
  38.     prev, node = __search_prev_cur__(uid, head)
  39.     if not node:
  40.         return False, head
  41.     if node == head:
  42.         head = node.next_item
  43.     else:
  44.         prev.next_item = node.next_item
  45.     return node.value[1], head
  46.  
  47.  
  48. def process_commands(n):
  49.     hash_table = [None] * M
  50.     for _ in range(n):
  51.         args = (input() + ' 0').split()[:3]
  52.         cmd = args[0]
  53.         uid = int(args[1])
  54.         v = int(args[2])
  55.         bucket = uid % M
  56.         head = hash_table[bucket]
  57.         res, head = {'put': lambda uid, v: put(uid, v, head),
  58.                      'get': lambda uid, _: get(uid, head),
  59.                      'delete': lambda uid, _: delete(uid, head)}[cmd](uid, v)
  60.         [0 if res is None else print(None) if res is False else print(res)]
  61.         hash_table[bucket] = head
  62.  
  63.  
  64. n = int(input())
  65. process_commands(n)
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement