fork download
  1. import string
  2.  
  3. HASH_MAX = 32
  4.  
  5. def hash(s):
  6. return sum(map(ord,s)) % HASH_MAX
  7.  
  8. class LinkedNode:
  9. def __init__(self, key, values):
  10. self.key = key
  11. self.values = values
  12. self.next_node = None
  13.  
  14. def table_insert(table, key, **values):
  15. head = table[hash(key)]
  16. if head is None:
  17. hash_table[hash(key)] = LinkedNode(key, values)
  18. else:
  19. while head.next_node is not None:
  20. head = head.next_node
  21. head.next_node = LinkedNode(key, values)
  22.  
  23. def table_lookup(table, key):
  24. head = hash_table[hash(key)]
  25. if head is None:
  26. return "Hash failure!"
  27. elif head.next_node is None:
  28. return head.values
  29. else:
  30. while head is not None and head.key != key:
  31. head = head.next_node
  32. return head.values if head is not None else "Hash failure!"
  33.  
  34. hash_table = [None for _ in range(HASH_MAX)]
  35.  
  36. table_insert(hash_table, 'abc', name='foo', age=11)
  37. table_insert(hash_table, 'def', name='bar', age=34)
  38. table_insert(hash_table, 'cba', name='baz', age=2357)
  39.  
  40. print(table_lookup(hash_table, 'abc'))
  41. print(table_lookup(hash_table, 'def'))
  42. print(table_lookup(hash_table, 'cba'))
  43. print(table_lookup(hash_table, 'abcd'))
  44.  
Success #stdin #stdout 0.05s 10344KB
stdin
Standard input is empty
stdout
{'age': 11, 'name': 'foo'}
{'age': 34, 'name': 'bar'}
{'age': 2357, 'name': 'baz'}
Hash failure!