From a9a2aef9a456dee4bac7515ce634034349ef8beb Mon Sep 17 00:00:00 2001 From: Cre4T3Tiv3 Date: Thu, 2 Nov 2023 18:49:43 -0600 Subject: [PATCH] update(algorithms): Revised commenting of all in-sopce modules and the readme directory structure. --- .gitignore | 69 +++++++-------- README.md | 27 ++++-- .../{ => python}/max_sum_divisible_by_k.py | 0 .../python/hash_quadratic_probing.py | 38 +++++++-- .../searching/binary-search/go/.gitignore | 41 --------- .../searching/binary-search/python/.gitignore | 83 ------------------- .../python/tests/test_binary_search.py | 3 +- .../python/adjusted_counting_sort.py | 20 +++-- .../tests/test_adjusted_counting_sort.py | 16 +++- 9 files changed, 111 insertions(+), 186 deletions(-) rename algorithms/dynamic-programming/{ => python}/max_sum_divisible_by_k.py (100%) delete mode 100644 algorithms/searching/binary-search/go/.gitignore delete mode 100644 algorithms/searching/binary-search/python/.gitignore diff --git a/.gitignore b/.gitignore index 20f6a2a..97bcbff 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,32 @@ +# ======================== +# Golang .gitignore +# ======================== + +# Binaries for Programs and Plugins: +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test Binary, Built with `go test -c`: +*.test + +# Output of the Go Coverage Tool, Specifically When Used with LiteIDE: +*.out + +# Dependency Directories (Remove the Comment Below to Include It) +# vendor/ + +# Go Workspace File: +go.work + +# The Local Development Env-Var JSON Config File: +/configs/config.json + +# Local Directory Containing Log Files: +/logs/* + # ======================== # Python .gitignore # ======================== @@ -124,46 +153,6 @@ dmypy.json # Cython debug symbols cython_debug/ -# ======================== -# Bash .gitignore -# ======================== - -# Editor backup/swap files -*~ -.*~ -*.swp -.*.swp - -# Compiled Binaries or scripts (if any) -bin/ -*.out - -# ======================== -# PowerShell .gitignore -# ======================== - -# Windows image file caches -Thumbs.db -ehthumbs.db - -# Folder config file -Desktop.ini - -# Recycle Bin used on file shares -$RECYCLE.BIN/ - -# Windows Installer files -*.cab -*.msi -*.msm -*.msp - -# Windows shortcuts -*.lnk - -# JetBrains IDEs (like PyCharm) -.idea/ - # ======================== # MISC .gitignore # ======================== diff --git a/README.md b/README.md index ce8e934..6cda6f2 100644 --- a/README.md +++ b/README.md @@ -21,20 +21,37 @@ For example: ``` algorithms-and-data-structures-portfolio |-- algorithms +| |-- dynamic-programming +| | |-- python +| | | |-- max_sum_divisible_by_k.py +| |-- hashing +| | |-- quadratic-probing +| | | |-- python +| | | | |-- hash_quadratic_probing.py +| | | | |-- README.md | |-- searching | | |-- binary-search -| | | |-- python | | | |-- go -| |-- hashing -| | |-- quadratic-probing +| | | | |-- binary_search_test.go +| | | | |-- binary_search.go +| | | | |-- go.mod +| | | | |-- README.md | | | |-- python +| | | | |-- tests +| | | | | |-- test_binary_search.py +| | | | |-- README.md +| | | | |-- binary_search.py | |-- sorting | | |-- adjusted-counting-sort | | | |-- python -| | | | |-- adjusted_counting.py -| | | | |-- README.md | | | | |-- tests | | | | | |-- test_adjusted_counting.py +| | | | |-- adjusted_counting.py +| | | | |-- README.md +|-- .gitignore +|-- LICENSE +|-- README.md + ``` diff --git a/algorithms/dynamic-programming/max_sum_divisible_by_k.py b/algorithms/dynamic-programming/python/max_sum_divisible_by_k.py similarity index 100% rename from algorithms/dynamic-programming/max_sum_divisible_by_k.py rename to algorithms/dynamic-programming/python/max_sum_divisible_by_k.py diff --git a/algorithms/hashing/quadratic-probing/python/hash_quadratic_probing.py b/algorithms/hashing/quadratic-probing/python/hash_quadratic_probing.py index 02091be..2630ce1 100644 --- a/algorithms/hashing/quadratic-probing/python/hash_quadratic_probing.py +++ b/algorithms/hashing/quadratic-probing/python/hash_quadratic_probing.py @@ -1,44 +1,63 @@ class HashTable: def __init__(self, size=10): """Initialize the hash table with a given size.""" + # The size of the hash table. self.size = size + # The hash table. self.table = [None] * self.size + # The number of key-value pairs stored in the hash table. self.count = 0 def _hash(self, key): """Compute the initial hash value for a key.""" + # The hash value is computed as follows: return key % self.size def _rehash(self, old_hash, i): """Compute the new hash value using quadratic probing.""" + # The new hash value is computed as follows: return (old_hash + i**2) % self.size def put(self, key, value): """Store the key-value pair in the hash table.""" + # Compute the initial hash value. initial_hash = self._hash(key) + # Initialize the hash value. hash_val = initial_hash + # Initialize the counter. i = 1 - # Find an available slot or a slot with the same key to update. + # Search for an empty slot or a slot with the same key. while self.table[hash_val] is not None and self.table[hash_val][0] != key: + # If the key already exists, update the value. hash_val = self._rehash(initial_hash, i) + # Increment the counter. i += 1 - + # If the key does not exist, add the key-value pair. if self.table[hash_val] is None: + # Increment the counter. self.count += 1 + # Add the key-value pair. self.table[hash_val] = (key, value) def get(self, key): """Retrieve the value associated with the given key.""" + # Compute the initial hash value. initial_hash = self._hash(key) + # Initialize the hash value. hash_val = initial_hash + # Initialize the counter. i = 1 # Search for the key in the hash table. while self.table[hash_val] is not None: + # Return the value if the key is found. if self.table[hash_val][0] == key: + # Return the value. return self.table[hash_val][1] + # Otherwise, rehash and search again. hash_val = self._rehash(initial_hash, i) + # Increment the counter. i += 1 # Return None if the key is not found. @@ -46,34 +65,43 @@ def get(self, key): def __setitem__(self, key, value): """Support assignment using bracket notation.""" + # Add the key-value pair. self.put(key, value) def __getitem__(self, key): """Support retrieval using bracket notation.""" + # Retrieve the value. return self.get(key) def __contains__(self, key): """Support the 'in' keyword.""" + # Check if the key exists. return self.get(key) is not None def test_hash_table(): """Function to test the HashTable functionality.""" + # Initialize the hash table. hash_table = HashTable() - - # Sample data for testing. + # Add some key-value pairs. keys = [1, 2, 12, 22] + # Note: The keys are chosen to demonstrate the quadratic probing. values = ["One", "Two", "Twelve", "Twenty Two"] + # Add the key-value pairs. for key, value in zip(keys, values): + # Add the key-value pair. hash_table[key] = value - + # Check if the key-value pairs were added correctly. for key, expected in zip(keys, values): + # Retrieve the value. result = hash_table[key] + # Check if the value is correct. assert ( result == expected ), f"Expected {expected}, but got {result} for key {key}" +# Test the HashTable class. if __name__ == "__main__": try: test_hash_table() diff --git a/algorithms/searching/binary-search/go/.gitignore b/algorithms/searching/binary-search/go/.gitignore deleted file mode 100644 index 8ace30b..0000000 --- a/algorithms/searching/binary-search/go/.gitignore +++ /dev/null @@ -1,41 +0,0 @@ -# Binaries for Programs and Plugins: -*.exe -*.exe~ -*.dll -*.so -*.dylib - -# Test Binary, Built with `go test -c`: -*.test - -# Output of the Go Coverage Tool, Specifically When Used with LiteIDE: -*.out - -# Dependency Directories (Remove the Comment Below to Include It) -# vendor/ - -# Go Workspace File: -go.work - -# The Local Development Env-Var JSON Config File: -/configs/config.json - -# Local Directory Containing Log Files: -/logs/* - -# macOS Desktop Services Store Files: -.DS_Store - -# Local Visual Studio Code Configs, Settings, etc. -.vscode/* -!.vscode/settings.json -!.vscode/tasks.json -!.vscode/launch.json -!.vscode/extensions.json -!.vscode/*.code-snippets - -# Local History for Visual Studio Code: -.history/ - -# Built Visual Studio Code Extensions: -*.vsix diff --git a/algorithms/searching/binary-search/python/.gitignore b/algorithms/searching/binary-search/python/.gitignore deleted file mode 100644 index deb67d6..0000000 --- a/algorithms/searching/binary-search/python/.gitignore +++ /dev/null @@ -1,83 +0,0 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -*.egg-info/ -.installed.cfg -*.egg - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py,cover -.hypothesis/ -.pytest_cache/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# Environment directories -.env -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Pycharm (IDE) -.idea/ - -# VS Code (IDE) -.vscode/ - -# Spyder (IDE) -.spyderproject -.spyproject - -# MyPy -.mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre (Static type checker for Python) -.pyre/ diff --git a/algorithms/searching/binary-search/python/tests/test_binary_search.py b/algorithms/searching/binary-search/python/tests/test_binary_search.py index da4c8e2..bbba24d 100644 --- a/algorithms/searching/binary-search/python/tests/test_binary_search.py +++ b/algorithms/searching/binary-search/python/tests/test_binary_search.py @@ -26,11 +26,12 @@ def test_binary_search(): result == expected ), f"Expected {expected}, but got {result} for array {arr} and target {target}" - +# Test the binary_search function. if __name__ == "__main__": try: # Run the tests. test_binary_search() + # Print a success message if all tests pass. print("All tests passed!") except AssertionError as e: # If any test fails, print a detailed error message. diff --git a/algorithms/sorting/adjusted-counting-sort/python/adjusted_counting_sort.py b/algorithms/sorting/adjusted-counting-sort/python/adjusted_counting_sort.py index 7a5eab5..88b4be6 100644 --- a/algorithms/sorting/adjusted-counting-sort/python/adjusted_counting_sort.py +++ b/algorithms/sorting/adjusted-counting-sort/python/adjusted_counting_sort.py @@ -1,8 +1,3 @@ -""" -Module for the Adjusted Counting Sort Algorithm -""" - - def adjusted_counting_sort(arr): """ Function to sort an array using the adjusted counting sort method. @@ -12,25 +7,34 @@ def adjusted_counting_sort(arr): Returns: list[int]: List of integers in sorted order. """ - # Create a frequency array of size 100 initialized with zeros + # Initialize the frequency array. freq = [0] * 100 - # Populate the frequency array based on input elements + # Count the frequencies of each element. for num in arr: + # Increment the frequency of the current element. freq[num] += 1 - # Return the sorted array based on frequencies + # Initialize the sorted array. sorted_arr = [] + # Iterate through the frequency array. for index, count in enumerate(freq): + # Add the current element to the sorted array. sorted_arr.extend([index] * count) + # Return the sorted array. return sorted_arr +# Test the adjusted_counting_sort function. if __name__ == "__main__": + # Get the number of elements. n = int(input("Enter the number of elements: ").strip()) + # Get the elements. arr = list( map(int, input("Enter the elements separated by spaces: ").rstrip().split()) ) + # Sort the array. result = adjusted_counting_sort(arr) + # Print the sorted array. print("Sorted Array:", " ".join(map(str, result))) diff --git a/algorithms/sorting/adjusted-counting-sort/python/tests/test_adjusted_counting_sort.py b/algorithms/sorting/adjusted-counting-sort/python/tests/test_adjusted_counting_sort.py index d3a3228..638da52 100644 --- a/algorithms/sorting/adjusted-counting-sort/python/tests/test_adjusted_counting_sort.py +++ b/algorithms/sorting/adjusted-counting-sort/python/tests/test_adjusted_counting_sort.py @@ -4,12 +4,13 @@ "../../.." ) # To include the parent directories in the module search path -from algorithms.sorting.adjusted_counting_sort.python.adjusted_counting_sort import ( - adjusted_counting_sort, -) +# Import the function to test. +from adjusted_counting_sort import adjusted_counting_sort + import unittest +# The parent class. class TestAdjustedCountingSort(unittest.TestCase): """ Unit tests for the Adjusted Counting Sort Algorithm @@ -19,26 +20,35 @@ def test_basic(self): """ Basic tests for the Adjusted Counting Sort """ + # Test 1: Test for a list with no duplicates. arr = [4, 2, 2, 8, 3, 3, 1] + # The expected output. self.assertEqual(adjusted_counting_sort(arr), [1, 2, 2, 3, 3, 4, 8]) + # Test 2: Test for a list with duplicates. arr = [9, 7, 5, 3, 1] + # The expected output. self.assertEqual(adjusted_counting_sort(arr), [1, 3, 5, 7, 9]) def test_empty(self): """ Test for an empty list """ + # Test 1: Test for an empty list. arr = [] + # The expected output. self.assertEqual(adjusted_counting_sort(arr), []) def test_single_element(self): """ Test for a list with a single element """ + # Test 1: Test for a list with a single element. arr = [5] + # The expected output. self.assertEqual(adjusted_counting_sort(arr), [5]) +# Run the unit tests. if __name__ == "__main__": unittest.main()