Skip to content

Instantly share code, notes, and snippets.

@travishen
Created December 5, 2018 03:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save travishen/f51365915ef7f178623a2cc9b2ede886 to your computer and use it in GitHub Desktop.
Save travishen/f51365915ef7f178623a2cc9b2ede886 to your computer and use it in GitHub Desktop.
Associate Array / Map / Dictionary + Hash Function Implements using Python
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"from collections import Iterable\n",
"from functools import reduce\n",
"\n",
"class HashTable(object):\n",
" def __init__(self, size=10):\n",
" self.size = 10\n",
" self.keys = [None] * self.size\n",
" self.values = [None] * self.size\n",
" \n",
" def __repr__(self):\n",
" return 'HashTable(size={})'.format(self.size)\n",
" \n",
" def put(self, key, value): \n",
" index = self.hash(key)\n",
"\n",
" while self.keys[index] is not None: # collision\n",
" if self.keys[index] == key: # update\n",
" self.values[index] = value \n",
" return\n",
" index = (index + 1) % self.size # rehash\n",
" \n",
" self.keys[index] = key\n",
" self.values[index] = value\n",
" \n",
" def get(self, key):\n",
" if key in self.keys:\n",
" return self.values[self.hash(key)]\n",
" return None\n",
" \n",
" def hash(self, key): \n",
" if isinstance(key, Iterable):\n",
" sum = reduce(lambda prev, n: prev + ord(n), key, 0)\n",
" else:\n",
" sum = key\n",
" \n",
" return sum % self.size"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"h = HashTable()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"h.put('a', 1)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"h.get('a')"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.2"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment