Last active
February 21, 2023 03:39
-
-
Save gvirtuoso/25fbf6e2783c8124aebf2ddb5ee2d989 to your computer and use it in GitHub Desktop.
Python DataStructure challenge
This file contains 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 random | |
class MyTable: | |
def __init__(self, slots): | |
self.slots = slots | |
self.table = [] | |
self.create_table() | |
self.current_slot = 0 | |
self.find_output = [] | |
def hash_key(self, slot): | |
return hash(slot) | |
def create_table(self): | |
idx = 0 | |
while idx < self.slots: | |
id = self.hash_key(idx) | |
self.table.append({id: []}) | |
idx += 1 | |
# print(self.table) | |
# Insert values across the slots (one per slot each time) | |
def insert(self, value): | |
self.table[self.current_slot][self.current_slot].append(value) | |
self.current_slot += 1 | |
if self.current_slot >= self.slots: self.current_slot = 0 | |
# print(self.table) | |
def find(self, value): | |
found = False | |
idx = 0 | |
while idx < self.slots: | |
slot_row = self.table[self.hash_key(idx)][self.hash_key(idx)] | |
if value in slot_row: | |
founded = True | |
self.find_output.append( | |
{"SearchFor": value, | |
"Found": True, | |
"Slot": idx, | |
"Position": slot_row.index(value)} | |
) | |
idx += 1 | |
if not found: | |
self.find_output.append( | |
{"SearchFor": value, | |
"Found": False} | |
) | |
print(self.find_output) | |
## Testing | |
slots = 3 | |
values = [1,3,7,8,9,10,6,7,12] | |
table = MyTable(slots) | |
for i in values: | |
table.insert(i) | |
# Show all places where we have number 7 | |
table.find(7) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment