find_mode working

This commit is contained in:
Andrew Scott 2022-06-03 13:23:11 -04:00
parent e23daab2dc
commit df3117dc8a
Signed by: a
GPG key ID: 3EB62D0BBB8DB381

View file

@ -6,6 +6,7 @@
# Description: HashMap implementation using Separate Chaining
import matplotlib
from a6_include import (
DynamicArray,
LinkedList,
@ -76,6 +77,26 @@ class HashMap:
else:
node.value = value
def find_mode_put(self, key: str, value: object) -> None:
"""Adds (or updates) a key/value pair to the hash map
Parameters
----------
key : str
Identifier for the given value
value : object
Value to add, or update if the key is already present
"""
hash = self._hash_function(key)
index = hash % self._capacity
node = self._buckets[index].contains(key)
if node is None:
self._buckets[index].insert(key, value)
self._size += 1
else:
node.value = node.value + value
def empty_buckets(self) -> int:
"""Gets the number of empty buckets in the hash table
@ -220,8 +241,21 @@ class HashMap:
def find_mode(da: DynamicArray) -> (DynamicArray, int):
"""
TODO: Write this implementation
"""Get the mode(s) and their frequency from a dynamic array
If there is more than one value that has the highest frequency all values at
that frequency will be included. The dynamic array must contain at least 1
element, and all elements must be strings.
Parameters
----------
da : DynamicArray
The dynamic array for which mode and frequency is needed
Returns
-------
(DynamicArray, int) : tuple
Dynamic array with the mode(s), Integer representing highest frequency
"""
mode_arr = DynamicArray()
@ -229,21 +263,26 @@ def find_mode(da: DynamicArray) -> (DynamicArray, int):
mode_arr.append(da[0])
return mode_arr, 1
# use this instance of your Separate Chaining HashMap
map = HashMap(da.length() // 3, hash_function_1)
item = 1
for i in range(da.length()):
key = "key" + str(item)
map.put(key, da[i])
item += 1
map.find_mode_put(da[i], 1)
return -1, -1
keys = map.get_keys()
max_val = 1
for i in range(keys.length()):
value = map.get(keys[i])
if value > max_val:
max_val = value
mode_arr = DynamicArray()
mode_arr.append(keys[i])
elif value == max_val:
mode_arr.append(keys[i])
return mode_arr, max_val
# ------------------- BASIC TESTING ---------------------------------------- #
# ------------------- BASIC TESTING ---------------------------------------- #
if __name__ == "__main__":
if __name__ == "__main__":
print("\nPDF - put example 1")
print("-------------------")
@ -354,7 +393,11 @@ if __name__ == "__main__":
# NOT inserted keys must be absent
result &= not m.contains_key(str(key + 1))
print(
capacity, result, m.get_size(), m.get_capacity(), round(m.table_load(), 2)
capacity,
result,
m.get_size(),
m.get_capacity(),
round(m.table_load(), 2),
)
print("\nPDF - get example 1")