Created
March 8, 2022 14:01
-
-
Save les-peters/af6d22c4bce0a5e8eceef16a13224319 to your computer and use it in GitHub Desktop.
Hashes without Hash, integer edition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os.path | |
| from os import path | |
| import csv | |
| question = """ | |
| Implement a hashmap from scratch without any existing libraries in your preferred language. | |
| A hashmap should: | |
| Be empty when initialized | |
| Have the function put(int key, int value) which inserts a (key, value) pair into the hashmap. | |
| If the key already exists, update the corresponding value. | |
| Have the function get(int key) which returns the value to which the specified key is mapped, or -1 if there's no mapping for the key. | |
| Have the function remove(key) which removes the key and its value if it exists in the map. | |
| """ | |
| hashmap_file = './hashmap.csv' | |
| def put(input_key, input_value): | |
| new_data = [] | |
| input_key = str(input_key) | |
| new_line = [input_key, input_value] | |
| updated = False | |
| if path.exists(hashmap_file): | |
| with open(hashmap_file, newline='') as hashmap: | |
| reader = csv.reader(hashmap) | |
| for key_value in reader: | |
| if input_key == key_value[0]: | |
| new_data.append(new_line) | |
| updated = True | |
| else: | |
| new_data.append(key_value) | |
| if updated == False: | |
| new_data.append(new_line) | |
| with open(hashmap_file, 'w', newline='') as hashmap: | |
| writer = csv.writer(hashmap) | |
| writer.writerows(new_data) | |
| return | |
| def get(input_key): | |
| input_key = str(input_key) | |
| if path.exists(hashmap_file): | |
| with open(hashmap_file, newline='') as hashmap: | |
| reader = csv.reader(hashmap) | |
| for key_value in reader: | |
| if input_key == key_value[0]: | |
| return key_value[1] | |
| return -1 | |
| def remove(input_key): | |
| input_key = str(input_key) | |
| new_data = [] | |
| deleted = False | |
| if path.exists(hashmap_file): | |
| with open(hashmap_file, newline='') as hashmap: | |
| reader = csv.reader(hashmap) | |
| for key_value in reader: | |
| if input_key == key_value[0]: | |
| deleted = True | |
| else: | |
| new_data.append(key_value) | |
| with open(hashmap_file, 'w', newline='') as hashmap: | |
| writer = csv.writer(hashmap) | |
| writer.writerows(new_data) | |
| return | |
| # populate hash | |
| put(1, '1') | |
| put(2, '2') | |
| put(3,'3') | |
| # test get | |
| print(get(1)) | |
| # test put: new value | |
| put(4, '4') | |
| print(get(4)) | |
| # test put: updating existing value | |
| put(4, 'cuatro') | |
| print(get(4)) | |
| # test remove | |
| remove(3) | |
| print(get(3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment