Advertisement
alex0sunny

open_addressing

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