repo_name
stringclasses
1 value
pr_number
int64
4.12k
11.2k
pr_title
stringlengths
9
107
pr_description
stringlengths
107
5.48k
author
stringlengths
4
18
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
118
5.52k
before_content
stringlengths
0
7.93M
after_content
stringlengths
0
7.93M
label
int64
-1
1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import random import sys LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def main() -> None: message = input("Enter message: ") key = "LFWOAYUISVKMNXPBDCRJTQEGHZ" resp = input("Encrypt/Decrypt [e/d]: ") check_valid_key(key) if resp.lower().startswith("e"): mode = "encrypt" translated = encrypt_message(key, message) elif resp.lower().startswith("d"): mode = "decrypt" translated = decrypt_message(key, message) print(f"\n{mode.title()}ion: \n{translated}") def check_valid_key(key: str) -> None: key_list = list(key) letters_list = list(LETTERS) key_list.sort() letters_list.sort() if key_list != letters_list: sys.exit("Error in the key or symbol set.") def encrypt_message(key: str, message: str) -> str: """ >>> encrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji') 'Ilcrism Olcvs' """ return translate_message(key, message, "encrypt") def decrypt_message(key: str, message: str) -> str: """ >>> decrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs') 'Harshil Darji' """ return translate_message(key, message, "decrypt") def translate_message(key: str, message: str, mode: str) -> str: translated = "" chars_a = LETTERS chars_b = key if mode == "decrypt": chars_a, chars_b = chars_b, chars_a for symbol in message: if symbol.upper() in chars_a: sym_index = chars_a.find(symbol.upper()) if symbol.isupper(): translated += chars_b[sym_index].upper() else: translated += chars_b[sym_index].lower() else: translated += symbol return translated def get_random_key() -> str: key = list(LETTERS) random.shuffle(key) return "".join(key) if __name__ == "__main__": main()
import random import sys LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def main() -> None: message = input("Enter message: ") key = "LFWOAYUISVKMNXPBDCRJTQEGHZ" resp = input("Encrypt/Decrypt [e/d]: ") check_valid_key(key) if resp.lower().startswith("e"): mode = "encrypt" translated = encrypt_message(key, message) elif resp.lower().startswith("d"): mode = "decrypt" translated = decrypt_message(key, message) print(f"\n{mode.title()}ion: \n{translated}") def check_valid_key(key: str) -> None: key_list = list(key) letters_list = list(LETTERS) key_list.sort() letters_list.sort() if key_list != letters_list: sys.exit("Error in the key or symbol set.") def encrypt_message(key: str, message: str) -> str: """ >>> encrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji') 'Ilcrism Olcvs' """ return translate_message(key, message, "encrypt") def decrypt_message(key: str, message: str) -> str: """ >>> decrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs') 'Harshil Darji' """ return translate_message(key, message, "decrypt") def translate_message(key: str, message: str, mode: str) -> str: translated = "" chars_a = LETTERS chars_b = key if mode == "decrypt": chars_a, chars_b = chars_b, chars_a for symbol in message: if symbol.upper() in chars_a: sym_index = chars_a.find(symbol.upper()) if symbol.isupper(): translated += chars_b[sym_index].upper() else: translated += chars_b[sym_index].lower() else: translated += symbol return translated def get_random_key() -> str: key = list(LETTERS) random.shuffle(key) return "".join(key) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Get book and author data from https://openlibrary.org ISBN: https://en.wikipedia.org/wiki/International_Standard_Book_Number """ from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def get_openlibrary_data(olid: str = "isbn/0140328726") -> dict: """ Given an 'isbn/0140328726', return book data from Open Library as a Python dict. Given an '/authors/OL34184A', return authors data as a Python dict. This code must work for olids with or without a leading slash ('/'). # Comment out doctests if they take too long or have results that may change # >>> get_openlibrary_data(olid='isbn/0140328726') # doctest: +ELLIPSIS {'publishers': ['Puffin'], 'number_of_pages': 96, 'isbn_10': ['0140328726'], ... # >>> get_openlibrary_data(olid='/authors/OL7353617A') # doctest: +ELLIPSIS {'name': 'Adrian Brisku', 'created': {'type': '/type/datetime', ... """ new_olid = olid.strip().strip("/") # Remove leading/trailing whitespace & slashes if new_olid.count("/") != 1: raise ValueError(f"{olid} is not a valid Open Library olid") return requests.get(f"https://openlibrary.org/{new_olid}.json").json() def summarize_book(ol_book_data: dict) -> dict: """ Given Open Library book data, return a summary as a Python dict. """ desired_keys = { "title": "Title", "publish_date": "Publish date", "authors": "Authors", "number_of_pages": "Number of pages:", "first_sentence": "First sentence", "isbn_10": "ISBN (10)", "isbn_13": "ISBN (13)", } data = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} data["Authors"] = [ get_openlibrary_data(author["key"])["name"] for author in data["Authors"] ] data["First sentence"] = data["First sentence"]["value"] for key, value in data.items(): if isinstance(value, list): data[key] = ", ".join(value) return data if __name__ == "__main__": import doctest doctest.testmod() while True: isbn = input("\nEnter the ISBN code to search (or 'quit' to stop): ").strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(f"Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.") continue print(f"\nSearching Open Library for ISBN: {isbn}...\n") try: book_summary = summarize_book(get_openlibrary_data(f"isbn/{isbn}")) print("\n".join(f"{key}: {value}" for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(f"Sorry, there are no results for ISBN: {isbn}.")
""" Get book and author data from https://openlibrary.org ISBN: https://en.wikipedia.org/wiki/International_Standard_Book_Number """ from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def get_openlibrary_data(olid: str = "isbn/0140328726") -> dict: """ Given an 'isbn/0140328726', return book data from Open Library as a Python dict. Given an '/authors/OL34184A', return authors data as a Python dict. This code must work for olids with or without a leading slash ('/'). # Comment out doctests if they take too long or have results that may change # >>> get_openlibrary_data(olid='isbn/0140328726') # doctest: +ELLIPSIS {'publishers': ['Puffin'], 'number_of_pages': 96, 'isbn_10': ['0140328726'], ... # >>> get_openlibrary_data(olid='/authors/OL7353617A') # doctest: +ELLIPSIS {'name': 'Adrian Brisku', 'created': {'type': '/type/datetime', ... """ new_olid = olid.strip().strip("/") # Remove leading/trailing whitespace & slashes if new_olid.count("/") != 1: raise ValueError(f"{olid} is not a valid Open Library olid") return requests.get(f"https://openlibrary.org/{new_olid}.json").json() def summarize_book(ol_book_data: dict) -> dict: """ Given Open Library book data, return a summary as a Python dict. """ desired_keys = { "title": "Title", "publish_date": "Publish date", "authors": "Authors", "number_of_pages": "Number of pages:", "first_sentence": "First sentence", "isbn_10": "ISBN (10)", "isbn_13": "ISBN (13)", } data = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} data["Authors"] = [ get_openlibrary_data(author["key"])["name"] for author in data["Authors"] ] data["First sentence"] = data["First sentence"]["value"] for key, value in data.items(): if isinstance(value, list): data[key] = ", ".join(value) return data if __name__ == "__main__": import doctest doctest.testmod() while True: isbn = input("\nEnter the ISBN code to search (or 'quit' to stop): ").strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(f"Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.") continue print(f"\nSearching Open Library for ISBN: {isbn}...\n") try: book_summary = summarize_book(get_openlibrary_data(f"isbn/{isbn}")) print("\n".join(f"{key}: {value}" for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(f"Sorry, there are no results for ISBN: {isbn}.")
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import cv2 import numpy as np """ Harris Corner Detector https://en.wikipedia.org/wiki/Harris_Corner_Detector """ class HarrisCorner: def __init__(self, k: float, window_size: int): """ k : is an empirically determined constant in [0.04,0.06] window_size : neighbourhoods considered """ if k in (0.04, 0.06): self.k = k self.window_size = window_size else: raise ValueError("invalid k value") def __str__(self) -> str: return str(self.k) def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]: """ Returns the image with corners identified img_path : path of the image output : list of the corner positions, image """ img = cv2.imread(img_path, 0) h, w = img.shape corner_list: list[list[int]] = [] color_img = img.copy() color_img = cv2.cvtColor(color_img, cv2.COLOR_GRAY2RGB) dy, dx = np.gradient(img) ixx = dx**2 iyy = dy**2 ixy = dx * dy k = 0.04 offset = self.window_size // 2 for y in range(offset, h - offset): for x in range(offset, w - offset): wxx = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() wyy = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() wxy = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() det = (wxx * wyy) - (wxy**2) trace = wxx + wyy r = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r]) color_img.itemset((y, x, 0), 0) color_img.itemset((y, x, 1), 0) color_img.itemset((y, x, 2), 255) return color_img, corner_list if __name__ == "__main__": edge_detect = HarrisCorner(0.04, 3) color_img, _ = edge_detect.detect("path_to_image") cv2.imwrite("detect.png", color_img)
import cv2 import numpy as np """ Harris Corner Detector https://en.wikipedia.org/wiki/Harris_Corner_Detector """ class HarrisCorner: def __init__(self, k: float, window_size: int): """ k : is an empirically determined constant in [0.04,0.06] window_size : neighbourhoods considered """ if k in (0.04, 0.06): self.k = k self.window_size = window_size else: raise ValueError("invalid k value") def __str__(self) -> str: return str(self.k) def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]: """ Returns the image with corners identified img_path : path of the image output : list of the corner positions, image """ img = cv2.imread(img_path, 0) h, w = img.shape corner_list: list[list[int]] = [] color_img = img.copy() color_img = cv2.cvtColor(color_img, cv2.COLOR_GRAY2RGB) dy, dx = np.gradient(img) ixx = dx**2 iyy = dy**2 ixy = dx * dy k = 0.04 offset = self.window_size // 2 for y in range(offset, h - offset): for x in range(offset, w - offset): wxx = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() wyy = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() wxy = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() det = (wxx * wyy) - (wxy**2) trace = wxx + wyy r = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r]) color_img.itemset((y, x, 0), 0) color_img.itemset((y, x, 1), 0) color_img.itemset((y, x, 2), 255) return color_img, corner_list if __name__ == "__main__": edge_detect = HarrisCorner(0.04, 3) color_img, _ = edge_detect.detect("path_to_image") cv2.imwrite("detect.png", color_img)
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Breadth-first search shortest path implementations. doctest: python -m doctest -v bfs_shortest_path.py Manual test: python bfs_shortest_path.py """ demo_graph = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } def bfs_shortest_path(graph: dict, start, goal) -> list[str]: """Find shortest path between `start` and `goal` nodes. Args: graph (dict): node/list of neighboring nodes key/value pairs. start: start node. goal: target node. Returns: Shortest path between `start` and `goal` nodes as a string of nodes. 'Not found' string if no path found. Example: >>> bfs_shortest_path(demo_graph, "G", "D") ['G', 'C', 'A', 'B', 'D'] >>> bfs_shortest_path(demo_graph, "G", "G") ['G'] >>> bfs_shortest_path(demo_graph, "G", "Unknown") [] """ # keep track of explored nodes explored = set() # keep track of all the paths to be checked queue = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue path = queue.pop(0) # get the last node from the path node = path[-1] if node not in explored: neighbours = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: new_path = list(path) new_path.append(neighbour) queue.append(new_path) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(node) # in case there's no path between the 2 nodes return [] def bfs_shortest_path_distance(graph: dict, start, target) -> int: """Find shortest path distance between `start` and `target` nodes. Args: graph: node/list of neighboring nodes key/value pairs. start: node to start search from. target: node to search for. Returns: Number of edges in shortest path between `start` and `target` nodes. -1 if no path exists. Example: >>> bfs_shortest_path_distance(demo_graph, "G", "D") 4 >>> bfs_shortest_path_distance(demo_graph, "A", "A") 0 >>> bfs_shortest_path_distance(demo_graph, "A", "Unknown") -1 """ if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 queue = [start] visited = set(start) # Keep tab on distances from `start` node. dist = {start: 0, target: -1} while queue: node = queue.pop(0) if node == target: dist[target] = ( dist[node] if dist[target] == -1 else min(dist[target], dist[node]) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(adjacent) queue.append(adjacent) dist[adjacent] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, "G", "D")) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, "G", "D")) # returns 4
"""Breadth-first search shortest path implementations. doctest: python -m doctest -v bfs_shortest_path.py Manual test: python bfs_shortest_path.py """ demo_graph = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } def bfs_shortest_path(graph: dict, start, goal) -> list[str]: """Find shortest path between `start` and `goal` nodes. Args: graph (dict): node/list of neighboring nodes key/value pairs. start: start node. goal: target node. Returns: Shortest path between `start` and `goal` nodes as a string of nodes. 'Not found' string if no path found. Example: >>> bfs_shortest_path(demo_graph, "G", "D") ['G', 'C', 'A', 'B', 'D'] >>> bfs_shortest_path(demo_graph, "G", "G") ['G'] >>> bfs_shortest_path(demo_graph, "G", "Unknown") [] """ # keep track of explored nodes explored = set() # keep track of all the paths to be checked queue = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue path = queue.pop(0) # get the last node from the path node = path[-1] if node not in explored: neighbours = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: new_path = list(path) new_path.append(neighbour) queue.append(new_path) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(node) # in case there's no path between the 2 nodes return [] def bfs_shortest_path_distance(graph: dict, start, target) -> int: """Find shortest path distance between `start` and `target` nodes. Args: graph: node/list of neighboring nodes key/value pairs. start: node to start search from. target: node to search for. Returns: Number of edges in shortest path between `start` and `target` nodes. -1 if no path exists. Example: >>> bfs_shortest_path_distance(demo_graph, "G", "D") 4 >>> bfs_shortest_path_distance(demo_graph, "A", "A") 0 >>> bfs_shortest_path_distance(demo_graph, "A", "Unknown") -1 """ if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 queue = [start] visited = set(start) # Keep tab on distances from `start` node. dist = {start: 0, target: -1} while queue: node = queue.pop(0) if node == target: dist[target] = ( dist[node] if dist[target] == -1 else min(dist[target], dist[node]) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(adjacent) queue.append(adjacent) dist[adjacent] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, "G", "D")) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, "G", "D")) # returns 4
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from PIL import Image """ Mean thresholding algorithm for image processing https://en.wikipedia.org/wiki/Thresholding_(image_processing) """ def mean_threshold(image: Image) -> Image: """ image: is a grayscale PIL image object """ height, width = image.size mean = 0 pixels = image.load() for i in range(width): for j in range(height): pixel = pixels[j, i] mean += pixel mean //= width * height for j in range(width): for i in range(height): pixels[i, j] = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": image = mean_threshold(Image.open("path_to_image").convert("L")) image.save("output_image_path")
from PIL import Image """ Mean thresholding algorithm for image processing https://en.wikipedia.org/wiki/Thresholding_(image_processing) """ def mean_threshold(image: Image) -> Image: """ image: is a grayscale PIL image object """ height, width = image.size mean = 0 pixels = image.load() for i in range(width): for j in range(height): pixel = pixels[j, i] mean += pixel mean //= width * height for j in range(width): for i in range(height): pixels[i, j] = 255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": image = mean_threshold(Image.open("path_to_image").convert("L")) image.save("output_image_path")
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/bin/sh # # An example hook script to check the commit log message taken by # applypatch from an e-mail message. # # The hook should exit with non-zero status after issuing an # appropriate message if it wants to stop the commit. The hook is # allowed to edit the commit message file. # # To enable this hook, rename this file to "applypatch-msg". . git-sh-setup commitmsg="$(git rev-parse --git-path hooks/commit-msg)" test -x "$commitmsg" && exec "$commitmsg" ${1+"$@"} :
#!/bin/sh # # An example hook script to check the commit log message taken by # applypatch from an e-mail message. # # The hook should exit with non-zero status after issuing an # appropriate message if it wants to stop the commit. The hook is # allowed to edit the commit message file. # # To enable this hook, rename this file to "applypatch-msg". . git-sh-setup commitmsg="$(git rev-parse --git-path hooks/commit-msg)" test -x "$commitmsg" && exec "$commitmsg" ${1+"$@"} :
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def check_polygon(nums: list[float]) -> bool: """ Takes list of possible side lengths and determines whether a two-dimensional polygon with such side lengths can exist. Returns a boolean value for the < comparison of the largest side length with sum of the rest. Wiki: https://en.wikipedia.org/wiki/Triangle_inequality >>> check_polygon([6, 10, 5]) True >>> check_polygon([3, 7, 13, 2]) False >>> check_polygon([1, 4.3, 5.2, 12.2]) False >>> nums = [3, 7, 13, 2] >>> _ = check_polygon(nums) # Run function, do not show answer in output >>> nums # Check numbers are not reordered [3, 7, 13, 2] >>> check_polygon([]) Traceback (most recent call last): ... ValueError: Monogons and Digons are not polygons in the Euclidean space >>> check_polygon([-2, 5, 6]) Traceback (most recent call last): ... ValueError: All values must be greater than 0 """ if len(nums) < 2: raise ValueError("Monogons and Digons are not polygons in the Euclidean space") if any(i <= 0 for i in nums): raise ValueError("All values must be greater than 0") copy_nums = nums.copy() copy_nums.sort() return copy_nums[-1] < sum(copy_nums[:-1]) if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations def check_polygon(nums: list[float]) -> bool: """ Takes list of possible side lengths and determines whether a two-dimensional polygon with such side lengths can exist. Returns a boolean value for the < comparison of the largest side length with sum of the rest. Wiki: https://en.wikipedia.org/wiki/Triangle_inequality >>> check_polygon([6, 10, 5]) True >>> check_polygon([3, 7, 13, 2]) False >>> check_polygon([1, 4.3, 5.2, 12.2]) False >>> nums = [3, 7, 13, 2] >>> _ = check_polygon(nums) # Run function, do not show answer in output >>> nums # Check numbers are not reordered [3, 7, 13, 2] >>> check_polygon([]) Traceback (most recent call last): ... ValueError: Monogons and Digons are not polygons in the Euclidean space >>> check_polygon([-2, 5, 6]) Traceback (most recent call last): ... ValueError: All values must be greater than 0 """ if len(nums) < 2: raise ValueError("Monogons and Digons are not polygons in the Euclidean space") if any(i <= 0 for i in nums): raise ValueError("All values must be greater than 0") copy_nums = nums.copy() copy_nums.sort() return copy_nums[-1] < sum(copy_nums[:-1]) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Cellular Automata Cellular automata are a way to simulate the behavior of "life", no matter if it is a robot or cell. They usually follow simple rules but can lead to the creation of complex forms. The most popular cellular automaton is Conway's [Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). * <https://en.wikipedia.org/wiki/Cellular_automaton> * <https://mathworld.wolfram.com/ElementaryCellularAutomaton.html>
# Cellular Automata Cellular automata are a way to simulate the behavior of "life", no matter if it is a robot or cell. They usually follow simple rules but can lead to the creation of complex forms. The most popular cellular automaton is Conway's [Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). * <https://en.wikipedia.org/wiki/Cellular_automaton> * <https://mathworld.wolfram.com/ElementaryCellularAutomaton.html>
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# @Author : lightXu # @File : convolve.py # @Time : 2019/7/8 0008 下午 16:13 from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import array, dot, pad, ravel, uint8, zeros def im2col(image, block_size): rows, cols = image.shape dst_height = cols - block_size[1] + 1 dst_width = rows - block_size[0] + 1 image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0])) row = 0 for i in range(0, dst_height): for j in range(0, dst_width): window = ravel(image[i : i + block_size[0], j : j + block_size[1]]) image_array[row, :] = window row += 1 return image_array def img_convolve(image, filter_kernel): height, width = image.shape[0], image.shape[1] k_size = filter_kernel.shape[0] pad_size = k_size // 2 # Pads image with the edge values of array. image_tmp = pad(image, pad_size, mode="edge") # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows image_array = im2col(image_tmp, (k_size, k_size)) # turn the kernel into shape(k*k, 1) kernel_array = ravel(filter_kernel) # reshape and get the dst image dst = dot(image_array, kernel_array).reshape(height, width) return dst if __name__ == "__main__": # read original image img = imread(r"../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # Laplace operator Laplace_kernel = array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) out = img_convolve(gray, Laplace_kernel).astype(uint8) imshow("Laplacian", out) waitKey(0)
# @Author : lightXu # @File : convolve.py # @Time : 2019/7/8 0008 下午 16:13 from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import array, dot, pad, ravel, uint8, zeros def im2col(image, block_size): rows, cols = image.shape dst_height = cols - block_size[1] + 1 dst_width = rows - block_size[0] + 1 image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0])) row = 0 for i in range(0, dst_height): for j in range(0, dst_width): window = ravel(image[i : i + block_size[0], j : j + block_size[1]]) image_array[row, :] = window row += 1 return image_array def img_convolve(image, filter_kernel): height, width = image.shape[0], image.shape[1] k_size = filter_kernel.shape[0] pad_size = k_size // 2 # Pads image with the edge values of array. image_tmp = pad(image, pad_size, mode="edge") # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows image_array = im2col(image_tmp, (k_size, k_size)) # turn the kernel into shape(k*k, 1) kernel_array = ravel(filter_kernel) # reshape and get the dst image dst = dot(image_array, kernel_array).reshape(height, width) return dst if __name__ == "__main__": # read original image img = imread(r"../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # Laplace operator Laplace_kernel = array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) out = img_convolve(gray, Laplace_kernel).astype(uint8) imshow("Laplacian", out) waitKey(0)
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def move_tower(height, from_pole, to_pole, with_pole): """ >>> move_tower(3, 'A', 'B', 'C') moving disk from A to B moving disk from A to C moving disk from B to C moving disk from A to B moving disk from C to A moving disk from C to B moving disk from A to B """ if height >= 1: move_tower(height - 1, from_pole, with_pole, to_pole) move_disk(from_pole, to_pole) move_tower(height - 1, with_pole, to_pole, from_pole) def move_disk(fp, tp): print("moving disk from", fp, "to", tp) def main(): height = int(input("Height of hanoi: ").strip()) move_tower(height, "A", "B", "C") if __name__ == "__main__": main()
def move_tower(height, from_pole, to_pole, with_pole): """ >>> move_tower(3, 'A', 'B', 'C') moving disk from A to B moving disk from A to C moving disk from B to C moving disk from A to B moving disk from C to A moving disk from C to B moving disk from A to B """ if height >= 1: move_tower(height - 1, from_pole, with_pole, to_pole) move_disk(from_pole, to_pole) move_tower(height - 1, with_pole, to_pole, from_pole) def move_disk(fp, tp): print("moving disk from", fp, "to", tp) def main(): height = int(input("Height of hanoi: ").strip()) move_tower(height, "A", "B", "C") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import string def decrypt(message: str) -> None: """ >>> decrypt('TMDETUX PMDVU') Decryption using Key #0: TMDETUX PMDVU Decryption using Key #1: SLCDSTW OLCUT Decryption using Key #2: RKBCRSV NKBTS Decryption using Key #3: QJABQRU MJASR Decryption using Key #4: PIZAPQT LIZRQ Decryption using Key #5: OHYZOPS KHYQP Decryption using Key #6: NGXYNOR JGXPO Decryption using Key #7: MFWXMNQ IFWON Decryption using Key #8: LEVWLMP HEVNM Decryption using Key #9: KDUVKLO GDUML Decryption using Key #10: JCTUJKN FCTLK Decryption using Key #11: IBSTIJM EBSKJ Decryption using Key #12: HARSHIL DARJI Decryption using Key #13: GZQRGHK CZQIH Decryption using Key #14: FYPQFGJ BYPHG Decryption using Key #15: EXOPEFI AXOGF Decryption using Key #16: DWNODEH ZWNFE Decryption using Key #17: CVMNCDG YVMED Decryption using Key #18: BULMBCF XULDC Decryption using Key #19: ATKLABE WTKCB Decryption using Key #20: ZSJKZAD VSJBA Decryption using Key #21: YRIJYZC URIAZ Decryption using Key #22: XQHIXYB TQHZY Decryption using Key #23: WPGHWXA SPGYX Decryption using Key #24: VOFGVWZ ROFXW Decryption using Key #25: UNEFUVY QNEWV """ for key in range(len(string.ascii_uppercase)): translated = "" for symbol in message: if symbol in string.ascii_uppercase: num = string.ascii_uppercase.find(symbol) num = num - key if num < 0: num = num + len(string.ascii_uppercase) translated = translated + string.ascii_uppercase[num] else: translated = translated + symbol print(f"Decryption using Key #{key}: {translated}") def main() -> None: message = input("Encrypted message: ") message = message.upper() decrypt(message) if __name__ == "__main__": import doctest doctest.testmod() main()
import string def decrypt(message: str) -> None: """ >>> decrypt('TMDETUX PMDVU') Decryption using Key #0: TMDETUX PMDVU Decryption using Key #1: SLCDSTW OLCUT Decryption using Key #2: RKBCRSV NKBTS Decryption using Key #3: QJABQRU MJASR Decryption using Key #4: PIZAPQT LIZRQ Decryption using Key #5: OHYZOPS KHYQP Decryption using Key #6: NGXYNOR JGXPO Decryption using Key #7: MFWXMNQ IFWON Decryption using Key #8: LEVWLMP HEVNM Decryption using Key #9: KDUVKLO GDUML Decryption using Key #10: JCTUJKN FCTLK Decryption using Key #11: IBSTIJM EBSKJ Decryption using Key #12: HARSHIL DARJI Decryption using Key #13: GZQRGHK CZQIH Decryption using Key #14: FYPQFGJ BYPHG Decryption using Key #15: EXOPEFI AXOGF Decryption using Key #16: DWNODEH ZWNFE Decryption using Key #17: CVMNCDG YVMED Decryption using Key #18: BULMBCF XULDC Decryption using Key #19: ATKLABE WTKCB Decryption using Key #20: ZSJKZAD VSJBA Decryption using Key #21: YRIJYZC URIAZ Decryption using Key #22: XQHIXYB TQHZY Decryption using Key #23: WPGHWXA SPGYX Decryption using Key #24: VOFGVWZ ROFXW Decryption using Key #25: UNEFUVY QNEWV """ for key in range(len(string.ascii_uppercase)): translated = "" for symbol in message: if symbol in string.ascii_uppercase: num = string.ascii_uppercase.find(symbol) num = num - key if num < 0: num = num + len(string.ascii_uppercase) translated = translated + string.ascii_uppercase[num] else: translated = translated + symbol print(f"Decryption using Key #{key}: {translated}") def main() -> None: message = input("Encrypted message: ") message = message.upper() decrypt(message) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import base64 def base32_encode(string: str) -> bytes: """ Encodes a given string to base32, returning a bytes-like object >>> base32_encode("Hello World!") b'JBSWY3DPEBLW64TMMQQQ====' >>> base32_encode("123456") b'GEZDGNBVGY======' >>> base32_encode("some long complex string") b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=' """ # encoded the input (we need a bytes like object) # then, b32encoded the bytes-like object return base64.b32encode(string.encode("utf-8")) def base32_decode(encoded_bytes: bytes) -> str: """ Decodes a given bytes-like object to a string, returning a string >>> base32_decode(b'JBSWY3DPEBLW64TMMQQQ====') 'Hello World!' >>> base32_decode(b'GEZDGNBVGY======') '123456' >>> base32_decode(b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=') 'some long complex string' """ # decode the bytes from base32 # then, decode the bytes-like object to return as a string return base64.b32decode(encoded_bytes).decode("utf-8") if __name__ == "__main__": test = "Hello World!" encoded = base32_encode(test) print(encoded) decoded = base32_decode(encoded) print(decoded)
import base64 def base32_encode(string: str) -> bytes: """ Encodes a given string to base32, returning a bytes-like object >>> base32_encode("Hello World!") b'JBSWY3DPEBLW64TMMQQQ====' >>> base32_encode("123456") b'GEZDGNBVGY======' >>> base32_encode("some long complex string") b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=' """ # encoded the input (we need a bytes like object) # then, b32encoded the bytes-like object return base64.b32encode(string.encode("utf-8")) def base32_decode(encoded_bytes: bytes) -> str: """ Decodes a given bytes-like object to a string, returning a string >>> base32_decode(b'JBSWY3DPEBLW64TMMQQQ====') 'Hello World!' >>> base32_decode(b'GEZDGNBVGY======') '123456' >>> base32_decode(b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=') 'some long complex string' """ # decode the bytes from base32 # then, decode the bytes-like object to return as a string return base64.b32decode(encoded_bytes).decode("utf-8") if __name__ == "__main__": test = "Hello World!" encoded = base32_encode(test) print(encoded) decoded = base32_decode(encoded) print(decoded)
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#
#
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Python3 program to evaluate a prefix expression. """ calc = { "+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y, "/": lambda x, y: x / y, } def is_operand(c): """ Return True if the given char c is an operand, e.g. it is a number >>> is_operand("1") True >>> is_operand("+") False """ return c.isdigit() def evaluate(expression): """ Evaluate a given expression in prefix notation. Asserts that the given expression is valid. >>> evaluate("+ 9 * 2 6") 21 >>> evaluate("/ * 10 2 + 4 1 ") 4.0 """ stack = [] # iterate over the string in reverse order for c in expression.split()[::-1]: # push operand to stack if is_operand(c): stack.append(int(c)) else: # pop values from stack can calculate the result # push the result onto the stack again o1 = stack.pop() o2 = stack.pop() stack.append(calc[c](o1, o2)) return stack.pop() # Driver code if __name__ == "__main__": test_expression = "+ 9 * 2 6" print(evaluate(test_expression)) test_expression = "/ * 10 2 + 4 1 " print(evaluate(test_expression))
""" Python3 program to evaluate a prefix expression. """ calc = { "+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y, "/": lambda x, y: x / y, } def is_operand(c): """ Return True if the given char c is an operand, e.g. it is a number >>> is_operand("1") True >>> is_operand("+") False """ return c.isdigit() def evaluate(expression): """ Evaluate a given expression in prefix notation. Asserts that the given expression is valid. >>> evaluate("+ 9 * 2 6") 21 >>> evaluate("/ * 10 2 + 4 1 ") 4.0 """ stack = [] # iterate over the string in reverse order for c in expression.split()[::-1]: # push operand to stack if is_operand(c): stack.append(int(c)) else: # pop values from stack can calculate the result # push the result onto the stack again o1 = stack.pop() o2 = stack.pop() stack.append(calc[c](o1, o2)) return stack.pop() # Driver code if __name__ == "__main__": test_expression = "+ 9 * 2 6" print(evaluate(test_expression)) test_expression = "/ * 10 2 + 4 1 " print(evaluate(test_expression))
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementation of double ended queue. """ from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass from typing import Any class Deque: """ Deque data structure. Operations ---------- append(val: Any) -> None appendleft(val: Any) -> None extend(iterable: Iterable) -> None extendleft(iterable: Iterable) -> None pop() -> Any popleft() -> Any Observers --------- is_empty() -> bool Attributes ---------- _front: _Node front of the deque a.k.a. the first element _back: _Node back of the element a.k.a. the last element _len: int the number of nodes """ __slots__ = ["_front", "_back", "_len"] @dataclass class _Node: """ Representation of a node. Contains a value and a pointer to the next node as well as to the previous one. """ val: Any = None next_node: Deque._Node | None = None prev_node: Deque._Node | None = None class _Iterator: """ Helper class for iteration. Will be used to implement iteration. Attributes ---------- _cur: _Node the current node of the iteration. """ __slots__ = ["_cur"] def __init__(self, cur: Deque._Node | None) -> None: self._cur = cur def __iter__(self) -> Deque._Iterator: """ >>> our_deque = Deque([1, 2, 3]) >>> iterator = iter(our_deque) """ return self def __next__(self) -> Any: """ >>> our_deque = Deque([1, 2, 3]) >>> iterator = iter(our_deque) >>> next(iterator) 1 >>> next(iterator) 2 >>> next(iterator) 3 """ if self._cur is None: # finished iterating raise StopIteration val = self._cur.val self._cur = self._cur.next_node return val def __init__(self, iterable: Iterable[Any] | None = None) -> None: self._front: Any = None self._back: Any = None self._len: int = 0 if iterable is not None: # append every value to the deque for val in iterable: self.append(val) def append(self, val: Any) -> None: """ Adds val to the end of the deque. Time complexity: O(1) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.append(4) >>> our_deque_1 [1, 2, 3, 4] >>> our_deque_2 = Deque('ab') >>> our_deque_2.append('c') >>> our_deque_2 ['a', 'b', 'c'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.append(4) >>> deque_collections_1 deque([1, 2, 3, 4]) >>> deque_collections_2 = deque('ab') >>> deque_collections_2.append('c') >>> deque_collections_2 deque(['a', 'b', 'c']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes self._back.next_node = node node.prev_node = self._back self._back = node # assign new back to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def appendleft(self, val: Any) -> None: """ Adds val to the beginning of the deque. Time complexity: O(1) >>> our_deque_1 = Deque([2, 3]) >>> our_deque_1.appendleft(1) >>> our_deque_1 [1, 2, 3] >>> our_deque_2 = Deque('bc') >>> our_deque_2.appendleft('a') >>> our_deque_2 ['a', 'b', 'c'] >>> from collections import deque >>> deque_collections_1 = deque([2, 3]) >>> deque_collections_1.appendleft(1) >>> deque_collections_1 deque([1, 2, 3]) >>> deque_collections_2 = deque('bc') >>> deque_collections_2.appendleft('a') >>> deque_collections_2 deque(['a', 'b', 'c']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes node.next_node = self._front self._front.prev_node = node self._front = node # assign new front to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def extend(self, iterable: Iterable[Any]) -> None: """ Appends every value of iterable to the end of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extend([4, 5]) >>> our_deque_1 [1, 2, 3, 4, 5] >>> our_deque_2 = Deque('ab') >>> our_deque_2.extend('cd') >>> our_deque_2 ['a', 'b', 'c', 'd'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.extend([4, 5]) >>> deque_collections_1 deque([1, 2, 3, 4, 5]) >>> deque_collections_2 = deque('ab') >>> deque_collections_2.extend('cd') >>> deque_collections_2 deque(['a', 'b', 'c', 'd']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ for val in iterable: self.append(val) def extendleft(self, iterable: Iterable[Any]) -> None: """ Appends every value of iterable to the beginning of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extendleft([0, -1]) >>> our_deque_1 [-1, 0, 1, 2, 3] >>> our_deque_2 = Deque('cd') >>> our_deque_2.extendleft('ba') >>> our_deque_2 ['a', 'b', 'c', 'd'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.extendleft([0, -1]) >>> deque_collections_1 deque([-1, 0, 1, 2, 3]) >>> deque_collections_2 = deque('cd') >>> deque_collections_2.extendleft('ba') >>> deque_collections_2 deque(['a', 'b', 'c', 'd']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ for val in iterable: self.appendleft(val) def pop(self) -> Any: """ Removes the last element of the deque and returns it. Time complexity: O(1) @returns topop.val: the value of the node to pop. >>> our_deque = Deque([1, 2, 3, 15182]) >>> our_popped = our_deque.pop() >>> our_popped 15182 >>> our_deque [1, 2, 3] >>> from collections import deque >>> deque_collections = deque([1, 2, 3, 15182]) >>> collections_popped = deque_collections.pop() >>> collections_popped 15182 >>> deque_collections deque([1, 2, 3]) >>> list(our_deque) == list(deque_collections) True >>> our_popped == collections_popped True """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._back self._back = self._back.prev_node # set new back # drop the last node - python will deallocate memory automatically self._back.next_node = None self._len -= 1 return topop.val def popleft(self) -> Any: """ Removes the first element of the deque and returns it. Time complexity: O(1) @returns topop.val: the value of the node to pop. >>> our_deque = Deque([15182, 1, 2, 3]) >>> our_popped = our_deque.popleft() >>> our_popped 15182 >>> our_deque [1, 2, 3] >>> from collections import deque >>> deque_collections = deque([15182, 1, 2, 3]) >>> collections_popped = deque_collections.popleft() >>> collections_popped 15182 >>> deque_collections deque([1, 2, 3]) >>> list(our_deque) == list(deque_collections) True >>> our_popped == collections_popped True """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._front self._front = self._front.next_node # set new front and drop the first node self._front.prev_node = None self._len -= 1 return topop.val def is_empty(self) -> bool: """ Checks if the deque is empty. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> our_deque.is_empty() False >>> our_empty_deque = Deque() >>> our_empty_deque.is_empty() True >>> from collections import deque >>> empty_deque_collections = deque() >>> list(our_empty_deque) == list(empty_deque_collections) True """ return self._front is None def __len__(self) -> int: """ Implements len() function. Returns the length of the deque. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> len(our_deque) 3 >>> our_empty_deque = Deque() >>> len(our_empty_deque) 0 >>> from collections import deque >>> deque_collections = deque([1, 2, 3]) >>> len(deque_collections) 3 >>> empty_deque_collections = deque() >>> len(empty_deque_collections) 0 >>> len(our_empty_deque) == len(empty_deque_collections) True """ return self._len def __eq__(self, other: object) -> bool: """ Implements "==" operator. Returns if *self* is equal to *other*. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_2 = Deque([1, 2, 3]) >>> our_deque_1 == our_deque_2 True >>> our_deque_3 = Deque([1, 2]) >>> our_deque_1 == our_deque_3 False >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_2 = deque([1, 2, 3]) >>> deque_collections_1 == deque_collections_2 True >>> deque_collections_3 = deque([1, 2]) >>> deque_collections_1 == deque_collections_3 False >>> (our_deque_1 == our_deque_2) == (deque_collections_1 == deque_collections_2) True >>> (our_deque_1 == our_deque_3) == (deque_collections_1 == deque_collections_3) True """ if not isinstance(other, Deque): return NotImplemented me = self._front oth = other._front # if the length of the dequeues are not the same, they are not equal if len(self) != len(other): return False while me is not None and oth is not None: # compare every value if me.val != oth.val: return False me = me.next_node oth = oth.next_node return True def __iter__(self) -> Deque._Iterator: """ Implements iteration. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> for v in our_deque: ... print(v) 1 2 3 >>> from collections import deque >>> deque_collections = deque([1, 2, 3]) >>> for v in deque_collections: ... print(v) 1 2 3 """ return Deque._Iterator(self._front) def __repr__(self) -> str: """ Implements representation of the deque. Represents it as a list, with its values between '[' and ']'. Time complexity: O(n) >>> our_deque = Deque([1, 2, 3]) >>> our_deque [1, 2, 3] """ values_list = [] aux = self._front while aux is not None: # append the values in a list to display values_list.append(aux.val) aux = aux.next_node return f"[{', '.join(repr(val) for val in values_list)}]" if __name__ == "__main__": import doctest doctest.testmod()
""" Implementation of double ended queue. """ from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass from typing import Any class Deque: """ Deque data structure. Operations ---------- append(val: Any) -> None appendleft(val: Any) -> None extend(iterable: Iterable) -> None extendleft(iterable: Iterable) -> None pop() -> Any popleft() -> Any Observers --------- is_empty() -> bool Attributes ---------- _front: _Node front of the deque a.k.a. the first element _back: _Node back of the element a.k.a. the last element _len: int the number of nodes """ __slots__ = ["_front", "_back", "_len"] @dataclass class _Node: """ Representation of a node. Contains a value and a pointer to the next node as well as to the previous one. """ val: Any = None next_node: Deque._Node | None = None prev_node: Deque._Node | None = None class _Iterator: """ Helper class for iteration. Will be used to implement iteration. Attributes ---------- _cur: _Node the current node of the iteration. """ __slots__ = ["_cur"] def __init__(self, cur: Deque._Node | None) -> None: self._cur = cur def __iter__(self) -> Deque._Iterator: """ >>> our_deque = Deque([1, 2, 3]) >>> iterator = iter(our_deque) """ return self def __next__(self) -> Any: """ >>> our_deque = Deque([1, 2, 3]) >>> iterator = iter(our_deque) >>> next(iterator) 1 >>> next(iterator) 2 >>> next(iterator) 3 """ if self._cur is None: # finished iterating raise StopIteration val = self._cur.val self._cur = self._cur.next_node return val def __init__(self, iterable: Iterable[Any] | None = None) -> None: self._front: Any = None self._back: Any = None self._len: int = 0 if iterable is not None: # append every value to the deque for val in iterable: self.append(val) def append(self, val: Any) -> None: """ Adds val to the end of the deque. Time complexity: O(1) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.append(4) >>> our_deque_1 [1, 2, 3, 4] >>> our_deque_2 = Deque('ab') >>> our_deque_2.append('c') >>> our_deque_2 ['a', 'b', 'c'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.append(4) >>> deque_collections_1 deque([1, 2, 3, 4]) >>> deque_collections_2 = deque('ab') >>> deque_collections_2.append('c') >>> deque_collections_2 deque(['a', 'b', 'c']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes self._back.next_node = node node.prev_node = self._back self._back = node # assign new back to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def appendleft(self, val: Any) -> None: """ Adds val to the beginning of the deque. Time complexity: O(1) >>> our_deque_1 = Deque([2, 3]) >>> our_deque_1.appendleft(1) >>> our_deque_1 [1, 2, 3] >>> our_deque_2 = Deque('bc') >>> our_deque_2.appendleft('a') >>> our_deque_2 ['a', 'b', 'c'] >>> from collections import deque >>> deque_collections_1 = deque([2, 3]) >>> deque_collections_1.appendleft(1) >>> deque_collections_1 deque([1, 2, 3]) >>> deque_collections_2 = deque('bc') >>> deque_collections_2.appendleft('a') >>> deque_collections_2 deque(['a', 'b', 'c']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes node.next_node = self._front self._front.prev_node = node self._front = node # assign new front to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def extend(self, iterable: Iterable[Any]) -> None: """ Appends every value of iterable to the end of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extend([4, 5]) >>> our_deque_1 [1, 2, 3, 4, 5] >>> our_deque_2 = Deque('ab') >>> our_deque_2.extend('cd') >>> our_deque_2 ['a', 'b', 'c', 'd'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.extend([4, 5]) >>> deque_collections_1 deque([1, 2, 3, 4, 5]) >>> deque_collections_2 = deque('ab') >>> deque_collections_2.extend('cd') >>> deque_collections_2 deque(['a', 'b', 'c', 'd']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ for val in iterable: self.append(val) def extendleft(self, iterable: Iterable[Any]) -> None: """ Appends every value of iterable to the beginning of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extendleft([0, -1]) >>> our_deque_1 [-1, 0, 1, 2, 3] >>> our_deque_2 = Deque('cd') >>> our_deque_2.extendleft('ba') >>> our_deque_2 ['a', 'b', 'c', 'd'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.extendleft([0, -1]) >>> deque_collections_1 deque([-1, 0, 1, 2, 3]) >>> deque_collections_2 = deque('cd') >>> deque_collections_2.extendleft('ba') >>> deque_collections_2 deque(['a', 'b', 'c', 'd']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ for val in iterable: self.appendleft(val) def pop(self) -> Any: """ Removes the last element of the deque and returns it. Time complexity: O(1) @returns topop.val: the value of the node to pop. >>> our_deque = Deque([1, 2, 3, 15182]) >>> our_popped = our_deque.pop() >>> our_popped 15182 >>> our_deque [1, 2, 3] >>> from collections import deque >>> deque_collections = deque([1, 2, 3, 15182]) >>> collections_popped = deque_collections.pop() >>> collections_popped 15182 >>> deque_collections deque([1, 2, 3]) >>> list(our_deque) == list(deque_collections) True >>> our_popped == collections_popped True """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._back self._back = self._back.prev_node # set new back # drop the last node - python will deallocate memory automatically self._back.next_node = None self._len -= 1 return topop.val def popleft(self) -> Any: """ Removes the first element of the deque and returns it. Time complexity: O(1) @returns topop.val: the value of the node to pop. >>> our_deque = Deque([15182, 1, 2, 3]) >>> our_popped = our_deque.popleft() >>> our_popped 15182 >>> our_deque [1, 2, 3] >>> from collections import deque >>> deque_collections = deque([15182, 1, 2, 3]) >>> collections_popped = deque_collections.popleft() >>> collections_popped 15182 >>> deque_collections deque([1, 2, 3]) >>> list(our_deque) == list(deque_collections) True >>> our_popped == collections_popped True """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._front self._front = self._front.next_node # set new front and drop the first node self._front.prev_node = None self._len -= 1 return topop.val def is_empty(self) -> bool: """ Checks if the deque is empty. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> our_deque.is_empty() False >>> our_empty_deque = Deque() >>> our_empty_deque.is_empty() True >>> from collections import deque >>> empty_deque_collections = deque() >>> list(our_empty_deque) == list(empty_deque_collections) True """ return self._front is None def __len__(self) -> int: """ Implements len() function. Returns the length of the deque. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> len(our_deque) 3 >>> our_empty_deque = Deque() >>> len(our_empty_deque) 0 >>> from collections import deque >>> deque_collections = deque([1, 2, 3]) >>> len(deque_collections) 3 >>> empty_deque_collections = deque() >>> len(empty_deque_collections) 0 >>> len(our_empty_deque) == len(empty_deque_collections) True """ return self._len def __eq__(self, other: object) -> bool: """ Implements "==" operator. Returns if *self* is equal to *other*. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_2 = Deque([1, 2, 3]) >>> our_deque_1 == our_deque_2 True >>> our_deque_3 = Deque([1, 2]) >>> our_deque_1 == our_deque_3 False >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_2 = deque([1, 2, 3]) >>> deque_collections_1 == deque_collections_2 True >>> deque_collections_3 = deque([1, 2]) >>> deque_collections_1 == deque_collections_3 False >>> (our_deque_1 == our_deque_2) == (deque_collections_1 == deque_collections_2) True >>> (our_deque_1 == our_deque_3) == (deque_collections_1 == deque_collections_3) True """ if not isinstance(other, Deque): return NotImplemented me = self._front oth = other._front # if the length of the dequeues are not the same, they are not equal if len(self) != len(other): return False while me is not None and oth is not None: # compare every value if me.val != oth.val: return False me = me.next_node oth = oth.next_node return True def __iter__(self) -> Deque._Iterator: """ Implements iteration. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> for v in our_deque: ... print(v) 1 2 3 >>> from collections import deque >>> deque_collections = deque([1, 2, 3]) >>> for v in deque_collections: ... print(v) 1 2 3 """ return Deque._Iterator(self._front) def __repr__(self) -> str: """ Implements representation of the deque. Represents it as a list, with its values between '[' and ']'. Time complexity: O(n) >>> our_deque = Deque([1, 2, 3]) >>> our_deque [1, 2, 3] """ values_list = [] aux = self._front while aux is not None: # append the values in a list to display values_list.append(aux.val) aux = aux.next_node return f"[{', '.join(repr(val) for val in values_list)}]" if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Minimum cut on Ford_Fulkerson algorithm. test_graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def bfs(graph, s, t, parent): # Return True if there is node that has not iterated. visited = [False] * len(graph) queue = [s] visited[s] = True while queue: u = queue.pop(0) for ind in range(len(graph[u])): if visited[ind] is False and graph[u][ind] > 0: queue.append(ind) visited[ind] = True parent[ind] = u return visited[t] def mincut(graph, source, sink): """This array is filled by BFS and to store path >>> mincut(test_graph, source=0, sink=5) [(1, 3), (4, 3), (4, 5)] """ parent = [-1] * (len(graph)) max_flow = 0 res = [] temp = [i[:] for i in graph] # Record original cut, copy. while bfs(graph, source, sink, parent): path_flow = float("Inf") s = sink while s != source: # Find the minimum value in select path path_flow = min(path_flow, graph[parent[s]][s]) s = parent[s] max_flow += path_flow v = sink while v != source: u = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] for i in range(len(graph)): for j in range(len(graph[0])): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j)) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
# Minimum cut on Ford_Fulkerson algorithm. test_graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] def bfs(graph, s, t, parent): # Return True if there is node that has not iterated. visited = [False] * len(graph) queue = [s] visited[s] = True while queue: u = queue.pop(0) for ind in range(len(graph[u])): if visited[ind] is False and graph[u][ind] > 0: queue.append(ind) visited[ind] = True parent[ind] = u return visited[t] def mincut(graph, source, sink): """This array is filled by BFS and to store path >>> mincut(test_graph, source=0, sink=5) [(1, 3), (4, 3), (4, 5)] """ parent = [-1] * (len(graph)) max_flow = 0 res = [] temp = [i[:] for i in graph] # Record original cut, copy. while bfs(graph, source, sink, parent): path_flow = float("Inf") s = sink while s != source: # Find the minimum value in select path path_flow = min(path_flow, graph[parent[s]][s]) s = parent[s] max_flow += path_flow v = sink while v != source: u = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] for i in range(len(graph)): for j in range(len(graph[0])): if graph[i][j] == 0 and temp[i][j] > 0: res.append((i, j)) return res if __name__ == "__main__": print(mincut(test_graph, source=0, sink=5))
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Implementation of Basic Math in Python.""" import math def prime_factors(n: int) -> list: """Find Prime Factors. >>> prime_factors(100) [2, 2, 5, 5] >>> prime_factors(0) Traceback (most recent call last): ... ValueError: Only positive integers have prime factors >>> prime_factors(-10) Traceback (most recent call last): ... ValueError: Only positive integers have prime factors """ if n <= 0: raise ValueError("Only positive integers have prime factors") pf = [] while n % 2 == 0: pf.append(2) n = int(n / 2) for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: pf.append(i) n = int(n / i) if n > 2: pf.append(n) return pf def number_of_divisors(n: int) -> int: """Calculate Number of Divisors of an Integer. >>> number_of_divisors(100) 9 >>> number_of_divisors(0) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted >>> number_of_divisors(-10) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted """ if n <= 0: raise ValueError("Only positive numbers are accepted") div = 1 temp = 1 while n % 2 == 0: temp += 1 n = int(n / 2) div *= temp for i in range(3, int(math.sqrt(n)) + 1, 2): temp = 1 while n % i == 0: temp += 1 n = int(n / i) div *= temp if n > 1: div *= 2 return div def sum_of_divisors(n: int) -> int: """Calculate Sum of Divisors. >>> sum_of_divisors(100) 217 >>> sum_of_divisors(0) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted >>> sum_of_divisors(-10) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted """ if n <= 0: raise ValueError("Only positive numbers are accepted") s = 1 temp = 1 while n % 2 == 0: temp += 1 n = int(n / 2) if temp > 1: s *= (2**temp - 1) / (2 - 1) for i in range(3, int(math.sqrt(n)) + 1, 2): temp = 1 while n % i == 0: temp += 1 n = int(n / i) if temp > 1: s *= (i**temp - 1) / (i - 1) return int(s) def euler_phi(n: int) -> int: """Calculate Euler's Phi Function. >>> euler_phi(100) 40 """ s = n for x in set(prime_factors(n)): s *= (x - 1) / x return int(s) if __name__ == "__main__": import doctest doctest.testmod()
"""Implementation of Basic Math in Python.""" import math def prime_factors(n: int) -> list: """Find Prime Factors. >>> prime_factors(100) [2, 2, 5, 5] >>> prime_factors(0) Traceback (most recent call last): ... ValueError: Only positive integers have prime factors >>> prime_factors(-10) Traceback (most recent call last): ... ValueError: Only positive integers have prime factors """ if n <= 0: raise ValueError("Only positive integers have prime factors") pf = [] while n % 2 == 0: pf.append(2) n = int(n / 2) for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: pf.append(i) n = int(n / i) if n > 2: pf.append(n) return pf def number_of_divisors(n: int) -> int: """Calculate Number of Divisors of an Integer. >>> number_of_divisors(100) 9 >>> number_of_divisors(0) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted >>> number_of_divisors(-10) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted """ if n <= 0: raise ValueError("Only positive numbers are accepted") div = 1 temp = 1 while n % 2 == 0: temp += 1 n = int(n / 2) div *= temp for i in range(3, int(math.sqrt(n)) + 1, 2): temp = 1 while n % i == 0: temp += 1 n = int(n / i) div *= temp if n > 1: div *= 2 return div def sum_of_divisors(n: int) -> int: """Calculate Sum of Divisors. >>> sum_of_divisors(100) 217 >>> sum_of_divisors(0) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted >>> sum_of_divisors(-10) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted """ if n <= 0: raise ValueError("Only positive numbers are accepted") s = 1 temp = 1 while n % 2 == 0: temp += 1 n = int(n / 2) if temp > 1: s *= (2**temp - 1) / (2 - 1) for i in range(3, int(math.sqrt(n)) + 1, 2): temp = 1 while n % i == 0: temp += 1 n = int(n / i) if temp > 1: s *= (i**temp - 1) / (i - 1) return int(s) def euler_phi(n: int) -> int: """Calculate Euler's Phi Function. >>> euler_phi(100) 40 """ s = n for x in set(prime_factors(n)): s *= (x - 1) / x return int(s) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations # Divide and Conquer algorithm def find_max(nums: list[int | float], left: int, right: int) -> int | float: """ find max value in list :param nums: contains elements :param left: index of first element :param right: index of last element :return: max in nums >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_max(nums, 0, len(nums) - 1) == max(nums) True True True True >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] >>> find_max(nums, 0, len(nums) - 1) == max(nums) True >>> find_max([], 0, 0) Traceback (most recent call last): ... ValueError: find_max() arg is an empty sequence >>> find_max(nums, 0, len(nums)) == max(nums) Traceback (most recent call last): ... IndexError: list index out of range >>> find_max(nums, -len(nums), -1) == max(nums) True >>> find_max(nums, -len(nums) - 1, -1) == max(nums) Traceback (most recent call last): ... IndexError: list index out of range """ if len(nums) == 0: raise ValueError("find_max() arg is an empty sequence") if ( left >= len(nums) or left < -len(nums) or right >= len(nums) or right < -len(nums) ): raise IndexError("list index out of range") if left == right: return nums[left] mid = (left + right) >> 1 # the middle left_max = find_max(nums, left, mid) # find max in range[left, mid] right_max = find_max(nums, mid + 1, right) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
from __future__ import annotations # Divide and Conquer algorithm def find_max(nums: list[int | float], left: int, right: int) -> int | float: """ find max value in list :param nums: contains elements :param left: index of first element :param right: index of last element :return: max in nums >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_max(nums, 0, len(nums) - 1) == max(nums) True True True True >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] >>> find_max(nums, 0, len(nums) - 1) == max(nums) True >>> find_max([], 0, 0) Traceback (most recent call last): ... ValueError: find_max() arg is an empty sequence >>> find_max(nums, 0, len(nums)) == max(nums) Traceback (most recent call last): ... IndexError: list index out of range >>> find_max(nums, -len(nums), -1) == max(nums) True >>> find_max(nums, -len(nums) - 1, -1) == max(nums) Traceback (most recent call last): ... IndexError: list index out of range """ if len(nums) == 0: raise ValueError("find_max() arg is an empty sequence") if ( left >= len(nums) or left < -len(nums) or right >= len(nums) or right < -len(nums) ): raise IndexError("list index out of range") if left == right: return nums[left] mid = (left + right) >> 1 # the middle left_max = find_max(nums, left, mid) # find max in range[left, mid] right_max = find_max(nums, mid + 1, right) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
PNG  IHDR=iCCPICC Profile(UoT?o\?US[IB*unS6mUo xB ISA$=t@hpS]Ƹ9w>5@WI`]5;V! A'@{N\..ƅG_!7suV$BlW=}i; F)A<.&Xax,38S(b׵*%31l #O-zQvaXOP5o6Zz&⻏^wkI/#&\%x/@{7S މjPh͔&mry>k7=ߪB#@fs_{덱п0-LZ~%Gpˈ{YXf^+_s-T>D@קƸ-9!r[2]3BcnCs?>*ԮeD|%4` :X2 pQSLPRaeyqĘ י5Fit )CdL$o$rpӶb>4+̹F_{Яki+x.+B.{L<۩ =UHcnf<>F ^e||pyv%b:iX'%8Iߔ? rw[vITVQN^dpYI"|#\cz[2M^S0[zIJ/HHȟ- Ic<xx-8ZNxA-8mCkKHaYn1Ĝ {qHgu#L hs :6z!y@}zgqٺ/S4~\~Y3M9PyK=. -z$8Y7"tkHևwⳟ\87܅O$~j]n5`ffsKpYqx(@ pHYs B(xdiTXtXML:com.adobe.xmp<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="XMP Core 4.4.0"> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/"> <xmp:CreatorTool>www.inkscape.org</xmp:CreatorTool> </rdf:Description> </rdf:RDF> </x:xmpmeta> 4 IDATxyeߧ{dL.$$$! "+@EY *̪zn^f\]x@@@ $stw+$IU{>bу bUVz,\ .mJ9S?m6jEObiʏ[AC bt wbQ\ 7~/Xƀ veKiT;⹆=aIs޶yF]@nqV-rq+ EDDRR}ލa7a zຠ("Pϭ^>{kz5Ԣn8W(mz4 F#('>K[hw8 qQ(Cez(0!8;g}7iu>0Y3 @'`ii]k.f F CD܈{"'UJNAe<\qPeqj ʝL}vÇ֟tqdFk6wk+r#*xuBzc--;obʝ͍fYdn! 9:sb׮ABk6Vf7>Kv]v5]? I{tҊF0do#Ii_Z1ÆLyH6V}%slE(u <{ c>M}k<Cl>xcp K> *WǢm֯$wee\=dNfPU9zIzJ%b2κhG!Q^ܳ>A״vj,s'7bn)c} X".j>@;^<ƉFg8YecsbeH8_`YY!{_?ߝ3uπT|Y-oe xI}UP t.S,2_)? bQ8ZAjsڷ?|ퟩvc,;8]އ O.@vE8#qva3vX{+w@Ddᇩyq9柼jΎ|plU@C@J~Y7^*"2=]M]~e X QZd+f^ː\8]9T`rf u=[:Y1a8"Xւ h?OP5Toۀ{,["v ZAKmHhMKQ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5Fit )CdL$o$rpӶb>4+̹F_{Яki+x.+B.{L<۩ =UHcnf<>F ^e||pyv%b:iX'%8Iߔ? rw[vITVQN^dpYI"|#\cz[2M^S0[zIJ/HHȟ- Ic<xx-8ZNxA-8mCkKHaYn1Ĝ {qHgu#L hs :6z!y@}zgqٺ/S4~\~Y3M9PyK=. -z$8Y7"tkHևwⳟ\87܅O$~j]n5`ffsKpYqx(@ pHYs B(xdiTXtXML:com.adobe.xmp<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="XMP Core 4.4.0"> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/"> <xmp:CreatorTool>www.inkscape.org</xmp:CreatorTool> </rdf:Description> </rdf:RDF> </x:xmpmeta> 4 IDATxyeߧ{dL.$$$! "+@EY *̪zn^f\]x@@@ $stw+$IU{>bу bUVz,\ .mJ9S?m6jEObiʏ[AC bt wbQ\ 7~/Xƀ veKiT;⹆=aIs޶yF]@nqV-rq+ EDDRR}ލa7a zຠ("Pϭ^>{kz5Ԣn8W(mz4 F#('>K[hw8 qQ(Cez(0!8;g}7iu>0Y3 @'`ii]k.f F CD܈{"'UJNAe<\qPeqj ʝL}vÇ֟tqdFk6wk+r#*xuBzc--;obʝ͍fYdn! 9:sb׮ABk6Vf7>Kv]v5]? I{tҊF0do#Ii_Z1ÆLyH6V}%slE(u <{ c>M}k<Cl>xcp K> *WǢm֯$wee\=dNfPU9zIzJ%b2κhG!Q^ܳ>A״vj,s'7bn)c} X".j>@;^<ƉFg8YecsbeH8_`YY!{_?ߝ3uπT|Y-oe xI}UP t.S,2_)? bQ8ZAjsڷ?|ퟩvc,;8]އ O.@vE8#qva3vX{+w@Ddᇩyq9柼jΎ|plU@C@J~Y7^*"2=]M]~e X QZd+f^ː\8]9T`rf u=[:Y1a8"Xւ h?OP5Toۀ{,["v ZAKmHhMKQj^j8>M]*I!5 UPؚT>;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T3Fn x+gج} fjcKkE?e5Q(9jp{ ZOBtaK(bx.7˖uq0†7_ղ) 8d?&AsH{}Eo? xm?C@d1D:EmU:<a&{@o8Yʏn5M`iݳ|po|~A6eഊ2ֳ,:BɆbxYqU(nϽfvf/{wߖ#&. W.oۆiPH3/&Q(N.0~;d\Ѥ|V',_6F32_[V.<u^"\2M*~n|-GR<?Zzs3'Nq.lՅěMikkm!Dɬ=kWs& /^XYYۣh_Gۼ{`°x]`sPeye- bxYtV[_:MknI[&ouiY0{xLc]_ů#4)k*5hU]3Ŷ\)~@ӣo{n/b, / ^em5m)MAYY5D2cgW"qRWpb%8O^3<l=v.ʶ*ʯU噳 v]+ڂt@MU.ܔ֔)yZmOFG4;ʍ^ψJe"L>9K5` 5t{=`lb+b ʷJXɳ6ei+zE tWUEa6ƫ|uyZg7_' 7&q(n@q8& p!ưad`8rzͳ`?⯣m el7]Ѯ8蹶"V-U/^$%}?V)?۟ *cK@'F*cwuQTħ W84xXwr wIk&m|]m#S{n\X/tdcae(e{<C_ zu_4\ kwCε+蹶b4jnS޲mmui)SyR0l΁i.vb<gIDATQ,m7I1Ï5\[m|]Ai 2 u-uze:ptFQ5͍/ mUdx9=`+WApm,g-(]^-UЫ2u3sNCZʨ* AL /8_6ug*eekˎi9tYWˢ@Zo6=*K[FIvYB ruVzUǡl2 _UϮ򧙞[[Zp&{BZMZ<^NㅸOv4 iM]*VUumqĺ]S!=}Keuy|f£ ]̺󙟿8'P]IENDB`
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import numpy as np from sklearn.utils import shuffle import input_data random_numer = 42 np.random.seed(random_numer) def ReLu(x): mask = (x > 0) * 1.0 return mask * x def d_ReLu(x): mask = (x > 0) * 1.0 return mask def arctan(x): return np.arctan(x) def d_arctan(x): return 1 / (1 + x ** 2) def log(x): return 1 / (1 + np.exp(-1 * x)) def d_log(x): return log(x) * (1 - log(x)) def tanh(x): return np.tanh(x) def d_tanh(x): return 1 - np.tanh(x) ** 2 def plot(samples): fig = plt.figure(figsize=(4, 4)) gs = gridspec.GridSpec(4, 4) gs.update(wspace=0.05, hspace=0.05) for i, sample in enumerate(samples): ax = plt.subplot(gs[i]) plt.axis("off") ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_aspect("equal") plt.imshow(sample.reshape(28, 28), cmap="Greys_r") return fig if __name__ == "__main__": # 1. Load Data and declare hyper print("--------- Load Data ----------") mnist = input_data.read_data_sets("MNIST_data", one_hot=False) temp = mnist.test images, labels = temp.images, temp.labels images, labels = shuffle(np.asarray(images), np.asarray(labels)) num_epoch = 10 learing_rate = 0.00009 G_input = 100 hidden_input, hidden_input2, hidden_input3 = 128, 256, 346 hidden_input4, hidden_input5, hidden_input6 = 480, 560, 686 print("--------- Declare Hyper Parameters ----------") # 2. Declare Weights D_W1 = ( np.random.normal(size=(784, hidden_input), scale=(1.0 / np.sqrt(784 / 2.0))) * 0.002 ) # D_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 D_b1 = np.zeros(hidden_input) D_W2 = ( np.random.normal( size=(hidden_input, 1), scale=(1.0 / np.sqrt(hidden_input / 2.0)) ) * 0.002 ) # D_b2 = np.random.normal(size=(1),scale=(1. / np.sqrt(1 / 2.))) *0.002 D_b2 = np.zeros(1) G_W1 = ( np.random.normal( size=(G_input, hidden_input), scale=(1.0 / np.sqrt(G_input / 2.0)) ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b1 = np.zeros(hidden_input) G_W2 = ( np.random.normal( size=(hidden_input, hidden_input2), scale=(1.0 / np.sqrt(hidden_input / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b2 = np.zeros(hidden_input2) G_W3 = ( np.random.normal( size=(hidden_input2, hidden_input3), scale=(1.0 / np.sqrt(hidden_input2 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b3 = np.zeros(hidden_input3) G_W4 = ( np.random.normal( size=(hidden_input3, hidden_input4), scale=(1.0 / np.sqrt(hidden_input3 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b4 = np.zeros(hidden_input4) G_W5 = ( np.random.normal( size=(hidden_input4, hidden_input5), scale=(1.0 / np.sqrt(hidden_input4 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b5 = np.zeros(hidden_input5) G_W6 = ( np.random.normal( size=(hidden_input5, hidden_input6), scale=(1.0 / np.sqrt(hidden_input5 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b6 = np.zeros(hidden_input6) G_W7 = ( np.random.normal( size=(hidden_input6, 784), scale=(1.0 / np.sqrt(hidden_input6 / 2.0)) ) * 0.002 ) # G_b2 = np.random.normal(size=(784),scale=(1. / np.sqrt(784 / 2.))) *0.002 G_b7 = np.zeros(784) # 3. For Adam Optimzier v1, m1 = 0, 0 v2, m2 = 0, 0 v3, m3 = 0, 0 v4, m4 = 0, 0 v5, m5 = 0, 0 v6, m6 = 0, 0 v7, m7 = 0, 0 v8, m8 = 0, 0 v9, m9 = 0, 0 v10, m10 = 0, 0 v11, m11 = 0, 0 v12, m12 = 0, 0 v13, m13 = 0, 0 v14, m14 = 0, 0 v15, m15 = 0, 0 v16, m16 = 0, 0 v17, m17 = 0, 0 v18, m18 = 0, 0 beta_1, beta_2, eps = 0.9, 0.999, 0.00000001 print("--------- Started Training ----------") for iter in range(num_epoch): random_int = np.random.randint(len(images) - 5) current_image = np.expand_dims(images[random_int], axis=0) # Func: Generate The first Fake Data Z = np.random.uniform(-1.0, 1.0, size=[1, G_input]) Gl1 = Z.dot(G_W1) + G_b1 Gl1A = arctan(Gl1) Gl2 = Gl1A.dot(G_W2) + G_b2 Gl2A = ReLu(Gl2) Gl3 = Gl2A.dot(G_W3) + G_b3 Gl3A = arctan(Gl3) Gl4 = Gl3A.dot(G_W4) + G_b4 Gl4A = ReLu(Gl4) Gl5 = Gl4A.dot(G_W5) + G_b5 Gl5A = tanh(Gl5) Gl6 = Gl5A.dot(G_W6) + G_b6 Gl6A = ReLu(Gl6) Gl7 = Gl6A.dot(G_W7) + G_b7 current_fake_data = log(Gl7) # Func: Forward Feed for Real data Dl1_r = current_image.dot(D_W1) + D_b1 Dl1_rA = ReLu(Dl1_r) Dl2_r = Dl1_rA.dot(D_W2) + D_b2 Dl2_rA = log(Dl2_r) # Func: Forward Feed for Fake Data Dl1_f = current_fake_data.dot(D_W1) + D_b1 Dl1_fA = ReLu(Dl1_f) Dl2_f = Dl1_fA.dot(D_W2) + D_b2 Dl2_fA = log(Dl2_f) # Func: Cost D D_cost = -np.log(Dl2_rA) + np.log(1.0 - Dl2_fA) # Func: Gradient grad_f_w2_part_1 = 1 / (1.0 - Dl2_fA) grad_f_w2_part_2 = d_log(Dl2_f) grad_f_w2_part_3 = Dl1_fA grad_f_w2 = grad_f_w2_part_3.T.dot(grad_f_w2_part_1 * grad_f_w2_part_2) grad_f_b2 = grad_f_w2_part_1 * grad_f_w2_part_2 grad_f_w1_part_1 = (grad_f_w2_part_1 * grad_f_w2_part_2).dot(D_W2.T) grad_f_w1_part_2 = d_ReLu(Dl1_f) grad_f_w1_part_3 = current_fake_data grad_f_w1 = grad_f_w1_part_3.T.dot(grad_f_w1_part_1 * grad_f_w1_part_2) grad_f_b1 = grad_f_w1_part_1 * grad_f_w1_part_2 grad_r_w2_part_1 = -1 / Dl2_rA grad_r_w2_part_2 = d_log(Dl2_r) grad_r_w2_part_3 = Dl1_rA grad_r_w2 = grad_r_w2_part_3.T.dot(grad_r_w2_part_1 * grad_r_w2_part_2) grad_r_b2 = grad_r_w2_part_1 * grad_r_w2_part_2 grad_r_w1_part_1 = (grad_r_w2_part_1 * grad_r_w2_part_2).dot(D_W2.T) grad_r_w1_part_2 = d_ReLu(Dl1_r) grad_r_w1_part_3 = current_image grad_r_w1 = grad_r_w1_part_3.T.dot(grad_r_w1_part_1 * grad_r_w1_part_2) grad_r_b1 = grad_r_w1_part_1 * grad_r_w1_part_2 grad_w1 = grad_f_w1 + grad_r_w1 grad_b1 = grad_f_b1 + grad_r_b1 grad_w2 = grad_f_w2 + grad_r_w2 grad_b2 = grad_f_b2 + grad_r_b2 # ---- Update Gradient ---- m1 = beta_1 * m1 + (1 - beta_1) * grad_w1 v1 = beta_2 * v1 + (1 - beta_2) * grad_w1 ** 2 m2 = beta_1 * m2 + (1 - beta_1) * grad_b1 v2 = beta_2 * v2 + (1 - beta_2) * grad_b1 ** 2 m3 = beta_1 * m3 + (1 - beta_1) * grad_w2 v3 = beta_2 * v3 + (1 - beta_2) * grad_w2 ** 2 m4 = beta_1 * m4 + (1 - beta_1) * grad_b2 v4 = beta_2 * v4 + (1 - beta_2) * grad_b2 ** 2 D_W1 = D_W1 - (learing_rate / (np.sqrt(v1 / (1 - beta_2)) + eps)) * ( m1 / (1 - beta_1) ) D_b1 = D_b1 - (learing_rate / (np.sqrt(v2 / (1 - beta_2)) + eps)) * ( m2 / (1 - beta_1) ) D_W2 = D_W2 - (learing_rate / (np.sqrt(v3 / (1 - beta_2)) + eps)) * ( m3 / (1 - beta_1) ) D_b2 = D_b2 - (learing_rate / (np.sqrt(v4 / (1 - beta_2)) + eps)) * ( m4 / (1 - beta_1) ) # Func: Forward Feed for G Z = np.random.uniform(-1.0, 1.0, size=[1, G_input]) Gl1 = Z.dot(G_W1) + G_b1 Gl1A = arctan(Gl1) Gl2 = Gl1A.dot(G_W2) + G_b2 Gl2A = ReLu(Gl2) Gl3 = Gl2A.dot(G_W3) + G_b3 Gl3A = arctan(Gl3) Gl4 = Gl3A.dot(G_W4) + G_b4 Gl4A = ReLu(Gl4) Gl5 = Gl4A.dot(G_W5) + G_b5 Gl5A = tanh(Gl5) Gl6 = Gl5A.dot(G_W6) + G_b6 Gl6A = ReLu(Gl6) Gl7 = Gl6A.dot(G_W7) + G_b7 current_fake_data = log(Gl7) Dl1 = current_fake_data.dot(D_W1) + D_b1 Dl1_A = ReLu(Dl1) Dl2 = Dl1_A.dot(D_W2) + D_b2 Dl2_A = log(Dl2) # Func: Cost G G_cost = -np.log(Dl2_A) # Func: Gradient grad_G_w7_part_1 = ((-1 / Dl2_A) * d_log(Dl2).dot(D_W2.T) * (d_ReLu(Dl1))).dot( D_W1.T ) grad_G_w7_part_2 = d_log(Gl7) grad_G_w7_part_3 = Gl6A grad_G_w7 = grad_G_w7_part_3.T.dot(grad_G_w7_part_1 * grad_G_w7_part_1) grad_G_b7 = grad_G_w7_part_1 * grad_G_w7_part_2 grad_G_w6_part_1 = (grad_G_w7_part_1 * grad_G_w7_part_2).dot(G_W7.T) grad_G_w6_part_2 = d_ReLu(Gl6) grad_G_w6_part_3 = Gl5A grad_G_w6 = grad_G_w6_part_3.T.dot(grad_G_w6_part_1 * grad_G_w6_part_2) grad_G_b6 = grad_G_w6_part_1 * grad_G_w6_part_2 grad_G_w5_part_1 = (grad_G_w6_part_1 * grad_G_w6_part_2).dot(G_W6.T) grad_G_w5_part_2 = d_tanh(Gl5) grad_G_w5_part_3 = Gl4A grad_G_w5 = grad_G_w5_part_3.T.dot(grad_G_w5_part_1 * grad_G_w5_part_2) grad_G_b5 = grad_G_w5_part_1 * grad_G_w5_part_2 grad_G_w4_part_1 = (grad_G_w5_part_1 * grad_G_w5_part_2).dot(G_W5.T) grad_G_w4_part_2 = d_ReLu(Gl4) grad_G_w4_part_3 = Gl3A grad_G_w4 = grad_G_w4_part_3.T.dot(grad_G_w4_part_1 * grad_G_w4_part_2) grad_G_b4 = grad_G_w4_part_1 * grad_G_w4_part_2 grad_G_w3_part_1 = (grad_G_w4_part_1 * grad_G_w4_part_2).dot(G_W4.T) grad_G_w3_part_2 = d_arctan(Gl3) grad_G_w3_part_3 = Gl2A grad_G_w3 = grad_G_w3_part_3.T.dot(grad_G_w3_part_1 * grad_G_w3_part_2) grad_G_b3 = grad_G_w3_part_1 * grad_G_w3_part_2 grad_G_w2_part_1 = (grad_G_w3_part_1 * grad_G_w3_part_2).dot(G_W3.T) grad_G_w2_part_2 = d_ReLu(Gl2) grad_G_w2_part_3 = Gl1A grad_G_w2 = grad_G_w2_part_3.T.dot(grad_G_w2_part_1 * grad_G_w2_part_2) grad_G_b2 = grad_G_w2_part_1 * grad_G_w2_part_2 grad_G_w1_part_1 = (grad_G_w2_part_1 * grad_G_w2_part_2).dot(G_W2.T) grad_G_w1_part_2 = d_arctan(Gl1) grad_G_w1_part_3 = Z grad_G_w1 = grad_G_w1_part_3.T.dot(grad_G_w1_part_1 * grad_G_w1_part_2) grad_G_b1 = grad_G_w1_part_1 * grad_G_w1_part_2 # ---- Update Gradient ---- m5 = beta_1 * m5 + (1 - beta_1) * grad_G_w1 v5 = beta_2 * v5 + (1 - beta_2) * grad_G_w1 ** 2 m6 = beta_1 * m6 + (1 - beta_1) * grad_G_b1 v6 = beta_2 * v6 + (1 - beta_2) * grad_G_b1 ** 2 m7 = beta_1 * m7 + (1 - beta_1) * grad_G_w2 v7 = beta_2 * v7 + (1 - beta_2) * grad_G_w2 ** 2 m8 = beta_1 * m8 + (1 - beta_1) * grad_G_b2 v8 = beta_2 * v8 + (1 - beta_2) * grad_G_b2 ** 2 m9 = beta_1 * m9 + (1 - beta_1) * grad_G_w3 v9 = beta_2 * v9 + (1 - beta_2) * grad_G_w3 ** 2 m10 = beta_1 * m10 + (1 - beta_1) * grad_G_b3 v10 = beta_2 * v10 + (1 - beta_2) * grad_G_b3 ** 2 m11 = beta_1 * m11 + (1 - beta_1) * grad_G_w4 v11 = beta_2 * v11 + (1 - beta_2) * grad_G_w4 ** 2 m12 = beta_1 * m12 + (1 - beta_1) * grad_G_b4 v12 = beta_2 * v12 + (1 - beta_2) * grad_G_b4 ** 2 m13 = beta_1 * m13 + (1 - beta_1) * grad_G_w5 v13 = beta_2 * v13 + (1 - beta_2) * grad_G_w5 ** 2 m14 = beta_1 * m14 + (1 - beta_1) * grad_G_b5 v14 = beta_2 * v14 + (1 - beta_2) * grad_G_b5 ** 2 m15 = beta_1 * m15 + (1 - beta_1) * grad_G_w6 v15 = beta_2 * v15 + (1 - beta_2) * grad_G_w6 ** 2 m16 = beta_1 * m16 + (1 - beta_1) * grad_G_b6 v16 = beta_2 * v16 + (1 - beta_2) * grad_G_b6 ** 2 m17 = beta_1 * m17 + (1 - beta_1) * grad_G_w7 v17 = beta_2 * v17 + (1 - beta_2) * grad_G_w7 ** 2 m18 = beta_1 * m18 + (1 - beta_1) * grad_G_b7 v18 = beta_2 * v18 + (1 - beta_2) * grad_G_b7 ** 2 G_W1 = G_W1 - (learing_rate / (np.sqrt(v5 / (1 - beta_2)) + eps)) * ( m5 / (1 - beta_1) ) G_b1 = G_b1 - (learing_rate / (np.sqrt(v6 / (1 - beta_2)) + eps)) * ( m6 / (1 - beta_1) ) G_W2 = G_W2 - (learing_rate / (np.sqrt(v7 / (1 - beta_2)) + eps)) * ( m7 / (1 - beta_1) ) G_b2 = G_b2 - (learing_rate / (np.sqrt(v8 / (1 - beta_2)) + eps)) * ( m8 / (1 - beta_1) ) G_W3 = G_W3 - (learing_rate / (np.sqrt(v9 / (1 - beta_2)) + eps)) * ( m9 / (1 - beta_1) ) G_b3 = G_b3 - (learing_rate / (np.sqrt(v10 / (1 - beta_2)) + eps)) * ( m10 / (1 - beta_1) ) G_W4 = G_W4 - (learing_rate / (np.sqrt(v11 / (1 - beta_2)) + eps)) * ( m11 / (1 - beta_1) ) G_b4 = G_b4 - (learing_rate / (np.sqrt(v12 / (1 - beta_2)) + eps)) * ( m12 / (1 - beta_1) ) G_W5 = G_W5 - (learing_rate / (np.sqrt(v13 / (1 - beta_2)) + eps)) * ( m13 / (1 - beta_1) ) G_b5 = G_b5 - (learing_rate / (np.sqrt(v14 / (1 - beta_2)) + eps)) * ( m14 / (1 - beta_1) ) G_W6 = G_W6 - (learing_rate / (np.sqrt(v15 / (1 - beta_2)) + eps)) * ( m15 / (1 - beta_1) ) G_b6 = G_b6 - (learing_rate / (np.sqrt(v16 / (1 - beta_2)) + eps)) * ( m16 / (1 - beta_1) ) G_W7 = G_W7 - (learing_rate / (np.sqrt(v17 / (1 - beta_2)) + eps)) * ( m17 / (1 - beta_1) ) G_b7 = G_b7 - (learing_rate / (np.sqrt(v18 / (1 - beta_2)) + eps)) * ( m18 / (1 - beta_1) ) # --- Print Error ---- # print("Current Iter: ",iter, " Current D cost:",D_cost, " Current G cost: ", G_cost,end='\r') if iter == 0: learing_rate = learing_rate * 0.01 if iter == 40: learing_rate = learing_rate * 0.01 # ---- Print to Out put ---- if iter % 10 == 0: print( "Current Iter: ", iter, " Current D cost:", D_cost, " Current G cost: ", G_cost, end="\r", ) print("--------- Show Example Result See Tab Above ----------") print("--------- Wait for the image to load ---------") Z = np.random.uniform(-1.0, 1.0, size=[16, G_input]) Gl1 = Z.dot(G_W1) + G_b1 Gl1A = arctan(Gl1) Gl2 = Gl1A.dot(G_W2) + G_b2 Gl2A = ReLu(Gl2) Gl3 = Gl2A.dot(G_W3) + G_b3 Gl3A = arctan(Gl3) Gl4 = Gl3A.dot(G_W4) + G_b4 Gl4A = ReLu(Gl4) Gl5 = Gl4A.dot(G_W5) + G_b5 Gl5A = tanh(Gl5) Gl6 = Gl5A.dot(G_W6) + G_b6 Gl6A = ReLu(Gl6) Gl7 = Gl6A.dot(G_W7) + G_b7 current_fake_data = log(Gl7) fig = plot(current_fake_data) fig.savefig( "Click_Me_{}.png".format( str(iter).zfill(3) + "_Ginput_" + str(G_input) + "_hiddenone" + str(hidden_input) + "_hiddentwo" + str(hidden_input2) + "_LR_" + str(learing_rate) ), bbox_inches="tight", ) # for complete explanation visit https://towardsdatascience.com/only-numpy-implementing-gan-general-adversarial-networks-and-adam-optimizer-using-numpy-with-2a7e4e032021 # -- end code --
import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import numpy as np from sklearn.utils import shuffle import input_data random_numer = 42 np.random.seed(random_numer) def ReLu(x): mask = (x > 0) * 1.0 return mask * x def d_ReLu(x): mask = (x > 0) * 1.0 return mask def arctan(x): return np.arctan(x) def d_arctan(x): return 1 / (1 + x ** 2) def log(x): return 1 / (1 + np.exp(-1 * x)) def d_log(x): return log(x) * (1 - log(x)) def tanh(x): return np.tanh(x) def d_tanh(x): return 1 - np.tanh(x) ** 2 def plot(samples): fig = plt.figure(figsize=(4, 4)) gs = gridspec.GridSpec(4, 4) gs.update(wspace=0.05, hspace=0.05) for i, sample in enumerate(samples): ax = plt.subplot(gs[i]) plt.axis("off") ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_aspect("equal") plt.imshow(sample.reshape(28, 28), cmap="Greys_r") return fig if __name__ == "__main__": # 1. Load Data and declare hyper print("--------- Load Data ----------") mnist = input_data.read_data_sets("MNIST_data", one_hot=False) temp = mnist.test images, labels = temp.images, temp.labels images, labels = shuffle(np.asarray(images), np.asarray(labels)) num_epoch = 10 learing_rate = 0.00009 G_input = 100 hidden_input, hidden_input2, hidden_input3 = 128, 256, 346 hidden_input4, hidden_input5, hidden_input6 = 480, 560, 686 print("--------- Declare Hyper Parameters ----------") # 2. Declare Weights D_W1 = ( np.random.normal(size=(784, hidden_input), scale=(1.0 / np.sqrt(784 / 2.0))) * 0.002 ) # D_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 D_b1 = np.zeros(hidden_input) D_W2 = ( np.random.normal( size=(hidden_input, 1), scale=(1.0 / np.sqrt(hidden_input / 2.0)) ) * 0.002 ) # D_b2 = np.random.normal(size=(1),scale=(1. / np.sqrt(1 / 2.))) *0.002 D_b2 = np.zeros(1) G_W1 = ( np.random.normal( size=(G_input, hidden_input), scale=(1.0 / np.sqrt(G_input / 2.0)) ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b1 = np.zeros(hidden_input) G_W2 = ( np.random.normal( size=(hidden_input, hidden_input2), scale=(1.0 / np.sqrt(hidden_input / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b2 = np.zeros(hidden_input2) G_W3 = ( np.random.normal( size=(hidden_input2, hidden_input3), scale=(1.0 / np.sqrt(hidden_input2 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b3 = np.zeros(hidden_input3) G_W4 = ( np.random.normal( size=(hidden_input3, hidden_input4), scale=(1.0 / np.sqrt(hidden_input3 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b4 = np.zeros(hidden_input4) G_W5 = ( np.random.normal( size=(hidden_input4, hidden_input5), scale=(1.0 / np.sqrt(hidden_input4 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b5 = np.zeros(hidden_input5) G_W6 = ( np.random.normal( size=(hidden_input5, hidden_input6), scale=(1.0 / np.sqrt(hidden_input5 / 2.0)), ) * 0.002 ) # G_b1 = np.random.normal(size=(128),scale=(1. / np.sqrt(128 / 2.))) *0.002 G_b6 = np.zeros(hidden_input6) G_W7 = ( np.random.normal( size=(hidden_input6, 784), scale=(1.0 / np.sqrt(hidden_input6 / 2.0)) ) * 0.002 ) # G_b2 = np.random.normal(size=(784),scale=(1. / np.sqrt(784 / 2.))) *0.002 G_b7 = np.zeros(784) # 3. For Adam Optimzier v1, m1 = 0, 0 v2, m2 = 0, 0 v3, m3 = 0, 0 v4, m4 = 0, 0 v5, m5 = 0, 0 v6, m6 = 0, 0 v7, m7 = 0, 0 v8, m8 = 0, 0 v9, m9 = 0, 0 v10, m10 = 0, 0 v11, m11 = 0, 0 v12, m12 = 0, 0 v13, m13 = 0, 0 v14, m14 = 0, 0 v15, m15 = 0, 0 v16, m16 = 0, 0 v17, m17 = 0, 0 v18, m18 = 0, 0 beta_1, beta_2, eps = 0.9, 0.999, 0.00000001 print("--------- Started Training ----------") for iter in range(num_epoch): random_int = np.random.randint(len(images) - 5) current_image = np.expand_dims(images[random_int], axis=0) # Func: Generate The first Fake Data Z = np.random.uniform(-1.0, 1.0, size=[1, G_input]) Gl1 = Z.dot(G_W1) + G_b1 Gl1A = arctan(Gl1) Gl2 = Gl1A.dot(G_W2) + G_b2 Gl2A = ReLu(Gl2) Gl3 = Gl2A.dot(G_W3) + G_b3 Gl3A = arctan(Gl3) Gl4 = Gl3A.dot(G_W4) + G_b4 Gl4A = ReLu(Gl4) Gl5 = Gl4A.dot(G_W5) + G_b5 Gl5A = tanh(Gl5) Gl6 = Gl5A.dot(G_W6) + G_b6 Gl6A = ReLu(Gl6) Gl7 = Gl6A.dot(G_W7) + G_b7 current_fake_data = log(Gl7) # Func: Forward Feed for Real data Dl1_r = current_image.dot(D_W1) + D_b1 Dl1_rA = ReLu(Dl1_r) Dl2_r = Dl1_rA.dot(D_W2) + D_b2 Dl2_rA = log(Dl2_r) # Func: Forward Feed for Fake Data Dl1_f = current_fake_data.dot(D_W1) + D_b1 Dl1_fA = ReLu(Dl1_f) Dl2_f = Dl1_fA.dot(D_W2) + D_b2 Dl2_fA = log(Dl2_f) # Func: Cost D D_cost = -np.log(Dl2_rA) + np.log(1.0 - Dl2_fA) # Func: Gradient grad_f_w2_part_1 = 1 / (1.0 - Dl2_fA) grad_f_w2_part_2 = d_log(Dl2_f) grad_f_w2_part_3 = Dl1_fA grad_f_w2 = grad_f_w2_part_3.T.dot(grad_f_w2_part_1 * grad_f_w2_part_2) grad_f_b2 = grad_f_w2_part_1 * grad_f_w2_part_2 grad_f_w1_part_1 = (grad_f_w2_part_1 * grad_f_w2_part_2).dot(D_W2.T) grad_f_w1_part_2 = d_ReLu(Dl1_f) grad_f_w1_part_3 = current_fake_data grad_f_w1 = grad_f_w1_part_3.T.dot(grad_f_w1_part_1 * grad_f_w1_part_2) grad_f_b1 = grad_f_w1_part_1 * grad_f_w1_part_2 grad_r_w2_part_1 = -1 / Dl2_rA grad_r_w2_part_2 = d_log(Dl2_r) grad_r_w2_part_3 = Dl1_rA grad_r_w2 = grad_r_w2_part_3.T.dot(grad_r_w2_part_1 * grad_r_w2_part_2) grad_r_b2 = grad_r_w2_part_1 * grad_r_w2_part_2 grad_r_w1_part_1 = (grad_r_w2_part_1 * grad_r_w2_part_2).dot(D_W2.T) grad_r_w1_part_2 = d_ReLu(Dl1_r) grad_r_w1_part_3 = current_image grad_r_w1 = grad_r_w1_part_3.T.dot(grad_r_w1_part_1 * grad_r_w1_part_2) grad_r_b1 = grad_r_w1_part_1 * grad_r_w1_part_2 grad_w1 = grad_f_w1 + grad_r_w1 grad_b1 = grad_f_b1 + grad_r_b1 grad_w2 = grad_f_w2 + grad_r_w2 grad_b2 = grad_f_b2 + grad_r_b2 # ---- Update Gradient ---- m1 = beta_1 * m1 + (1 - beta_1) * grad_w1 v1 = beta_2 * v1 + (1 - beta_2) * grad_w1 ** 2 m2 = beta_1 * m2 + (1 - beta_1) * grad_b1 v2 = beta_2 * v2 + (1 - beta_2) * grad_b1 ** 2 m3 = beta_1 * m3 + (1 - beta_1) * grad_w2 v3 = beta_2 * v3 + (1 - beta_2) * grad_w2 ** 2 m4 = beta_1 * m4 + (1 - beta_1) * grad_b2 v4 = beta_2 * v4 + (1 - beta_2) * grad_b2 ** 2 D_W1 = D_W1 - (learing_rate / (np.sqrt(v1 / (1 - beta_2)) + eps)) * ( m1 / (1 - beta_1) ) D_b1 = D_b1 - (learing_rate / (np.sqrt(v2 / (1 - beta_2)) + eps)) * ( m2 / (1 - beta_1) ) D_W2 = D_W2 - (learing_rate / (np.sqrt(v3 / (1 - beta_2)) + eps)) * ( m3 / (1 - beta_1) ) D_b2 = D_b2 - (learing_rate / (np.sqrt(v4 / (1 - beta_2)) + eps)) * ( m4 / (1 - beta_1) ) # Func: Forward Feed for G Z = np.random.uniform(-1.0, 1.0, size=[1, G_input]) Gl1 = Z.dot(G_W1) + G_b1 Gl1A = arctan(Gl1) Gl2 = Gl1A.dot(G_W2) + G_b2 Gl2A = ReLu(Gl2) Gl3 = Gl2A.dot(G_W3) + G_b3 Gl3A = arctan(Gl3) Gl4 = Gl3A.dot(G_W4) + G_b4 Gl4A = ReLu(Gl4) Gl5 = Gl4A.dot(G_W5) + G_b5 Gl5A = tanh(Gl5) Gl6 = Gl5A.dot(G_W6) + G_b6 Gl6A = ReLu(Gl6) Gl7 = Gl6A.dot(G_W7) + G_b7 current_fake_data = log(Gl7) Dl1 = current_fake_data.dot(D_W1) + D_b1 Dl1_A = ReLu(Dl1) Dl2 = Dl1_A.dot(D_W2) + D_b2 Dl2_A = log(Dl2) # Func: Cost G G_cost = -np.log(Dl2_A) # Func: Gradient grad_G_w7_part_1 = ((-1 / Dl2_A) * d_log(Dl2).dot(D_W2.T) * (d_ReLu(Dl1))).dot( D_W1.T ) grad_G_w7_part_2 = d_log(Gl7) grad_G_w7_part_3 = Gl6A grad_G_w7 = grad_G_w7_part_3.T.dot(grad_G_w7_part_1 * grad_G_w7_part_1) grad_G_b7 = grad_G_w7_part_1 * grad_G_w7_part_2 grad_G_w6_part_1 = (grad_G_w7_part_1 * grad_G_w7_part_2).dot(G_W7.T) grad_G_w6_part_2 = d_ReLu(Gl6) grad_G_w6_part_3 = Gl5A grad_G_w6 = grad_G_w6_part_3.T.dot(grad_G_w6_part_1 * grad_G_w6_part_2) grad_G_b6 = grad_G_w6_part_1 * grad_G_w6_part_2 grad_G_w5_part_1 = (grad_G_w6_part_1 * grad_G_w6_part_2).dot(G_W6.T) grad_G_w5_part_2 = d_tanh(Gl5) grad_G_w5_part_3 = Gl4A grad_G_w5 = grad_G_w5_part_3.T.dot(grad_G_w5_part_1 * grad_G_w5_part_2) grad_G_b5 = grad_G_w5_part_1 * grad_G_w5_part_2 grad_G_w4_part_1 = (grad_G_w5_part_1 * grad_G_w5_part_2).dot(G_W5.T) grad_G_w4_part_2 = d_ReLu(Gl4) grad_G_w4_part_3 = Gl3A grad_G_w4 = grad_G_w4_part_3.T.dot(grad_G_w4_part_1 * grad_G_w4_part_2) grad_G_b4 = grad_G_w4_part_1 * grad_G_w4_part_2 grad_G_w3_part_1 = (grad_G_w4_part_1 * grad_G_w4_part_2).dot(G_W4.T) grad_G_w3_part_2 = d_arctan(Gl3) grad_G_w3_part_3 = Gl2A grad_G_w3 = grad_G_w3_part_3.T.dot(grad_G_w3_part_1 * grad_G_w3_part_2) grad_G_b3 = grad_G_w3_part_1 * grad_G_w3_part_2 grad_G_w2_part_1 = (grad_G_w3_part_1 * grad_G_w3_part_2).dot(G_W3.T) grad_G_w2_part_2 = d_ReLu(Gl2) grad_G_w2_part_3 = Gl1A grad_G_w2 = grad_G_w2_part_3.T.dot(grad_G_w2_part_1 * grad_G_w2_part_2) grad_G_b2 = grad_G_w2_part_1 * grad_G_w2_part_2 grad_G_w1_part_1 = (grad_G_w2_part_1 * grad_G_w2_part_2).dot(G_W2.T) grad_G_w1_part_2 = d_arctan(Gl1) grad_G_w1_part_3 = Z grad_G_w1 = grad_G_w1_part_3.T.dot(grad_G_w1_part_1 * grad_G_w1_part_2) grad_G_b1 = grad_G_w1_part_1 * grad_G_w1_part_2 # ---- Update Gradient ---- m5 = beta_1 * m5 + (1 - beta_1) * grad_G_w1 v5 = beta_2 * v5 + (1 - beta_2) * grad_G_w1 ** 2 m6 = beta_1 * m6 + (1 - beta_1) * grad_G_b1 v6 = beta_2 * v6 + (1 - beta_2) * grad_G_b1 ** 2 m7 = beta_1 * m7 + (1 - beta_1) * grad_G_w2 v7 = beta_2 * v7 + (1 - beta_2) * grad_G_w2 ** 2 m8 = beta_1 * m8 + (1 - beta_1) * grad_G_b2 v8 = beta_2 * v8 + (1 - beta_2) * grad_G_b2 ** 2 m9 = beta_1 * m9 + (1 - beta_1) * grad_G_w3 v9 = beta_2 * v9 + (1 - beta_2) * grad_G_w3 ** 2 m10 = beta_1 * m10 + (1 - beta_1) * grad_G_b3 v10 = beta_2 * v10 + (1 - beta_2) * grad_G_b3 ** 2 m11 = beta_1 * m11 + (1 - beta_1) * grad_G_w4 v11 = beta_2 * v11 + (1 - beta_2) * grad_G_w4 ** 2 m12 = beta_1 * m12 + (1 - beta_1) * grad_G_b4 v12 = beta_2 * v12 + (1 - beta_2) * grad_G_b4 ** 2 m13 = beta_1 * m13 + (1 - beta_1) * grad_G_w5 v13 = beta_2 * v13 + (1 - beta_2) * grad_G_w5 ** 2 m14 = beta_1 * m14 + (1 - beta_1) * grad_G_b5 v14 = beta_2 * v14 + (1 - beta_2) * grad_G_b5 ** 2 m15 = beta_1 * m15 + (1 - beta_1) * grad_G_w6 v15 = beta_2 * v15 + (1 - beta_2) * grad_G_w6 ** 2 m16 = beta_1 * m16 + (1 - beta_1) * grad_G_b6 v16 = beta_2 * v16 + (1 - beta_2) * grad_G_b6 ** 2 m17 = beta_1 * m17 + (1 - beta_1) * grad_G_w7 v17 = beta_2 * v17 + (1 - beta_2) * grad_G_w7 ** 2 m18 = beta_1 * m18 + (1 - beta_1) * grad_G_b7 v18 = beta_2 * v18 + (1 - beta_2) * grad_G_b7 ** 2 G_W1 = G_W1 - (learing_rate / (np.sqrt(v5 / (1 - beta_2)) + eps)) * ( m5 / (1 - beta_1) ) G_b1 = G_b1 - (learing_rate / (np.sqrt(v6 / (1 - beta_2)) + eps)) * ( m6 / (1 - beta_1) ) G_W2 = G_W2 - (learing_rate / (np.sqrt(v7 / (1 - beta_2)) + eps)) * ( m7 / (1 - beta_1) ) G_b2 = G_b2 - (learing_rate / (np.sqrt(v8 / (1 - beta_2)) + eps)) * ( m8 / (1 - beta_1) ) G_W3 = G_W3 - (learing_rate / (np.sqrt(v9 / (1 - beta_2)) + eps)) * ( m9 / (1 - beta_1) ) G_b3 = G_b3 - (learing_rate / (np.sqrt(v10 / (1 - beta_2)) + eps)) * ( m10 / (1 - beta_1) ) G_W4 = G_W4 - (learing_rate / (np.sqrt(v11 / (1 - beta_2)) + eps)) * ( m11 / (1 - beta_1) ) G_b4 = G_b4 - (learing_rate / (np.sqrt(v12 / (1 - beta_2)) + eps)) * ( m12 / (1 - beta_1) ) G_W5 = G_W5 - (learing_rate / (np.sqrt(v13 / (1 - beta_2)) + eps)) * ( m13 / (1 - beta_1) ) G_b5 = G_b5 - (learing_rate / (np.sqrt(v14 / (1 - beta_2)) + eps)) * ( m14 / (1 - beta_1) ) G_W6 = G_W6 - (learing_rate / (np.sqrt(v15 / (1 - beta_2)) + eps)) * ( m15 / (1 - beta_1) ) G_b6 = G_b6 - (learing_rate / (np.sqrt(v16 / (1 - beta_2)) + eps)) * ( m16 / (1 - beta_1) ) G_W7 = G_W7 - (learing_rate / (np.sqrt(v17 / (1 - beta_2)) + eps)) * ( m17 / (1 - beta_1) ) G_b7 = G_b7 - (learing_rate / (np.sqrt(v18 / (1 - beta_2)) + eps)) * ( m18 / (1 - beta_1) ) # --- Print Error ---- # print("Current Iter: ",iter, " Current D cost:",D_cost, " Current G cost: ", G_cost,end='\r') if iter == 0: learing_rate = learing_rate * 0.01 if iter == 40: learing_rate = learing_rate * 0.01 # ---- Print to Out put ---- if iter % 10 == 0: print( "Current Iter: ", iter, " Current D cost:", D_cost, " Current G cost: ", G_cost, end="\r", ) print("--------- Show Example Result See Tab Above ----------") print("--------- Wait for the image to load ---------") Z = np.random.uniform(-1.0, 1.0, size=[16, G_input]) Gl1 = Z.dot(G_W1) + G_b1 Gl1A = arctan(Gl1) Gl2 = Gl1A.dot(G_W2) + G_b2 Gl2A = ReLu(Gl2) Gl3 = Gl2A.dot(G_W3) + G_b3 Gl3A = arctan(Gl3) Gl4 = Gl3A.dot(G_W4) + G_b4 Gl4A = ReLu(Gl4) Gl5 = Gl4A.dot(G_W5) + G_b5 Gl5A = tanh(Gl5) Gl6 = Gl5A.dot(G_W6) + G_b6 Gl6A = ReLu(Gl6) Gl7 = Gl6A.dot(G_W7) + G_b7 current_fake_data = log(Gl7) fig = plot(current_fake_data) fig.savefig( "Click_Me_{}.png".format( str(iter).zfill(3) + "_Ginput_" + str(G_input) + "_hiddenone" + str(hidden_input) + "_hiddentwo" + str(hidden_input2) + "_LR_" + str(learing_rate) ), bbox_inches="tight", ) # for complete explanation visit https://towardsdatascience.com/only-numpy-implementing-gan-general-adversarial-networks-and-adam-optimizer-using-numpy-with-2a7e4e032021 # -- end code --
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import requests from bs4 import BeautifulSoup def horoscope(zodiac_sign: int, day: str) -> str: url = ( "https://www.horoscope.com/us/horoscopes/general/" f"horoscope-general-daily-{day}.aspx?sign={zodiac_sign}" ) soup = BeautifulSoup(requests.get(url).content, "html.parser") return soup.find("div", class_="main-horoscope").p.text if __name__ == "__main__": print("Daily Horoscope. \n") print( "enter your Zodiac sign number:\n", "1. Aries\n", "2. Taurus\n", "3. Gemini\n", "4. Cancer\n", "5. Leo\n", "6. Virgo\n", "7. Libra\n", "8. Scorpio\n", "9. Sagittarius\n", "10. Capricorn\n", "11. Aquarius\n", "12. Pisces\n", ) zodiac_sign = int(input("number> ").strip()) print("choose some day:\n", "yesterday\n", "today\n", "tomorrow\n") day = input("enter the day> ") horoscope_text = horoscope(zodiac_sign, day) print(horoscope_text)
import requests from bs4 import BeautifulSoup def horoscope(zodiac_sign: int, day: str) -> str: url = ( "https://www.horoscope.com/us/horoscopes/general/" f"horoscope-general-daily-{day}.aspx?sign={zodiac_sign}" ) soup = BeautifulSoup(requests.get(url).content, "html.parser") return soup.find("div", class_="main-horoscope").p.text if __name__ == "__main__": print("Daily Horoscope. \n") print( "enter your Zodiac sign number:\n", "1. Aries\n", "2. Taurus\n", "3. Gemini\n", "4. Cancer\n", "5. Leo\n", "6. Virgo\n", "7. Libra\n", "8. Scorpio\n", "9. Sagittarius\n", "10. Capricorn\n", "11. Aquarius\n", "12. Pisces\n", ) zodiac_sign = int(input("number> ").strip()) print("choose some day:\n", "yesterday\n", "today\n", "tomorrow\n") day = input("enter the day> ") horoscope_text = horoscope(zodiac_sign, day) print(horoscope_text)
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Numerical integration or quadrature for a smooth function f with known values at x_i This method is the classical approach of suming 'Equally Spaced Abscissas' method 2: "Simpson Rule" """ def method_2(boundary, steps): # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a, b, h) y = 0.0 y += (h / 3.0) * f(a) cnt = 2 for i in x_i: y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i) cnt += 1 y += (h / 3.0) * f(b) return y def make_points(a, b, h): x = a + h while x < (b - h): yield x x = x + h def f(x): # enter your function here y = (x - 0) * (x - 0) return y def main(): a = 0.0 # Lower bound of integration b = 1.0 # Upper bound of integration steps = 10.0 # define number of steps or resolution boundary = [a, b] # define boundary of integration y = method_2(boundary, steps) print(f"y = {y}") if __name__ == "__main__": main()
""" Numerical integration or quadrature for a smooth function f with known values at x_i This method is the classical approach of suming 'Equally Spaced Abscissas' method 2: "Simpson Rule" """ def method_2(boundary, steps): # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a, b, h) y = 0.0 y += (h / 3.0) * f(a) cnt = 2 for i in x_i: y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i) cnt += 1 y += (h / 3.0) * f(b) return y def make_points(a, b, h): x = a + h while x < (b - h): yield x x = x + h def f(x): # enter your function here y = (x - 0) * (x - 0) return y def main(): a = 0.0 # Lower bound of integration b = 1.0 # Upper bound of integration steps = 10.0 # define number of steps or resolution boundary = [a, b] # define boundary of integration y = method_2(boundary, steps) print(f"y = {y}") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
Unnamed repository; edit this file 'description' to name the repository.
Unnamed repository; edit this file 'description' to name the repository.
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/bin/sh # # An example hook script to prepare the commit log message. # Called by "git commit" with the name of the file that has the # commit message, followed by the description of the commit # message's source. The hook's purpose is to edit the commit # message file. If the hook fails with a non-zero status, # the commit is aborted. # # To enable this hook, rename this file to "prepare-commit-msg". # This hook includes three examples. The first one removes the # "# Please enter the commit message..." help message. # # The second includes the output of "git diff --name-status -r" # into the message, just before the "git status" output. It is # commented because it doesn't cope with --amend or with squashed # commits. # # The third example adds a Signed-off-by line to the message, that can # still be edited. This is rarely a good idea. COMMIT_MSG_FILE=$1 COMMIT_SOURCE=$2 SHA1=$3 /usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE" # case "$COMMIT_SOURCE,$SHA1" in # ,|template,) # /usr/bin/perl -i.bak -pe ' # print "\n" . `git diff --cached --name-status -r` # if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;; # *) ;; # esac # SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') # git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE" # if test -z "$COMMIT_SOURCE" # then # /usr/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE" # fi
#!/bin/sh # # An example hook script to prepare the commit log message. # Called by "git commit" with the name of the file that has the # commit message, followed by the description of the commit # message's source. The hook's purpose is to edit the commit # message file. If the hook fails with a non-zero status, # the commit is aborted. # # To enable this hook, rename this file to "prepare-commit-msg". # This hook includes three examples. The first one removes the # "# Please enter the commit message..." help message. # # The second includes the output of "git diff --name-status -r" # into the message, just before the "git status" output. It is # commented because it doesn't cope with --amend or with squashed # commits. # # The third example adds a Signed-off-by line to the message, that can # still be edited. This is rarely a good idea. COMMIT_MSG_FILE=$1 COMMIT_SOURCE=$2 SHA1=$3 /usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE" # case "$COMMIT_SOURCE,$SHA1" in # ,|template,) # /usr/bin/perl -i.bak -pe ' # print "\n" . `git diff --cached --name-status -r` # if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;; # *) ;; # esac # SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') # git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE" # if test -z "$COMMIT_SOURCE" # then # /usr/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE" # fi
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
ref: refs/remotes/origin/master
ref: refs/remotes/origin/master
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Wavelet tree is a data-structure designed to efficiently answer various range queries for arrays. Wavelets trees are different from other binary trees in the sense that the nodes are split based on the actual values of the elements and not on indices, such as the with segment trees or fenwick trees. You can read more about them here: 1. https://users.dcc.uchile.cl/~jperez/papers/ioiconf16.pdf 2. https://www.youtube.com/watch?v=4aSv9PcecDw&t=811s 3. https://www.youtube.com/watch?v=CybAgVF-MMc&t=1178s """ from __future__ import annotations test_array = [2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7] class Node: def __init__(self, length: int) -> None: self.minn: int = -1 self.maxx: int = -1 self.map_left: list[int] = [-1] * length self.left: Node | None = None self.right: Node | None = None def __repr__(self) -> str: """ >>> node = Node(length=27) >>> repr(node) 'Node(min_value=-1 max_value=-1)' >>> repr(node) == str(node) True """ return f"Node(min_value={self.minn} max_value={self.maxx})" def build_tree(arr: list[int]) -> Node | None: """ Builds the tree for arr and returns the root of the constructed tree >>> build_tree(test_array) Node(min_value=0 max_value=9) """ root = Node(len(arr)) root.minn, root.maxx = min(arr), max(arr) # Leaf node case where the node contains only one unique value if root.minn == root.maxx: return root """ Take the mean of min and max element of arr as the pivot and partition arr into left_arr and right_arr with all elements <= pivot in the left_arr and the rest in right_arr, maintaining the order of the elements, then recursively build trees for left_arr and right_arr """ pivot = (root.minn + root.maxx) // 2 left_arr: list[int] = [] right_arr: list[int] = [] for index, num in enumerate(arr): if num <= pivot: left_arr.append(num) else: right_arr.append(num) root.map_left[index] = len(left_arr) root.left = build_tree(left_arr) root.right = build_tree(right_arr) return root def rank_till_index(node: Node | None, num: int, index: int) -> int: """ Returns the number of occurrences of num in interval [0, index] in the list >>> root = build_tree(test_array) >>> rank_till_index(root, 6, 6) 1 >>> rank_till_index(root, 2, 0) 1 >>> rank_till_index(root, 1, 10) 2 >>> rank_till_index(root, 17, 7) 0 >>> rank_till_index(root, 0, 9) 1 """ if index < 0 or node is None: return 0 # Leaf node cases if node.minn == node.maxx: return index + 1 if node.minn == num else 0 pivot = (node.minn + node.maxx) // 2 if num <= pivot: # go the left subtree and map index to the left subtree return rank_till_index(node.left, num, node.map_left[index] - 1) else: # go to the right subtree and map index to the right subtree return rank_till_index(node.right, num, index - node.map_left[index]) def rank(node: Node | None, num: int, start: int, end: int) -> int: """ Returns the number of occurrences of num in interval [start, end] in the list >>> root = build_tree(test_array) >>> rank(root, 6, 3, 13) 2 >>> rank(root, 2, 0, 19) 4 >>> rank(root, 9, 2 ,2) 0 >>> rank(root, 0, 5, 10) 2 """ if start > end: return 0 rank_till_end = rank_till_index(node, num, end) rank_before_start = rank_till_index(node, num, start - 1) return rank_till_end - rank_before_start def quantile(node: Node | None, index: int, start: int, end: int) -> int: """ Returns the index'th smallest element in interval [start, end] in the list index is 0-indexed >>> root = build_tree(test_array) >>> quantile(root, 2, 2, 5) 5 >>> quantile(root, 5, 2, 13) 4 >>> quantile(root, 0, 6, 6) 8 >>> quantile(root, 4, 2, 5) -1 """ if index > (end - start) or start > end or node is None: return -1 # Leaf node case if node.minn == node.maxx: return node.minn # Number of elements in the left subtree in interval [start, end] num_elements_in_left_tree = node.map_left[end] - ( node.map_left[start - 1] if start else 0 ) if num_elements_in_left_tree > index: return quantile( node.left, index, (node.map_left[start - 1] if start else 0), node.map_left[end] - 1, ) else: return quantile( node.right, index - num_elements_in_left_tree, start - (node.map_left[start - 1] if start else 0), end - node.map_left[end], ) def range_counting( node: Node | None, start: int, end: int, start_num: int, end_num: int ) -> int: """ Returns the number of elements in range [start_num, end_num] in interval [start, end] in the list >>> root = build_tree(test_array) >>> range_counting(root, 1, 10, 3, 7) 3 >>> range_counting(root, 2, 2, 1, 4) 1 >>> range_counting(root, 0, 19, 0, 100) 20 >>> range_counting(root, 1, 0, 1, 100) 0 >>> range_counting(root, 0, 17, 100, 1) 0 """ if ( start > end or node is None or start_num > end_num or node.minn > end_num or node.maxx < start_num ): return 0 if start_num <= node.minn and node.maxx <= end_num: return end - start + 1 left = range_counting( node.left, (node.map_left[start - 1] if start else 0), node.map_left[end] - 1, start_num, end_num, ) right = range_counting( node.right, start - (node.map_left[start - 1] if start else 0), end - node.map_left[end], start_num, end_num, ) return left + right if __name__ == "__main__": import doctest doctest.testmod()
""" Wavelet tree is a data-structure designed to efficiently answer various range queries for arrays. Wavelets trees are different from other binary trees in the sense that the nodes are split based on the actual values of the elements and not on indices, such as the with segment trees or fenwick trees. You can read more about them here: 1. https://users.dcc.uchile.cl/~jperez/papers/ioiconf16.pdf 2. https://www.youtube.com/watch?v=4aSv9PcecDw&t=811s 3. https://www.youtube.com/watch?v=CybAgVF-MMc&t=1178s """ from __future__ import annotations test_array = [2, 1, 4, 5, 6, 0, 8, 9, 1, 2, 0, 6, 4, 2, 0, 6, 5, 3, 2, 7] class Node: def __init__(self, length: int) -> None: self.minn: int = -1 self.maxx: int = -1 self.map_left: list[int] = [-1] * length self.left: Node | None = None self.right: Node | None = None def __repr__(self) -> str: """ >>> node = Node(length=27) >>> repr(node) 'Node(min_value=-1 max_value=-1)' >>> repr(node) == str(node) True """ return f"Node(min_value={self.minn} max_value={self.maxx})" def build_tree(arr: list[int]) -> Node | None: """ Builds the tree for arr and returns the root of the constructed tree >>> build_tree(test_array) Node(min_value=0 max_value=9) """ root = Node(len(arr)) root.minn, root.maxx = min(arr), max(arr) # Leaf node case where the node contains only one unique value if root.minn == root.maxx: return root """ Take the mean of min and max element of arr as the pivot and partition arr into left_arr and right_arr with all elements <= pivot in the left_arr and the rest in right_arr, maintaining the order of the elements, then recursively build trees for left_arr and right_arr """ pivot = (root.minn + root.maxx) // 2 left_arr: list[int] = [] right_arr: list[int] = [] for index, num in enumerate(arr): if num <= pivot: left_arr.append(num) else: right_arr.append(num) root.map_left[index] = len(left_arr) root.left = build_tree(left_arr) root.right = build_tree(right_arr) return root def rank_till_index(node: Node | None, num: int, index: int) -> int: """ Returns the number of occurrences of num in interval [0, index] in the list >>> root = build_tree(test_array) >>> rank_till_index(root, 6, 6) 1 >>> rank_till_index(root, 2, 0) 1 >>> rank_till_index(root, 1, 10) 2 >>> rank_till_index(root, 17, 7) 0 >>> rank_till_index(root, 0, 9) 1 """ if index < 0 or node is None: return 0 # Leaf node cases if node.minn == node.maxx: return index + 1 if node.minn == num else 0 pivot = (node.minn + node.maxx) // 2 if num <= pivot: # go the left subtree and map index to the left subtree return rank_till_index(node.left, num, node.map_left[index] - 1) else: # go to the right subtree and map index to the right subtree return rank_till_index(node.right, num, index - node.map_left[index]) def rank(node: Node | None, num: int, start: int, end: int) -> int: """ Returns the number of occurrences of num in interval [start, end] in the list >>> root = build_tree(test_array) >>> rank(root, 6, 3, 13) 2 >>> rank(root, 2, 0, 19) 4 >>> rank(root, 9, 2 ,2) 0 >>> rank(root, 0, 5, 10) 2 """ if start > end: return 0 rank_till_end = rank_till_index(node, num, end) rank_before_start = rank_till_index(node, num, start - 1) return rank_till_end - rank_before_start def quantile(node: Node | None, index: int, start: int, end: int) -> int: """ Returns the index'th smallest element in interval [start, end] in the list index is 0-indexed >>> root = build_tree(test_array) >>> quantile(root, 2, 2, 5) 5 >>> quantile(root, 5, 2, 13) 4 >>> quantile(root, 0, 6, 6) 8 >>> quantile(root, 4, 2, 5) -1 """ if index > (end - start) or start > end or node is None: return -1 # Leaf node case if node.minn == node.maxx: return node.minn # Number of elements in the left subtree in interval [start, end] num_elements_in_left_tree = node.map_left[end] - ( node.map_left[start - 1] if start else 0 ) if num_elements_in_left_tree > index: return quantile( node.left, index, (node.map_left[start - 1] if start else 0), node.map_left[end] - 1, ) else: return quantile( node.right, index - num_elements_in_left_tree, start - (node.map_left[start - 1] if start else 0), end - node.map_left[end], ) def range_counting( node: Node | None, start: int, end: int, start_num: int, end_num: int ) -> int: """ Returns the number of elements in range [start_num, end_num] in interval [start, end] in the list >>> root = build_tree(test_array) >>> range_counting(root, 1, 10, 3, 7) 3 >>> range_counting(root, 2, 2, 1, 4) 1 >>> range_counting(root, 0, 19, 0, 100) 20 >>> range_counting(root, 1, 0, 1, 100) 0 >>> range_counting(root, 0, 17, 100, 1) 0 """ if ( start > end or node is None or start_num > end_num or node.minn > end_num or node.maxx < start_num ): return 0 if start_num <= node.minn and node.maxx <= end_num: return end - start + 1 left = range_counting( node.left, (node.map_left[start - 1] if start else 0), node.map_left[end] - 1, start_num, end_num, ) right = range_counting( node.right, start - (node.map_left[start - 1] if start else 0), end - node.map_left[end], start_num, end_num, ) return left + right if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 """ A Polybius Square is a table that allows someone to translate letters into numbers. https://www.braingle.com/brainteasers/codes/polybius.php """ import numpy as np SQUARE = [ ["a", "b", "c", "d", "e"], ["f", "g", "h", "i", "k"], ["l", "m", "n", "o", "p"], ["q", "r", "s", "t", "u"], ["v", "w", "x", "y", "z"], ] class PolybiusCipher: def __init__(self) -> None: self.SQUARE = np.array(SQUARE) def letter_to_numbers(self, letter: str) -> np.ndarray: """ Return the pair of numbers that represents the given letter in the polybius square >>> np.array_equal(PolybiusCipher().letter_to_numbers('a'), [1,1]) True >>> np.array_equal(PolybiusCipher().letter_to_numbers('u'), [4,5]) True """ index1, index2 = np.where(self.SQUARE == letter) indexes = np.concatenate([index1 + 1, index2 + 1]) return indexes def numbers_to_letter(self, index1: int, index2: int) -> str: """ Return the letter corresponding to the position [index1, index2] in the polybius square >>> PolybiusCipher().numbers_to_letter(4, 5) == "u" True >>> PolybiusCipher().numbers_to_letter(1, 1) == "a" True """ return self.SQUARE[index1 - 1, index2 - 1] def encode(self, message: str) -> str: """ Return the encoded version of message according to the polybius cipher >>> PolybiusCipher().encode("test message") == "44154344 32154343112215" True >>> PolybiusCipher().encode("Test Message") == "44154344 32154343112215" True """ message = message.lower() message = message.replace("j", "i") encoded_message = "" for letter_index in range(len(message)): if message[letter_index] != " ": numbers = self.letter_to_numbers(message[letter_index]) encoded_message = encoded_message + str(numbers[0]) + str(numbers[1]) elif message[letter_index] == " ": encoded_message = encoded_message + " " return encoded_message def decode(self, message: str) -> str: """ Return the decoded version of message according to the polybius cipher >>> PolybiusCipher().decode("44154344 32154343112215") == "test message" True >>> PolybiusCipher().decode("4415434432154343112215") == "testmessage" True """ message = message.replace(" ", " ") decoded_message = "" for numbers_index in range(int(len(message) / 2)): if message[numbers_index * 2] != " ": index1 = message[numbers_index * 2] index2 = message[numbers_index * 2 + 1] letter = self.numbers_to_letter(int(index1), int(index2)) decoded_message = decoded_message + letter elif message[numbers_index * 2] == " ": decoded_message = decoded_message + " " return decoded_message
#!/usr/bin/env python3 """ A Polybius Square is a table that allows someone to translate letters into numbers. https://www.braingle.com/brainteasers/codes/polybius.php """ import numpy as np SQUARE = [ ["a", "b", "c", "d", "e"], ["f", "g", "h", "i", "k"], ["l", "m", "n", "o", "p"], ["q", "r", "s", "t", "u"], ["v", "w", "x", "y", "z"], ] class PolybiusCipher: def __init__(self) -> None: self.SQUARE = np.array(SQUARE) def letter_to_numbers(self, letter: str) -> np.ndarray: """ Return the pair of numbers that represents the given letter in the polybius square >>> np.array_equal(PolybiusCipher().letter_to_numbers('a'), [1,1]) True >>> np.array_equal(PolybiusCipher().letter_to_numbers('u'), [4,5]) True """ index1, index2 = np.where(self.SQUARE == letter) indexes = np.concatenate([index1 + 1, index2 + 1]) return indexes def numbers_to_letter(self, index1: int, index2: int) -> str: """ Return the letter corresponding to the position [index1, index2] in the polybius square >>> PolybiusCipher().numbers_to_letter(4, 5) == "u" True >>> PolybiusCipher().numbers_to_letter(1, 1) == "a" True """ return self.SQUARE[index1 - 1, index2 - 1] def encode(self, message: str) -> str: """ Return the encoded version of message according to the polybius cipher >>> PolybiusCipher().encode("test message") == "44154344 32154343112215" True >>> PolybiusCipher().encode("Test Message") == "44154344 32154343112215" True """ message = message.lower() message = message.replace("j", "i") encoded_message = "" for letter_index in range(len(message)): if message[letter_index] != " ": numbers = self.letter_to_numbers(message[letter_index]) encoded_message = encoded_message + str(numbers[0]) + str(numbers[1]) elif message[letter_index] == " ": encoded_message = encoded_message + " " return encoded_message def decode(self, message: str) -> str: """ Return the decoded version of message according to the polybius cipher >>> PolybiusCipher().decode("44154344 32154343112215") == "test message" True >>> PolybiusCipher().decode("4415434432154343112215") == "testmessage" True """ message = message.replace(" ", " ") decoded_message = "" for numbers_index in range(int(len(message) / 2)): if message[numbers_index * 2] != " ": index1 = message[numbers_index * 2] index2 = message[numbers_index * 2 + 1] letter = self.numbers_to_letter(int(index1), int(index2)) decoded_message = decoded_message + letter elif message[numbers_index * 2] == " ": decoded_message = decoded_message + " " return decoded_message
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 13: https://projecteuler.net/problem=13 Problem Statement: Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. """ import os def solution(): """ Returns the first ten digits of the sum of the array elements from the file num.txt >>> solution() '5537376230' """ file_path = os.path.join(os.path.dirname(__file__), "num.txt") with open(file_path) as file_hand: return str(sum(int(line) for line in file_hand))[:10] if __name__ == "__main__": print(solution())
""" Problem 13: https://projecteuler.net/problem=13 Problem Statement: Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. """ import os def solution(): """ Returns the first ten digits of the sum of the array elements from the file num.txt >>> solution() '5537376230' """ file_path = os.path.join(os.path.dirname(__file__), "num.txt") with open(file_path) as file_hand: return str(sum(int(line) for line in file_hand))[:10] if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 44: https://projecteuler.net/problem=44 Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are: 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal. Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of D? """ def is_pentagonal(n: int) -> bool: """ Returns True if n is pentagonal, False otherwise. >>> is_pentagonal(330) True >>> is_pentagonal(7683) False >>> is_pentagonal(2380) True """ root = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def solution(limit: int = 5000) -> int: """ Returns the minimum difference of two pentagonal numbers P1 and P2 such that P1 + P2 is pentagonal and P2 - P1 is pentagonal. >>> solution(5000) 5482660 """ pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)] for i, pentagonal_i in enumerate(pentagonal_nums): for j in range(i, len(pentagonal_nums)): pentagonal_j = pentagonal_nums[j] a = pentagonal_i + pentagonal_j b = pentagonal_j - pentagonal_i if is_pentagonal(a) and is_pentagonal(b): return b return -1 if __name__ == "__main__": print(f"{solution() = }")
""" Problem 44: https://projecteuler.net/problem=44 Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are: 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal. Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D = |Pk − Pj| is minimised; what is the value of D? """ def is_pentagonal(n: int) -> bool: """ Returns True if n is pentagonal, False otherwise. >>> is_pentagonal(330) True >>> is_pentagonal(7683) False >>> is_pentagonal(2380) True """ root = (1 + 24 * n) ** 0.5 return ((1 + root) / 6) % 1 == 0 def solution(limit: int = 5000) -> int: """ Returns the minimum difference of two pentagonal numbers P1 and P2 such that P1 + P2 is pentagonal and P2 - P1 is pentagonal. >>> solution(5000) 5482660 """ pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)] for i, pentagonal_i in enumerate(pentagonal_nums): for j in range(i, len(pentagonal_nums)): pentagonal_j = pentagonal_nums[j] a = pentagonal_i + pentagonal_j b = pentagonal_j - pentagonal_i if is_pentagonal(a) and is_pentagonal(b): return b return -1 if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,007
Upgrade to flake8 v6
### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-11-29T14:16:34Z"
"2022-11-29T15:56:42Z"
f32d611689dc72bda67f1c4636ab1599c60d27a4
08c22457058207dc465b9ba9fd95659d33b3f1dd
Upgrade to flake8 v6. ### Describe your change: The [new version of flake8](https://pypi.org/project/flake8/) complains about misplaced comments in `.flake8` `flake8-broken-line` is not compatible with flake8 v6 -- wemake-services/flake8-broken-line#280 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Three distinct points are plotted at random on a Cartesian plane, for which -1000 ≤ x, y ≤ 1000, such that a triangle is formed. Consider the following two triangles: A(-340,495), B(-153,-910), C(835,-947) X(-175,41), Y(-421,-714), Z(574,-645) It can be verified that triangle ABC contains the origin, whereas triangle XYZ does not. Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the coordinates of one thousand "random" triangles, find the number of triangles for which the interior contains the origin. NOTE: The first two examples in the file represent the triangles in the example given above. """ from __future__ import annotations from pathlib import Path def vector_product(point1: tuple[int, int], point2: tuple[int, int]) -> int: """ Return the 2-d vector product of two vectors. >>> vector_product((1, 2), (-5, 0)) 10 >>> vector_product((3, 1), (6, 10)) 24 """ return point1[0] * point2[1] - point1[1] * point2[0] def contains_origin(x1: int, y1: int, x2: int, y2: int, x3: int, y3: int) -> bool: """ Check if the triangle given by the points A(x1, y1), B(x2, y2), C(x3, y3) contains the origin. >>> contains_origin(-340, 495, -153, -910, 835, -947) True >>> contains_origin(-175, 41, -421, -714, 574, -645) False """ point_a: tuple[int, int] = (x1, y1) point_a_to_b: tuple[int, int] = (x2 - x1, y2 - y1) point_a_to_c: tuple[int, int] = (x3 - x1, y3 - y1) a: float = -vector_product(point_a, point_a_to_b) / vector_product( point_a_to_c, point_a_to_b ) b: float = +vector_product(point_a, point_a_to_c) / vector_product( point_a_to_c, point_a_to_b ) return a > 0 and b > 0 and a + b < 1 def solution(filename: str = "p102_triangles.txt") -> int: """ Find the number of triangles whose interior contains the origin. >>> solution("test_triangles.txt") 1 """ data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8") triangles: list[list[int]] = [] for line in data.strip().split("\n"): triangles.append([int(number) for number in line.split(",")]) ret: int = 0 triangle: list[int] for triangle in triangles: ret += contains_origin(*triangle) return ret if __name__ == "__main__": print(f"{solution() = }")
""" Three distinct points are plotted at random on a Cartesian plane, for which -1000 ≤ x, y ≤ 1000, such that a triangle is formed. Consider the following two triangles: A(-340,495), B(-153,-910), C(835,-947) X(-175,41), Y(-421,-714), Z(574,-645) It can be verified that triangle ABC contains the origin, whereas triangle XYZ does not. Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the coordinates of one thousand "random" triangles, find the number of triangles for which the interior contains the origin. NOTE: The first two examples in the file represent the triangles in the example given above. """ from __future__ import annotations from pathlib import Path def vector_product(point1: tuple[int, int], point2: tuple[int, int]) -> int: """ Return the 2-d vector product of two vectors. >>> vector_product((1, 2), (-5, 0)) 10 >>> vector_product((3, 1), (6, 10)) 24 """ return point1[0] * point2[1] - point1[1] * point2[0] def contains_origin(x1: int, y1: int, x2: int, y2: int, x3: int, y3: int) -> bool: """ Check if the triangle given by the points A(x1, y1), B(x2, y2), C(x3, y3) contains the origin. >>> contains_origin(-340, 495, -153, -910, 835, -947) True >>> contains_origin(-175, 41, -421, -714, 574, -645) False """ point_a: tuple[int, int] = (x1, y1) point_a_to_b: tuple[int, int] = (x2 - x1, y2 - y1) point_a_to_c: tuple[int, int] = (x3 - x1, y3 - y1) a: float = -vector_product(point_a, point_a_to_b) / vector_product( point_a_to_c, point_a_to_b ) b: float = +vector_product(point_a, point_a_to_c) / vector_product( point_a_to_c, point_a_to_b ) return a > 0 and b > 0 and a + b < 1 def solution(filename: str = "p102_triangles.txt") -> int: """ Find the number of triangles whose interior contains the origin. >>> solution("test_triangles.txt") 1 """ data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8") triangles: list[list[int]] = [] for line in data.strip().split("\n"): triangles.append([int(number) for number in line.split(",")]) ret: int = 0 triangle: list[int] for triangle in triangles: ret += contains_origin(*triangle) return ret if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Convert a positive Decimal Number to Any Other Representation""" from string import ascii_uppercase ALPHABET_VALUES = {str(ord(c) - 55): c for c in ascii_uppercase} def decimal_to_any(num: int, base: int) -> str: """ Convert a positive integer to another base as str. >>> decimal_to_any(0, 2) '0' >>> decimal_to_any(5, 4) '11' >>> decimal_to_any(20, 3) '202' >>> decimal_to_any(58, 16) '3A' >>> decimal_to_any(243, 17) 'E5' >>> decimal_to_any(34923, 36) 'QY3' >>> decimal_to_any(10, 11) 'A' >>> decimal_to_any(16, 16) '10' >>> decimal_to_any(36, 36) '10' >>> # negatives will error >>> decimal_to_any(-45, 8) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: parameter must be positive int >>> # floats will error >>> decimal_to_any(34.4, 6) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: int() can't convert non-string with explicit base >>> # a float base will error >>> decimal_to_any(5, 2.5) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> # a str base will error >>> decimal_to_any(10, '16') # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'str' object cannot be interpreted as an integer >>> # a base less than 2 will error >>> decimal_to_any(7, 0) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: base must be >= 2 >>> # a base greater than 36 will error >>> decimal_to_any(34, 37) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: base must be <= 36 """ if isinstance(num, float): raise TypeError("int() can't convert non-string with explicit base") if num < 0: raise ValueError("parameter must be positive int") if isinstance(base, str): raise TypeError("'str' object cannot be interpreted as an integer") if isinstance(base, float): raise TypeError("'float' object cannot be interpreted as an integer") if base in (0, 1): raise ValueError("base must be >= 2") if base > 36: raise ValueError("base must be <= 36") new_value = "" mod = 0 div = 0 while div != 1: div, mod = divmod(num, base) if base >= 11 and 9 < mod < 36: actual_value = ALPHABET_VALUES[str(mod)] mod = actual_value new_value += str(mod) div = num // base num = div if div == 0: return str(new_value[::-1]) elif div == 1: new_value += str(div) return str(new_value[::-1]) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(1000): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
"""Convert a positive Decimal Number to Any Other Representation""" from string import ascii_uppercase ALPHABET_VALUES = {str(ord(c) - 55): c for c in ascii_uppercase} def decimal_to_any(num: int, base: int) -> str: """ Convert a positive integer to another base as str. >>> decimal_to_any(0, 2) '0' >>> decimal_to_any(5, 4) '11' >>> decimal_to_any(20, 3) '202' >>> decimal_to_any(58, 16) '3A' >>> decimal_to_any(243, 17) 'E5' >>> decimal_to_any(34923, 36) 'QY3' >>> decimal_to_any(10, 11) 'A' >>> decimal_to_any(16, 16) '10' >>> decimal_to_any(36, 36) '10' >>> # negatives will error >>> decimal_to_any(-45, 8) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: parameter must be positive int >>> # floats will error >>> decimal_to_any(34.4, 6) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: int() can't convert non-string with explicit base >>> # a float base will error >>> decimal_to_any(5, 2.5) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> # a str base will error >>> decimal_to_any(10, '16') # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'str' object cannot be interpreted as an integer >>> # a base less than 2 will error >>> decimal_to_any(7, 0) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: base must be >= 2 >>> # a base greater than 36 will error >>> decimal_to_any(34, 37) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: base must be <= 36 """ if isinstance(num, float): raise TypeError("int() can't convert non-string with explicit base") if num < 0: raise ValueError("parameter must be positive int") if isinstance(base, str): raise TypeError("'str' object cannot be interpreted as an integer") if isinstance(base, float): raise TypeError("'float' object cannot be interpreted as an integer") if base in (0, 1): raise ValueError("base must be >= 2") if base > 36: raise ValueError("base must be <= 36") new_value = "" mod = 0 div = 0 while div != 1: div, mod = divmod(num, base) if base >= 11 and 9 < mod < 36: actual_value = ALPHABET_VALUES[str(mod)] else: actual_value = str(mod) new_value += actual_value div = num // base num = div if div == 0: return str(new_value[::-1]) elif div == 1: new_value += str(div) return str(new_value[::-1]) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(1000): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Linked Lists consists of Nodes. Nodes contain data and also may link to other nodes: - Head Node: First node, the address of the head node gives us access of the complete list - Last node: points to null """ from __future__ import annotations from typing import Any class Node: def __init__(self, item: Any, next: Any) -> None: # noqa: A002 self.item = item self.next = next class LinkedList: def __init__(self) -> None: self.head: Node | None = None self.size = 0 def add(self, item: Any) -> None: self.head = Node(item, self.head) self.size += 1 def remove(self) -> Any: # Switched 'self.is_empty()' to 'self.head is None' # because mypy was considering the possibility that 'self.head' # can be None in below else part and giving error if self.head is None: return None else: item = self.head.item self.head = self.head.next self.size -= 1 return item def is_empty(self) -> bool: return self.head is None def __str__(self) -> str: """ >>> linked_list = LinkedList() >>> linked_list.add(23) >>> linked_list.add(14) >>> linked_list.add(9) >>> print(linked_list) 9 --> 14 --> 23 """ if not self.is_empty: return "" else: iterate = self.head item_str = "" item_list: list[str] = [] while iterate: item_list.append(str(iterate.item)) iterate = iterate.next item_str = " --> ".join(item_list) return item_str def __len__(self) -> int: """ >>> linked_list = LinkedList() >>> len(linked_list) 0 >>> linked_list.add("a") >>> len(linked_list) 1 >>> linked_list.add("b") >>> len(linked_list) 2 >>> _ = linked_list.remove() >>> len(linked_list) 1 >>> _ = linked_list.remove() >>> len(linked_list) 0 """ return self.size
""" Linked Lists consists of Nodes. Nodes contain data and also may link to other nodes: - Head Node: First node, the address of the head node gives us access of the complete list - Last node: points to null """ from __future__ import annotations from typing import Any class Node: def __init__(self, item: Any, next: Any) -> None: # noqa: A002 self.item = item self.next = next class LinkedList: def __init__(self) -> None: self.head: Node | None = None self.size = 0 def add(self, item: Any) -> None: self.head = Node(item, self.head) self.size += 1 def remove(self) -> Any: # Switched 'self.is_empty()' to 'self.head is None' # because mypy was considering the possibility that 'self.head' # can be None in below else part and giving error if self.head is None: return None else: item = self.head.item self.head = self.head.next self.size -= 1 return item def is_empty(self) -> bool: return self.head is None def __str__(self) -> str: """ >>> linked_list = LinkedList() >>> linked_list.add(23) >>> linked_list.add(14) >>> linked_list.add(9) >>> print(linked_list) 9 --> 14 --> 23 """ if self.is_empty(): return "" else: iterate = self.head item_str = "" item_list: list[str] = [] while iterate: item_list.append(str(iterate.item)) iterate = iterate.next item_str = " --> ".join(item_list) return item_str def __len__(self) -> int: """ >>> linked_list = LinkedList() >>> len(linked_list) 0 >>> linked_list.add("a") >>> len(linked_list) 1 >>> linked_list.add("b") >>> len(linked_list) 2 >>> _ = linked_list.remove() >>> len(linked_list) 1 >>> _ = linked_list.remove() >>> len(linked_list) 0 """ return self.size
1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# An OOP approach to representing and manipulating matrices from __future__ import annotations class Matrix: """ Matrix object generated from a 2D array where each element is an array representing a row. Rows can contain type int or float. Common operations and information available. >>> rows = [ ... [1, 2, 3], ... [4, 5, 6], ... [7, 8, 9] ... ] >>> matrix = Matrix(rows) >>> print(matrix) [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]] Matrix rows and columns are available as 2D arrays >>> matrix.rows [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> matrix.columns() [[1, 4, 7], [2, 5, 8], [3, 6, 9]] Order is returned as a tuple >>> matrix.order (3, 3) Squareness and invertability are represented as bool >>> matrix.is_square True >>> matrix.is_invertable() False Identity, Minors, Cofactors and Adjugate are returned as Matrices. Inverse can be a Matrix or Nonetype >>> print(matrix.identity()) [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]] >>> print(matrix.minors()) [[-3. -6. -3.] [-6. -12. -6.] [-3. -6. -3.]] >>> print(matrix.cofactors()) [[-3. 6. -3.] [6. -12. 6.] [-3. 6. -3.]] >>> # won't be apparent due to the nature of the cofactor matrix >>> print(matrix.adjugate()) [[-3. 6. -3.] [6. -12. 6.] [-3. 6. -3.]] >>> matrix.inverse() Traceback (most recent call last): ... TypeError: Only matrices with a non-zero determinant have an inverse Determinant is an int, float, or Nonetype >>> matrix.determinant() 0 Negation, scalar multiplication, addition, subtraction, multiplication and exponentiation are available and all return a Matrix >>> print(-matrix) [[-1. -2. -3.] [-4. -5. -6.] [-7. -8. -9.]] >>> matrix2 = matrix * 3 >>> print(matrix2) [[3. 6. 9.] [12. 15. 18.] [21. 24. 27.]] >>> print(matrix + matrix2) [[4. 8. 12.] [16. 20. 24.] [28. 32. 36.]] >>> print(matrix - matrix2) [[-2. -4. -6.] [-8. -10. -12.] [-14. -16. -18.]] >>> print(matrix ** 3) [[468. 576. 684.] [1062. 1305. 1548.] [1656. 2034. 2412.]] Matrices can also be modified >>> matrix.add_row([10, 11, 12]) >>> print(matrix) [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.] [10. 11. 12.]] >>> matrix2.add_column([8, 16, 32]) >>> print(matrix2) [[3. 6. 9. 8.] [12. 15. 18. 16.] [21. 24. 27. 32.]] >>> print(matrix * matrix2) [[90. 108. 126. 136.] [198. 243. 288. 304.] [306. 378. 450. 472.] [414. 513. 612. 640.]] """ def __init__(self, rows: list[list[int]]): error = TypeError( "Matrices must be formed from a list of zero or more lists containing at " "least one and the same number of values, each of which must be of type " "int or float." ) if len(rows) != 0: cols = len(rows[0]) if cols == 0: raise error for row in rows: if len(row) != cols: raise error for value in row: if not isinstance(value, (int, float)): raise error self.rows = rows else: self.rows = [] # MATRIX INFORMATION def columns(self) -> list[list[int]]: return [[row[i] for row in self.rows] for i in range(len(self.rows[0]))] @property def num_rows(self) -> int: return len(self.rows) @property def num_columns(self) -> int: return len(self.rows[0]) @property def order(self) -> tuple[int, int]: return (self.num_rows, self.num_columns) @property def is_square(self) -> bool: return self.order[0] == self.order[1] def identity(self) -> Matrix: values = [ [0 if column_num != row_num else 1 for column_num in range(self.num_rows)] for row_num in range(self.num_rows) ] return Matrix(values) def determinant(self) -> int: if not self.is_square: return 0 if self.order == (0, 0): return 1 if self.order == (1, 1): return int(self.rows[0][0]) if self.order == (2, 2): return int( (self.rows[0][0] * self.rows[1][1]) - (self.rows[0][1] * self.rows[1][0]) ) else: return sum( self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns) ) def is_invertable(self) -> bool: return bool(self.determinant()) def get_minor(self, row: int, column: int) -> int: values = [ [ self.rows[other_row][other_column] for other_column in range(self.num_columns) if other_column != column ] for other_row in range(self.num_rows) if other_row != row ] return Matrix(values).determinant() def get_cofactor(self, row: int, column: int) -> int: if (row + column) % 2 == 0: return self.get_minor(row, column) return -1 * self.get_minor(row, column) def minors(self) -> Matrix: return Matrix( [ [self.get_minor(row, column) for column in range(self.num_columns)] for row in range(self.num_rows) ] ) def cofactors(self) -> Matrix: return Matrix( [ [ self.minors().rows[row][column] if (row + column) % 2 == 0 else self.minors().rows[row][column] * -1 for column in range(self.minors().num_columns) ] for row in range(self.minors().num_rows) ] ) def adjugate(self) -> Matrix: values = [ [self.cofactors().rows[column][row] for column in range(self.num_columns)] for row in range(self.num_rows) ] return Matrix(values) def inverse(self) -> Matrix: determinant = self.determinant() if not determinant: raise TypeError("Only matrices with a non-zero determinant have an inverse") return self.adjugate() * (1 / determinant) def __repr__(self) -> str: return str(self.rows) def __str__(self) -> str: if self.num_rows == 0: return "[]" if self.num_rows == 1: return "[[" + ". ".join(str(self.rows[0])) + "]]" return ( "[" + "\n ".join( [ "[" + ". ".join([str(value) for value in row]) + ".]" for row in self.rows ] ) + "]" ) # MATRIX MANIPULATION def add_row(self, row: list[int], position: int | None = None) -> None: type_error = TypeError("Row must be a list containing all ints and/or floats") if not isinstance(row, list): raise type_error for value in row: if not isinstance(value, (int, float)): raise type_error if len(row) != self.num_columns: raise ValueError( "Row must be equal in length to the other rows in the matrix" ) if position is None: self.rows.append(row) else: self.rows = self.rows[0:position] + [row] + self.rows[position:] def add_column(self, column: list[int], position: int | None = None) -> None: type_error = TypeError( "Column must be a list containing all ints and/or floats" ) if not isinstance(column, list): raise type_error for value in column: if not isinstance(value, (int, float)): raise type_error if len(column) != self.num_rows: raise ValueError( "Column must be equal in length to the other columns in the matrix" ) if position is None: self.rows = [self.rows[i] + [column[i]] for i in range(self.num_rows)] else: self.rows = [ self.rows[i][0:position] + [column[i]] + self.rows[i][position:] for i in range(self.num_rows) ] # MATRIX OPERATIONS def __eq__(self, other: object) -> bool: if not isinstance(other, Matrix): return NotImplemented return self.rows == other.rows def __ne__(self, other: object) -> bool: return not self == other def __neg__(self) -> Matrix: return self * -1 def __add__(self, other: Matrix) -> Matrix: if self.order != other.order: raise ValueError("Addition requires matrices of the same order") return Matrix( [ [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __sub__(self, other: Matrix) -> Matrix: if self.order != other.order: raise ValueError("Subtraction requires matrices of the same order") return Matrix( [ [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __mul__(self, other: Matrix | int | float) -> Matrix: if isinstance(other, (int, float)): return Matrix( [[int(element * other) for element in row] for row in self.rows] ) elif isinstance(other, Matrix): if self.num_columns != other.num_rows: raise ValueError( "The number of columns in the first matrix must " "be equal to the number of rows in the second" ) return Matrix( [ [Matrix.dot_product(row, column) for column in other.columns()] for row in self.rows ] ) else: raise TypeError( "A Matrix can only be multiplied by an int, float, or another matrix" ) def __pow__(self, other: int) -> Matrix: if not isinstance(other, int): raise TypeError("A Matrix can only be raised to the power of an int") if not self.is_square: raise ValueError("Only square matrices can be raised to a power") if other == 0: return self.identity() if other < 0: if self.is_invertable: return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ) result = self for _ in range(other - 1): result *= self return result @classmethod def dot_product(cls, row: list[int], column: list[int]) -> int: return sum(row[i] * column[i] for i in range(len(row))) if __name__ == "__main__": import doctest doctest.testmod()
# An OOP approach to representing and manipulating matrices from __future__ import annotations class Matrix: """ Matrix object generated from a 2D array where each element is an array representing a row. Rows can contain type int or float. Common operations and information available. >>> rows = [ ... [1, 2, 3], ... [4, 5, 6], ... [7, 8, 9] ... ] >>> matrix = Matrix(rows) >>> print(matrix) [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.]] Matrix rows and columns are available as 2D arrays >>> matrix.rows [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> matrix.columns() [[1, 4, 7], [2, 5, 8], [3, 6, 9]] Order is returned as a tuple >>> matrix.order (3, 3) Squareness and invertability are represented as bool >>> matrix.is_square True >>> matrix.is_invertable() False Identity, Minors, Cofactors and Adjugate are returned as Matrices. Inverse can be a Matrix or Nonetype >>> print(matrix.identity()) [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]] >>> print(matrix.minors()) [[-3. -6. -3.] [-6. -12. -6.] [-3. -6. -3.]] >>> print(matrix.cofactors()) [[-3. 6. -3.] [6. -12. 6.] [-3. 6. -3.]] >>> # won't be apparent due to the nature of the cofactor matrix >>> print(matrix.adjugate()) [[-3. 6. -3.] [6. -12. 6.] [-3. 6. -3.]] >>> matrix.inverse() Traceback (most recent call last): ... TypeError: Only matrices with a non-zero determinant have an inverse Determinant is an int, float, or Nonetype >>> matrix.determinant() 0 Negation, scalar multiplication, addition, subtraction, multiplication and exponentiation are available and all return a Matrix >>> print(-matrix) [[-1. -2. -3.] [-4. -5. -6.] [-7. -8. -9.]] >>> matrix2 = matrix * 3 >>> print(matrix2) [[3. 6. 9.] [12. 15. 18.] [21. 24. 27.]] >>> print(matrix + matrix2) [[4. 8. 12.] [16. 20. 24.] [28. 32. 36.]] >>> print(matrix - matrix2) [[-2. -4. -6.] [-8. -10. -12.] [-14. -16. -18.]] >>> print(matrix ** 3) [[468. 576. 684.] [1062. 1305. 1548.] [1656. 2034. 2412.]] Matrices can also be modified >>> matrix.add_row([10, 11, 12]) >>> print(matrix) [[1. 2. 3.] [4. 5. 6.] [7. 8. 9.] [10. 11. 12.]] >>> matrix2.add_column([8, 16, 32]) >>> print(matrix2) [[3. 6. 9. 8.] [12. 15. 18. 16.] [21. 24. 27. 32.]] >>> print(matrix * matrix2) [[90. 108. 126. 136.] [198. 243. 288. 304.] [306. 378. 450. 472.] [414. 513. 612. 640.]] """ def __init__(self, rows: list[list[int]]): error = TypeError( "Matrices must be formed from a list of zero or more lists containing at " "least one and the same number of values, each of which must be of type " "int or float." ) if len(rows) != 0: cols = len(rows[0]) if cols == 0: raise error for row in rows: if len(row) != cols: raise error for value in row: if not isinstance(value, (int, float)): raise error self.rows = rows else: self.rows = [] # MATRIX INFORMATION def columns(self) -> list[list[int]]: return [[row[i] for row in self.rows] for i in range(len(self.rows[0]))] @property def num_rows(self) -> int: return len(self.rows) @property def num_columns(self) -> int: return len(self.rows[0]) @property def order(self) -> tuple[int, int]: return (self.num_rows, self.num_columns) @property def is_square(self) -> bool: return self.order[0] == self.order[1] def identity(self) -> Matrix: values = [ [0 if column_num != row_num else 1 for column_num in range(self.num_rows)] for row_num in range(self.num_rows) ] return Matrix(values) def determinant(self) -> int: if not self.is_square: return 0 if self.order == (0, 0): return 1 if self.order == (1, 1): return int(self.rows[0][0]) if self.order == (2, 2): return int( (self.rows[0][0] * self.rows[1][1]) - (self.rows[0][1] * self.rows[1][0]) ) else: return sum( self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns) ) def is_invertable(self) -> bool: return bool(self.determinant()) def get_minor(self, row: int, column: int) -> int: values = [ [ self.rows[other_row][other_column] for other_column in range(self.num_columns) if other_column != column ] for other_row in range(self.num_rows) if other_row != row ] return Matrix(values).determinant() def get_cofactor(self, row: int, column: int) -> int: if (row + column) % 2 == 0: return self.get_minor(row, column) return -1 * self.get_minor(row, column) def minors(self) -> Matrix: return Matrix( [ [self.get_minor(row, column) for column in range(self.num_columns)] for row in range(self.num_rows) ] ) def cofactors(self) -> Matrix: return Matrix( [ [ self.minors().rows[row][column] if (row + column) % 2 == 0 else self.minors().rows[row][column] * -1 for column in range(self.minors().num_columns) ] for row in range(self.minors().num_rows) ] ) def adjugate(self) -> Matrix: values = [ [self.cofactors().rows[column][row] for column in range(self.num_columns)] for row in range(self.num_rows) ] return Matrix(values) def inverse(self) -> Matrix: determinant = self.determinant() if not determinant: raise TypeError("Only matrices with a non-zero determinant have an inverse") return self.adjugate() * (1 / determinant) def __repr__(self) -> str: return str(self.rows) def __str__(self) -> str: if self.num_rows == 0: return "[]" if self.num_rows == 1: return "[[" + ". ".join(str(self.rows[0])) + "]]" return ( "[" + "\n ".join( [ "[" + ". ".join([str(value) for value in row]) + ".]" for row in self.rows ] ) + "]" ) # MATRIX MANIPULATION def add_row(self, row: list[int], position: int | None = None) -> None: type_error = TypeError("Row must be a list containing all ints and/or floats") if not isinstance(row, list): raise type_error for value in row: if not isinstance(value, (int, float)): raise type_error if len(row) != self.num_columns: raise ValueError( "Row must be equal in length to the other rows in the matrix" ) if position is None: self.rows.append(row) else: self.rows = self.rows[0:position] + [row] + self.rows[position:] def add_column(self, column: list[int], position: int | None = None) -> None: type_error = TypeError( "Column must be a list containing all ints and/or floats" ) if not isinstance(column, list): raise type_error for value in column: if not isinstance(value, (int, float)): raise type_error if len(column) != self.num_rows: raise ValueError( "Column must be equal in length to the other columns in the matrix" ) if position is None: self.rows = [self.rows[i] + [column[i]] for i in range(self.num_rows)] else: self.rows = [ self.rows[i][0:position] + [column[i]] + self.rows[i][position:] for i in range(self.num_rows) ] # MATRIX OPERATIONS def __eq__(self, other: object) -> bool: if not isinstance(other, Matrix): return NotImplemented return self.rows == other.rows def __ne__(self, other: object) -> bool: return not self == other def __neg__(self) -> Matrix: return self * -1 def __add__(self, other: Matrix) -> Matrix: if self.order != other.order: raise ValueError("Addition requires matrices of the same order") return Matrix( [ [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __sub__(self, other: Matrix) -> Matrix: if self.order != other.order: raise ValueError("Subtraction requires matrices of the same order") return Matrix( [ [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns)] for i in range(self.num_rows) ] ) def __mul__(self, other: Matrix | int | float) -> Matrix: if isinstance(other, (int, float)): return Matrix( [[int(element * other) for element in row] for row in self.rows] ) elif isinstance(other, Matrix): if self.num_columns != other.num_rows: raise ValueError( "The number of columns in the first matrix must " "be equal to the number of rows in the second" ) return Matrix( [ [Matrix.dot_product(row, column) for column in other.columns()] for row in self.rows ] ) else: raise TypeError( "A Matrix can only be multiplied by an int, float, or another matrix" ) def __pow__(self, other: int) -> Matrix: if not isinstance(other, int): raise TypeError("A Matrix can only be raised to the power of an int") if not self.is_square: raise ValueError("Only square matrices can be raised to a power") if other == 0: return self.identity() if other < 0: if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ) result = self for _ in range(other - 1): result *= self return result @classmethod def dot_product(cls, row: list[int], column: list[int]) -> int: return sum(row[i] * column[i] for i in range(len(row))) if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" In a multi-threaded download, this algorithm could be used to provide each worker thread with a block of non-overlapping bytes to download. For example: for i in allocation_list: requests.get(url,headers={'Range':f'bytes={i}'}) """ from __future__ import annotations def allocation_num(number_of_bytes: int, partitions: int) -> list[str]: """ Divide a number of bytes into x partitions. :param number_of_bytes: the total of bytes. :param partitions: the number of partition need to be allocated. :return: list of bytes to be assigned to each worker thread >>> allocation_num(16647, 4) ['1-4161', '4162-8322', '8323-12483', '12484-16647'] >>> allocation_num(50000, 5) ['1-10000', '10001-20000', '20001-30000', '30001-40000', '40001-50000'] >>> allocation_num(888, 999) Traceback (most recent call last): ... ValueError: partitions can not > number_of_bytes! >>> allocation_num(888, -4) Traceback (most recent call last): ... ValueError: partitions must be a positive number! """ if partitions <= 0: raise ValueError("partitions must be a positive number!") if partitions > number_of_bytes: raise ValueError("partitions can not > number_of_bytes!") bytes_per_partition = number_of_bytes // partitions allocation_list = [] for i in range(partitions): start_bytes = i * bytes_per_partition + 1 end_bytes = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f"{start_bytes}-{end_bytes}") return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
""" In a multi-threaded download, this algorithm could be used to provide each worker thread with a block of non-overlapping bytes to download. For example: for i in allocation_list: requests.get(url,headers={'Range':f'bytes={i}'}) """ from __future__ import annotations def allocation_num(number_of_bytes: int, partitions: int) -> list[str]: """ Divide a number of bytes into x partitions. :param number_of_bytes: the total of bytes. :param partitions: the number of partition need to be allocated. :return: list of bytes to be assigned to each worker thread >>> allocation_num(16647, 4) ['1-4161', '4162-8322', '8323-12483', '12484-16647'] >>> allocation_num(50000, 5) ['1-10000', '10001-20000', '20001-30000', '30001-40000', '40001-50000'] >>> allocation_num(888, 999) Traceback (most recent call last): ... ValueError: partitions can not > number_of_bytes! >>> allocation_num(888, -4) Traceback (most recent call last): ... ValueError: partitions must be a positive number! """ if partitions <= 0: raise ValueError("partitions must be a positive number!") if partitions > number_of_bytes: raise ValueError("partitions can not > number_of_bytes!") bytes_per_partition = number_of_bytes // partitions allocation_list = [] for i in range(partitions): start_bytes = i * bytes_per_partition + 1 end_bytes = ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f"{start_bytes}-{end_bytes}") return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Source: https://github.com/jason9075/opencv-mosaic-data-aug""" import glob import os import random from string import ascii_lowercase, digits import cv2 import numpy as np # Parrameters OUTPUT_SIZE = (720, 1280) # Height, Width SCALE_RANGE = (0.4, 0.6) # if height or width lower than this scale, drop it. FILTER_TINY_SCALE = 1 / 100 LABEL_DIR = "" IMG_DIR = "" OUTPUT_DIR = "" NUMBER_IMAGES = 250 def main() -> None: """ Get images list and annotations list from input dir. Update new images and annotations. Save images and annotations in output dir. """ img_paths, annos = get_dataset(LABEL_DIR, IMG_DIR) for index in range(NUMBER_IMAGES): idxs = random.sample(range(len(annos)), 4) new_image, new_annos, path = update_image_and_anno( img_paths, annos, idxs, OUTPUT_SIZE, SCALE_RANGE, filter_scale=FILTER_TINY_SCALE, ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' letter_code = random_chars(32) file_name = path.split(os.sep)[-1].rsplit(".", 1)[0] file_root = f"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}" cv2.imwrite(f"{file_root}.jpg", new_image, [cv2.IMWRITE_JPEG_QUALITY, 85]) print(f"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}") annos_list = [] for anno in new_annos: width = anno[3] - anno[1] height = anno[4] - anno[2] x_center = anno[1] + width / 2 y_center = anno[2] + height / 2 obj = f"{anno[0]} {x_center} {y_center} {width} {height}" annos_list.append(obj) with open(f"{file_root}.txt", "w") as outfile: outfile.write("\n".join(line for line in annos_list)) def get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]: """ - label_dir <type: str>: Path to label include annotation of images - img_dir <type: str>: Path to folder contain images Return <type: list>: List of images path and labels """ img_paths = [] labels = [] for label_file in glob.glob(os.path.join(label_dir, "*.txt")): label_name = label_file.split(os.sep)[-1].rsplit(".", 1)[0] with open(label_file) as in_file: obj_lists = in_file.readlines() img_path = os.path.join(img_dir, f"{label_name}.jpg") boxes = [] for obj_list in obj_lists: obj = obj_list.rstrip("\n").split(" ") xmin = float(obj[1]) - float(obj[3]) / 2 ymin = float(obj[2]) - float(obj[4]) / 2 xmax = float(obj[1]) + float(obj[3]) / 2 ymax = float(obj[2]) + float(obj[4]) / 2 boxes.append([int(obj[0]), xmin, ymin, xmax, ymax]) if not boxes: continue img_paths.append(img_path) labels.append(boxes) return img_paths, labels def update_image_and_anno( all_img_list: list, all_annos: list, idxs: list[int], output_size: tuple[int, int], scale_range: tuple[float, float], filter_scale: float = 0.0, ) -> tuple[list, list, str]: """ - all_img_list <type: list>: list of all images - all_annos <type: list>: list of all annotations of specific image - idxs <type: list>: index of image in list - output_size <type: tuple>: size of output image (Height, Width) - scale_range <type: tuple>: range of scale image - filter_scale <type: float>: the condition of downscale image and bounding box Return: - output_img <type: narray>: image after resize - new_anno <type: list>: list of new annotation after scale - path[0] <type: string>: get the name of image file """ output_img = np.zeros([output_size[0], output_size[1], 3], dtype=np.uint8) scale_x = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) scale_y = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) divid_point_x = int(scale_x * output_size[1]) divid_point_y = int(scale_y * output_size[0]) new_anno = [] path_list = [] for i, index in enumerate(idxs): path = all_img_list[index] path_list.append(path) img_annos = all_annos[index] img = cv2.imread(path) if i == 0: # top-left img = cv2.resize(img, (divid_point_x, divid_point_y)) output_img[:divid_point_y, :divid_point_x, :] = img for bbox in img_annos: xmin = bbox[1] * scale_x ymin = bbox[2] * scale_y xmax = bbox[3] * scale_x ymax = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) elif i == 1: # top-right img = cv2.resize(img, (output_size[1] - divid_point_x, divid_point_y)) output_img[:divid_point_y, divid_point_x : output_size[1], :] = img for bbox in img_annos: xmin = scale_x + bbox[1] * (1 - scale_x) ymin = bbox[2] * scale_y xmax = scale_x + bbox[3] * (1 - scale_x) ymax = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) elif i == 2: # bottom-left img = cv2.resize(img, (divid_point_x, output_size[0] - divid_point_y)) output_img[divid_point_y : output_size[0], :divid_point_x, :] = img for bbox in img_annos: xmin = bbox[1] * scale_x ymin = scale_y + bbox[2] * (1 - scale_y) xmax = bbox[3] * scale_x ymax = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) else: # bottom-right img = cv2.resize( img, (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) output_img[ divid_point_y : output_size[0], divid_point_x : output_size[1], : ] = img for bbox in img_annos: xmin = scale_x + bbox[1] * (1 - scale_x) ymin = scale_y + bbox[2] * (1 - scale_y) xmax = scale_x + bbox[3] * (1 - scale_x) ymax = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) # Remove bounding box small than scale of filter if 0 < filter_scale: new_anno = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def random_chars(number_char: int) -> str: """ Automatic generate random 32 characters. Get random string code: '7b7ad245cdff75241935e4dd860f3bad' >>> len(random_chars(32)) 32 """ assert number_char > 1, "The number of character should greater than 1" letter_code = ascii_lowercase + digits return "".join(random.choice(letter_code) for _ in range(number_char)) if __name__ == "__main__": main() print("DONE ✅")
"""Source: https://github.com/jason9075/opencv-mosaic-data-aug""" import glob import os import random from string import ascii_lowercase, digits import cv2 import numpy as np # Parrameters OUTPUT_SIZE = (720, 1280) # Height, Width SCALE_RANGE = (0.4, 0.6) # if height or width lower than this scale, drop it. FILTER_TINY_SCALE = 1 / 100 LABEL_DIR = "" IMG_DIR = "" OUTPUT_DIR = "" NUMBER_IMAGES = 250 def main() -> None: """ Get images list and annotations list from input dir. Update new images and annotations. Save images and annotations in output dir. """ img_paths, annos = get_dataset(LABEL_DIR, IMG_DIR) for index in range(NUMBER_IMAGES): idxs = random.sample(range(len(annos)), 4) new_image, new_annos, path = update_image_and_anno( img_paths, annos, idxs, OUTPUT_SIZE, SCALE_RANGE, filter_scale=FILTER_TINY_SCALE, ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' letter_code = random_chars(32) file_name = path.split(os.sep)[-1].rsplit(".", 1)[0] file_root = f"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}" cv2.imwrite(f"{file_root}.jpg", new_image, [cv2.IMWRITE_JPEG_QUALITY, 85]) print(f"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}") annos_list = [] for anno in new_annos: width = anno[3] - anno[1] height = anno[4] - anno[2] x_center = anno[1] + width / 2 y_center = anno[2] + height / 2 obj = f"{anno[0]} {x_center} {y_center} {width} {height}" annos_list.append(obj) with open(f"{file_root}.txt", "w") as outfile: outfile.write("\n".join(line for line in annos_list)) def get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]: """ - label_dir <type: str>: Path to label include annotation of images - img_dir <type: str>: Path to folder contain images Return <type: list>: List of images path and labels """ img_paths = [] labels = [] for label_file in glob.glob(os.path.join(label_dir, "*.txt")): label_name = label_file.split(os.sep)[-1].rsplit(".", 1)[0] with open(label_file) as in_file: obj_lists = in_file.readlines() img_path = os.path.join(img_dir, f"{label_name}.jpg") boxes = [] for obj_list in obj_lists: obj = obj_list.rstrip("\n").split(" ") xmin = float(obj[1]) - float(obj[3]) / 2 ymin = float(obj[2]) - float(obj[4]) / 2 xmax = float(obj[1]) + float(obj[3]) / 2 ymax = float(obj[2]) + float(obj[4]) / 2 boxes.append([int(obj[0]), xmin, ymin, xmax, ymax]) if not boxes: continue img_paths.append(img_path) labels.append(boxes) return img_paths, labels def update_image_and_anno( all_img_list: list, all_annos: list, idxs: list[int], output_size: tuple[int, int], scale_range: tuple[float, float], filter_scale: float = 0.0, ) -> tuple[list, list, str]: """ - all_img_list <type: list>: list of all images - all_annos <type: list>: list of all annotations of specific image - idxs <type: list>: index of image in list - output_size <type: tuple>: size of output image (Height, Width) - scale_range <type: tuple>: range of scale image - filter_scale <type: float>: the condition of downscale image and bounding box Return: - output_img <type: narray>: image after resize - new_anno <type: list>: list of new annotation after scale - path[0] <type: string>: get the name of image file """ output_img = np.zeros([output_size[0], output_size[1], 3], dtype=np.uint8) scale_x = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) scale_y = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) divid_point_x = int(scale_x * output_size[1]) divid_point_y = int(scale_y * output_size[0]) new_anno = [] path_list = [] for i, index in enumerate(idxs): path = all_img_list[index] path_list.append(path) img_annos = all_annos[index] img = cv2.imread(path) if i == 0: # top-left img = cv2.resize(img, (divid_point_x, divid_point_y)) output_img[:divid_point_y, :divid_point_x, :] = img for bbox in img_annos: xmin = bbox[1] * scale_x ymin = bbox[2] * scale_y xmax = bbox[3] * scale_x ymax = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) elif i == 1: # top-right img = cv2.resize(img, (output_size[1] - divid_point_x, divid_point_y)) output_img[:divid_point_y, divid_point_x : output_size[1], :] = img for bbox in img_annos: xmin = scale_x + bbox[1] * (1 - scale_x) ymin = bbox[2] * scale_y xmax = scale_x + bbox[3] * (1 - scale_x) ymax = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) elif i == 2: # bottom-left img = cv2.resize(img, (divid_point_x, output_size[0] - divid_point_y)) output_img[divid_point_y : output_size[0], :divid_point_x, :] = img for bbox in img_annos: xmin = bbox[1] * scale_x ymin = scale_y + bbox[2] * (1 - scale_y) xmax = bbox[3] * scale_x ymax = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) else: # bottom-right img = cv2.resize( img, (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) output_img[ divid_point_y : output_size[0], divid_point_x : output_size[1], : ] = img for bbox in img_annos: xmin = scale_x + bbox[1] * (1 - scale_x) ymin = scale_y + bbox[2] * (1 - scale_y) xmax = scale_x + bbox[3] * (1 - scale_x) ymax = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) # Remove bounding box small than scale of filter if 0 < filter_scale: new_anno = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def random_chars(number_char: int) -> str: """ Automatic generate random 32 characters. Get random string code: '7b7ad245cdff75241935e4dd860f3bad' >>> len(random_chars(32)) 32 """ assert number_char > 1, "The number of character should greater than 1" letter_code = ascii_lowercase + digits return "".join(random.choice(letter_code) for _ in range(number_char)) if __name__ == "__main__": main() print("DONE ✅")
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" * Binary Exponentiation with Multiplication * This is a method to find a*b in a time complexity of O(log b) * This is one of the most commonly used methods of finding result of multiplication. * Also useful in cases where solution to (a*b)%c is required, * where a,b,c can be numbers over the computers calculation limits. * Done using iteration, can also be done using recursion * @author chinmoy159 * @version 1.0 dated 10/08/2017 """ def b_expo(a, b): res = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def b_expo_mod(a, b, c): res = 0 while b > 0: if b & 1: res = ((res % c) + (a % c)) % c a += a b >>= 1 return res """ * Wondering how this method works ! * It's pretty simple. * Let's say you need to calculate a ^ b * RULE 1 : a * b = (a+a) * (b/2) ---- example : 4 * 4 = (4+4) * (4/2) = 8 * 2 * RULE 2 : IF b is ODD, then ---- a * b = a + (a * (b - 1)) :: where (b - 1) is even. * Once b is even, repeat the process to get a * b * Repeat the process till b = 1 OR b = 0, because a*1 = a AND a*0 = 0 * * As far as the modulo is concerned, * the fact : (a+b) % c = ((a%c) + (b%c)) % c * Now apply RULE 1 OR 2, whichever is required. """
""" * Binary Exponentiation with Multiplication * This is a method to find a*b in a time complexity of O(log b) * This is one of the most commonly used methods of finding result of multiplication. * Also useful in cases where solution to (a*b)%c is required, * where a,b,c can be numbers over the computers calculation limits. * Done using iteration, can also be done using recursion * @author chinmoy159 * @version 1.0 dated 10/08/2017 """ def b_expo(a, b): res = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def b_expo_mod(a, b, c): res = 0 while b > 0: if b & 1: res = ((res % c) + (a % c)) % c a += a b >>= 1 return res """ * Wondering how this method works ! * It's pretty simple. * Let's say you need to calculate a ^ b * RULE 1 : a * b = (a+a) * (b/2) ---- example : 4 * 4 = (4+4) * (4/2) = 8 * 2 * RULE 2 : IF b is ODD, then ---- a * b = a + (a * (b - 1)) :: where (b - 1) is even. * Once b is even, repeat the process to get a * b * Repeat the process till b = 1 OR b = 0, because a*1 = a AND a*0 = 0 * * As far as the modulo is concerned, * the fact : (a+b) % c = ((a%c) + (b%c)) % c * Now apply RULE 1 OR 2, whichever is required. """
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def search(list_data: list, key: int, left: int = 0, right: int = 0) -> int: """ Iterate through the array to find the index of key using recursion. :param list_data: the list to be searched :param key: the key to be searched :param left: the index of first element :param right: the index of last element :return: the index of key value if found, -1 otherwise. >>> search(list(range(0, 11)), 5) 5 >>> search([1, 2, 4, 5, 3], 4) 2 >>> search([1, 2, 4, 5, 3], 6) -1 >>> search([5], 5) 0 >>> search([], 1) -1 """ right = right or len(list_data) - 1 if left > right: return -1 elif list_data[left] == key: return left elif list_data[right] == key: return right else: return search(list_data, key, left + 1, right - 1) if __name__ == "__main__": import doctest doctest.testmod()
def search(list_data: list, key: int, left: int = 0, right: int = 0) -> int: """ Iterate through the array to find the index of key using recursion. :param list_data: the list to be searched :param key: the key to be searched :param left: the index of first element :param right: the index of last element :return: the index of key value if found, -1 otherwise. >>> search(list(range(0, 11)), 5) 5 >>> search([1, 2, 4, 5, 3], 4) 2 >>> search([1, 2, 4, 5, 3], 6) -1 >>> search([5], 5) 0 >>> search([], 1) -1 """ right = right or len(list_data) - 1 if left > right: return -1 elif list_data[left] == key: return left elif list_data[right] == key: return right else: return search(list_data, key, left + 1, right - 1) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 10: https://projecteuler.net/problem=10 Summation of primes The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. References: - https://en.wikipedia.org/wiki/Prime_number - https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes """ def solution(n: int = 2000000) -> int: """ Returns the sum of all the primes below n using Sieve of Eratosthenes: The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million. Only for positive numbers. >>> solution(1000) 76127 >>> solution(5000) 1548136 >>> solution(10000) 5736396 >>> solution(7) 10 >>> solution(7.1) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> solution(-7) # doctest: +ELLIPSIS Traceback (most recent call last): ... IndexError: list assignment index out of range >>> solution("seven") # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: can only concatenate str (not "int") to str """ primality_list = [0 for i in range(n + 1)] primality_list[0] = 1 primality_list[1] = 1 for i in range(2, int(n**0.5) + 1): if primality_list[i] == 0: for j in range(i * i, n + 1, i): primality_list[j] = 1 sum_of_primes = 0 for i in range(n): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 10: https://projecteuler.net/problem=10 Summation of primes The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. References: - https://en.wikipedia.org/wiki/Prime_number - https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes """ def solution(n: int = 2000000) -> int: """ Returns the sum of all the primes below n using Sieve of Eratosthenes: The sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than n when n is smaller than 10 million. Only for positive numbers. >>> solution(1000) 76127 >>> solution(5000) 1548136 >>> solution(10000) 5736396 >>> solution(7) 10 >>> solution(7.1) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> solution(-7) # doctest: +ELLIPSIS Traceback (most recent call last): ... IndexError: list assignment index out of range >>> solution("seven") # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: can only concatenate str (not "int") to str """ primality_list = [0 for i in range(n + 1)] primality_list[0] = 1 primality_list[1] = 1 for i in range(2, int(n**0.5) + 1): if primality_list[i] == 0: for j in range(i * i, n + 1, i): primality_list[j] = 1 sum_of_primes = 0 for i in range(n): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from PIL import Image def change_brightness(img: Image, level: float) -> Image: """ Change the brightness of a PIL Image to a given level. """ def brightness(c: int) -> float: """ Fundamental Transformation/Operation that'll be performed on every bit. """ return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("level must be between -255.0 (black) and 255.0 (white)") return img.point(brightness) if __name__ == "__main__": # Load image with Image.open("image_data/lena.jpg") as img: # Change brightness to 100 brigt_img = change_brightness(img, 100) brigt_img.save("image_data/lena_brightness.png", format="png")
from PIL import Image def change_brightness(img: Image, level: float) -> Image: """ Change the brightness of a PIL Image to a given level. """ def brightness(c: int) -> float: """ Fundamental Transformation/Operation that'll be performed on every bit. """ return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("level must be between -255.0 (black) and 255.0 (white)") return img.point(brightness) if __name__ == "__main__": # Load image with Image.open("image_data/lena.jpg") as img: # Change brightness to 100 brigt_img = change_brightness(img, 100) brigt_img.save("image_data/lena_brightness.png", format="png")
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Given a sorted array of integers, return indices of the two numbers such that they add up to a specific target using the two pointers technique. You may assume that each input would have exactly one solution, and you may not use the same element twice. This is an alternative solution of the two-sum problem, which uses a map to solve the problem. Hence can not solve the issue if there is a constraint not use the same index twice. [1] Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. [1]: https://github.com/TheAlgorithms/Python/blob/master/other/two_sum.py """ from __future__ import annotations def two_pointer(nums: list[int], target: int) -> list[int]: """ >>> two_pointer([2, 7, 11, 15], 9) [0, 1] >>> two_pointer([2, 7, 11, 15], 17) [0, 3] >>> two_pointer([2, 7, 11, 15], 18) [1, 2] >>> two_pointer([2, 7, 11, 15], 26) [2, 3] >>> two_pointer([1, 3, 3], 6) [1, 2] >>> two_pointer([2, 7, 11, 15], 8) [] >>> two_pointer([3 * i for i in range(10)], 19) [] >>> two_pointer([1, 2, 3], 6) [] """ i = 0 j = len(nums) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: i = i + 1 else: j = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"{two_pointer([2, 7, 11, 15], 9) = }")
""" Given a sorted array of integers, return indices of the two numbers such that they add up to a specific target using the two pointers technique. You may assume that each input would have exactly one solution, and you may not use the same element twice. This is an alternative solution of the two-sum problem, which uses a map to solve the problem. Hence can not solve the issue if there is a constraint not use the same index twice. [1] Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. [1]: https://github.com/TheAlgorithms/Python/blob/master/other/two_sum.py """ from __future__ import annotations def two_pointer(nums: list[int], target: int) -> list[int]: """ >>> two_pointer([2, 7, 11, 15], 9) [0, 1] >>> two_pointer([2, 7, 11, 15], 17) [0, 3] >>> two_pointer([2, 7, 11, 15], 18) [1, 2] >>> two_pointer([2, 7, 11, 15], 26) [2, 3] >>> two_pointer([1, 3, 3], 6) [1, 2] >>> two_pointer([2, 7, 11, 15], 8) [] >>> two_pointer([3 * i for i in range(10)], 19) [] >>> two_pointer([1, 2, 3], 6) [] """ i = 0 j = len(nums) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: i = i + 1 else: j = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f"{two_pointer([2, 7, 11, 15], 9) = }")
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge """ A pure Python implementation of the patience sort algorithm For more information: https://en.wikipedia.org/wiki/Patience_sorting This algorithm is based on the card game patience For doctests run following command: python3 -m doctest -v patience_sort.py For manual testing run: python3 patience_sort.py """ @total_ordering class Stack(list): def __lt__(self, other): return self[-1] < other[-1] def __eq__(self, other): return self[-1] == other[-1] def patience_sort(collection: list) -> list: """A pure implementation of patience sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> patience_sort([1, 9, 5, 21, 17, 6]) [1, 5, 6, 9, 17, 21] >>> patience_sort([]) [] >>> patience_sort([-3, -17, -48]) [-48, -17, -3] """ stacks: list[Stack] = [] # sort into stacks for element in collection: new_stacks = Stack([element]) i = bisect_left(stacks, new_stacks) if i != len(stacks): stacks[i].append(element) else: stacks.append(new_stacks) # use a heap-based merge to merge stack efficiently collection[:] = merge(*(reversed(stack) for stack in stacks)) return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(patience_sort(unsorted))
from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge """ A pure Python implementation of the patience sort algorithm For more information: https://en.wikipedia.org/wiki/Patience_sorting This algorithm is based on the card game patience For doctests run following command: python3 -m doctest -v patience_sort.py For manual testing run: python3 patience_sort.py """ @total_ordering class Stack(list): def __lt__(self, other): return self[-1] < other[-1] def __eq__(self, other): return self[-1] == other[-1] def patience_sort(collection: list) -> list: """A pure implementation of patience sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> patience_sort([1, 9, 5, 21, 17, 6]) [1, 5, 6, 9, 17, 21] >>> patience_sort([]) [] >>> patience_sort([-3, -17, -48]) [-48, -17, -3] """ stacks: list[Stack] = [] # sort into stacks for element in collection: new_stacks = Stack([element]) i = bisect_left(stacks, new_stacks) if i != len(stacks): stacks[i].append(element) else: stacks.append(new_stacks) # use a heap-based merge to merge stack efficiently collection[:] = merge(*(reversed(stack) for stack in stacks)) return collection if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(patience_sort(unsorted))
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations from cmath import sqrt def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]: """ Given the numerical coefficients a, b and c, calculates the roots for any quadratic equation of the form ax^2 + bx + c >>> quadratic_roots(a=1, b=3, c=-4) (1.0, -4.0) >>> quadratic_roots(5, 6, 1) (-0.2, -1.0) >>> quadratic_roots(1, -6, 25) ((3+4j), (3-4j)) """ if a == 0: raise ValueError("Coefficient 'a' must not be zero.") delta = b * b - 4 * a * c root_1 = (-b + sqrt(delta)) / (2 * a) root_2 = (-b - sqrt(delta)) / (2 * a) return ( root_1.real if not root_1.imag else root_1, root_2.real if not root_2.imag else root_2, ) def main(): solution1, solution2 = quadratic_roots(a=5, b=6, c=1) print(f"The solutions are: {solution1} and {solution2}") if __name__ == "__main__": main()
from __future__ import annotations from cmath import sqrt def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]: """ Given the numerical coefficients a, b and c, calculates the roots for any quadratic equation of the form ax^2 + bx + c >>> quadratic_roots(a=1, b=3, c=-4) (1.0, -4.0) >>> quadratic_roots(5, 6, 1) (-0.2, -1.0) >>> quadratic_roots(1, -6, 25) ((3+4j), (3-4j)) """ if a == 0: raise ValueError("Coefficient 'a' must not be zero.") delta = b * b - 4 * a * c root_1 = (-b + sqrt(delta)) / (2 * a) root_2 = (-b - sqrt(delta)) / (2 * a) return ( root_1.real if not root_1.imag else root_1, root_2.real if not root_2.imag else root_2, ) def main(): solution1, solution2 = quadratic_roots(a=5, b=6, c=1) print(f"The solutions are: {solution1} and {solution2}") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Sum of digits sequence Problem 551 Let a(0), a(1),... be an integer sequence defined by: a(0) = 1 for n >= 1, a(n) is the sum of the digits of all preceding terms The sequence starts with 1, 1, 2, 4, 8, ... You are given a(10^6) = 31054319. Find a(10^15) """ ks = range(2, 20 + 1) base = [10**k for k in range(ks[-1] + 1)] memo: dict[int, dict[int, list[list[int]]]] = {} def next_term(a_i, k, i, n): """ Calculates and updates a_i in-place to either the n-th term or the smallest term for which c > 10^k when the terms are written in the form: a(i) = b * 10^k + c For any a(i), if digitsum(b) and c have the same value, the difference between subsequent terms will be the same until c >= 10^k. This difference is cached to greatly speed up the computation. Arguments: a_i -- array of digits starting from the one's place that represent the i-th term in the sequence k -- k when terms are written in the from a(i) = b*10^k + c. Term are calulcated until c > 10^k or the n-th term is reached. i -- position along the sequence n -- term to calculate up to if k is large enough Return: a tuple of difference between ending term and starting term, and the number of terms calculated. ex. if starting term is a_0=1, and ending term is a_10=62, then (61, 9) is returned. """ # ds_b - digitsum(b) ds_b = sum(a_i[j] for j in range(k, len(a_i))) c = sum(a_i[j] * base[j] for j in range(min(len(a_i), k))) diff, dn = 0, 0 max_dn = n - i sub_memo = memo.get(ds_b) if sub_memo is not None: jumps = sub_memo.get(c) if jumps is not None and len(jumps) > 0: # find and make the largest jump without going over max_jump = -1 for _k in range(len(jumps) - 1, -1, -1): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: max_jump = _k break if max_jump >= 0: diff, dn, _kk = jumps[max_jump] # since the difference between jumps is cached, add c new_c = diff + c for j in range(min(k, len(a_i))): new_c, a_i[j] = divmod(new_c, 10) if new_c > 0: add(a_i, k, new_c) else: sub_memo[c] = [] else: sub_memo = {c: []} memo[ds_b] = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps _diff, terms_jumped = next_term(a_i, k - 1, i + dn, n) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead _diff, terms_jumped = compute(a_i, k, i + dn, n) diff += _diff dn += terms_jumped jumps = sub_memo[c] # keep jumps sorted by # of terms skipped j = 0 while j < len(jumps): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(j, (diff, dn, k)) return (diff, dn) def compute(a_i, k, i, n): """ same as next_term(a_i, k, i, n) but computes terms without memoizing results. """ if i >= n: return 0, i if k > len(a_i): a_i.extend([0 for _ in range(k - len(a_i))]) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) start_i = i ds_b, ds_c, diff = 0, 0, 0 for j in range(len(a_i)): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 addend = ds_c + ds_b diff += addend ds_c = 0 for j in range(k): s = a_i[j] + addend addend, a_i[j] = divmod(s, 10) ds_c += a_i[j] if addend > 0: break if addend > 0: add(a_i, k, addend) return diff, i - start_i def add(digits, k, addend): """ adds addend to digit array given in digits starting at index k """ for j in range(k, len(digits)): s = digits[j] + addend if s >= 10: quotient, digits[j] = divmod(s, 10) addend = addend // 10 + quotient else: digits[j] = s addend = addend // 10 if addend == 0: break while addend > 0: addend, digit = divmod(addend, 10) digits.append(digit) def solution(n: int = 10**15) -> int: """ returns n-th term of sequence >>> solution(10) 62 >>> solution(10**6) 31054319 >>> solution(10**15) 73597483551591773 """ digits = [1] i = 1 dn = 0 while True: diff, terms_jumped = next_term(digits, 20, i + dn, n) dn += terms_jumped if dn == n - i: break a_n = 0 for j in range(len(digits)): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(f"{solution() = }")
""" Sum of digits sequence Problem 551 Let a(0), a(1),... be an integer sequence defined by: a(0) = 1 for n >= 1, a(n) is the sum of the digits of all preceding terms The sequence starts with 1, 1, 2, 4, 8, ... You are given a(10^6) = 31054319. Find a(10^15) """ ks = range(2, 20 + 1) base = [10**k for k in range(ks[-1] + 1)] memo: dict[int, dict[int, list[list[int]]]] = {} def next_term(a_i, k, i, n): """ Calculates and updates a_i in-place to either the n-th term or the smallest term for which c > 10^k when the terms are written in the form: a(i) = b * 10^k + c For any a(i), if digitsum(b) and c have the same value, the difference between subsequent terms will be the same until c >= 10^k. This difference is cached to greatly speed up the computation. Arguments: a_i -- array of digits starting from the one's place that represent the i-th term in the sequence k -- k when terms are written in the from a(i) = b*10^k + c. Term are calulcated until c > 10^k or the n-th term is reached. i -- position along the sequence n -- term to calculate up to if k is large enough Return: a tuple of difference between ending term and starting term, and the number of terms calculated. ex. if starting term is a_0=1, and ending term is a_10=62, then (61, 9) is returned. """ # ds_b - digitsum(b) ds_b = sum(a_i[j] for j in range(k, len(a_i))) c = sum(a_i[j] * base[j] for j in range(min(len(a_i), k))) diff, dn = 0, 0 max_dn = n - i sub_memo = memo.get(ds_b) if sub_memo is not None: jumps = sub_memo.get(c) if jumps is not None and len(jumps) > 0: # find and make the largest jump without going over max_jump = -1 for _k in range(len(jumps) - 1, -1, -1): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: max_jump = _k break if max_jump >= 0: diff, dn, _kk = jumps[max_jump] # since the difference between jumps is cached, add c new_c = diff + c for j in range(min(k, len(a_i))): new_c, a_i[j] = divmod(new_c, 10) if new_c > 0: add(a_i, k, new_c) else: sub_memo[c] = [] else: sub_memo = {c: []} memo[ds_b] = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps _diff, terms_jumped = next_term(a_i, k - 1, i + dn, n) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead _diff, terms_jumped = compute(a_i, k, i + dn, n) diff += _diff dn += terms_jumped jumps = sub_memo[c] # keep jumps sorted by # of terms skipped j = 0 while j < len(jumps): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(j, (diff, dn, k)) return (diff, dn) def compute(a_i, k, i, n): """ same as next_term(a_i, k, i, n) but computes terms without memoizing results. """ if i >= n: return 0, i if k > len(a_i): a_i.extend([0 for _ in range(k - len(a_i))]) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) start_i = i ds_b, ds_c, diff = 0, 0, 0 for j in range(len(a_i)): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 addend = ds_c + ds_b diff += addend ds_c = 0 for j in range(k): s = a_i[j] + addend addend, a_i[j] = divmod(s, 10) ds_c += a_i[j] if addend > 0: break if addend > 0: add(a_i, k, addend) return diff, i - start_i def add(digits, k, addend): """ adds addend to digit array given in digits starting at index k """ for j in range(k, len(digits)): s = digits[j] + addend if s >= 10: quotient, digits[j] = divmod(s, 10) addend = addend // 10 + quotient else: digits[j] = s addend = addend // 10 if addend == 0: break while addend > 0: addend, digit = divmod(addend, 10) digits.append(digit) def solution(n: int = 10**15) -> int: """ returns n-th term of sequence >>> solution(10) 62 >>> solution(10**6) 31054319 >>> solution(10**15) 73597483551591773 """ digits = [1] i = 1 dn = 0 while True: diff, terms_jumped = next_term(digits, 20, i + dn, n) dn += terms_jumped if dn == n - i: break a_n = 0 for j in range(len(digits)): a_n += digits[j] * 10**j return a_n if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Uses Pythagoras theorem to calculate the distance between two points in space.""" import math class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self) -> str: return f"Point({self.x}, {self.y}, {self.z})" def distance(a: Point, b: Point) -> float: return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) def test_distance() -> None: """ >>> point1 = Point(2, -1, 7) >>> point2 = Point(1, -3, 5) >>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}") Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0 """ pass if __name__ == "__main__": import doctest doctest.testmod()
"""Uses Pythagoras theorem to calculate the distance between two points in space.""" import math class Point: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __repr__(self) -> str: return f"Point({self.x}, {self.y}, {self.z})" def distance(a: Point, b: Point) -> float: return math.sqrt(abs((b.x - a.x) ** 2 + (b.y - a.y) ** 2 + (b.z - a.z) ** 2)) def test_distance() -> None: """ >>> point1 = Point(2, -1, 7) >>> point2 = Point(1, -3, 5) >>> print(f"Distance from {point1} to {point2} is {distance(point1, point2)}") Distance from Point(2, -1, 7) to Point(1, -3, 5) is 3.0 """ pass if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def find_primitive(n: int) -> int | None: for r in range(1, n): li = [] for x in range(n - 1): val = pow(r, x, n) if val in li: break li.append(val) else: return r return None if __name__ == "__main__": q = int(input("Enter a prime number q: ")) a = find_primitive(q) if a is None: print(f"Cannot find the primitive for the value: {a!r}") else: a_private = int(input("Enter private key of A: ")) a_public = pow(a, a_private, q) b_private = int(input("Enter private key of B: ")) b_public = pow(a, b_private, q) a_secret = pow(b_public, a_private, q) b_secret = pow(a_public, b_private, q) print("The key value generated by A is: ", a_secret) print("The key value generated by B is: ", b_secret)
from __future__ import annotations def find_primitive(n: int) -> int | None: for r in range(1, n): li = [] for x in range(n - 1): val = pow(r, x, n) if val in li: break li.append(val) else: return r return None if __name__ == "__main__": q = int(input("Enter a prime number q: ")) a = find_primitive(q) if a is None: print(f"Cannot find the primitive for the value: {a!r}") else: a_private = int(input("Enter private key of A: ")) a_public = pow(a, a_private, q) b_private = int(input("Enter private key of B: ")) b_public = pow(a, b_private, q) a_secret = pow(b_public, a_private, q) b_secret = pow(a_public, b_private, q) print("The key value generated by A is: ", a_secret) print("The key value generated by B is: ", b_secret)
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" == Carmichael Numbers == A number n is said to be a Carmichael number if it satisfies the following modular arithmetic condition: power(b, n-1) MOD n = 1, for all b ranging from 1 to n such that b and n are relatively prime, i.e, gcd(b, n) = 1 Examples of Carmichael Numbers: 561, 1105, ... https://en.wikipedia.org/wiki/Carmichael_number """ def gcd(a: int, b: int) -> int: if a < b: return gcd(b, a) if a % b == 0: return b return gcd(b, a % b) def power(x: int, y: int, mod: int) -> int: if y == 0: return 1 temp = power(x, y // 2, mod) % mod temp = (temp * temp) % mod if y % 2 == 1: temp = (temp * x) % mod return temp def is_carmichael_number(n: int) -> bool: b = 2 while b < n: if gcd(b, n) == 1 and power(b, n - 1, n) != 1: return False b += 1 return True if __name__ == "__main__": number = int(input("Enter number: ").strip()) if is_carmichael_number(number): print(f"{number} is a Carmichael Number.") else: print(f"{number} is not a Carmichael Number.")
""" == Carmichael Numbers == A number n is said to be a Carmichael number if it satisfies the following modular arithmetic condition: power(b, n-1) MOD n = 1, for all b ranging from 1 to n such that b and n are relatively prime, i.e, gcd(b, n) = 1 Examples of Carmichael Numbers: 561, 1105, ... https://en.wikipedia.org/wiki/Carmichael_number """ def gcd(a: int, b: int) -> int: if a < b: return gcd(b, a) if a % b == 0: return b return gcd(b, a % b) def power(x: int, y: int, mod: int) -> int: if y == 0: return 1 temp = power(x, y // 2, mod) % mod temp = (temp * temp) % mod if y % 2 == 1: temp = (temp * x) % mod return temp def is_carmichael_number(n: int) -> bool: b = 2 while b < n: if gcd(b, n) == 1 and power(b, n - 1, n) != 1: return False b += 1 return True if __name__ == "__main__": number = int(input("Enter number: ").strip()) if is_carmichael_number(number): print(f"{number} is a Carmichael Number.") else: print(f"{number} is not a Carmichael Number.")
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def remove_duplicates(key: str) -> str: """ Removes duplicate alphabetic characters in a keyword (letter is ignored after its first appearance). :param key: Keyword to use :return: String with duplicates removed >>> remove_duplicates('Hello World!!') 'Helo Wrd' """ key_no_dups = "" for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def create_cipher_map(key: str) -> dict[str, str]: """ Returns a cipher map given a keyword. :param key: keyword to use :return: dictionary cipher map """ # Create a list of the letters in the alphabet alphabet = [chr(i + 65) for i in range(26)] # Remove duplicate characters from key key = remove_duplicates(key.upper()) offset = len(key) # First fill cipher with key characters cipher_alphabet = {alphabet[i]: char for i, char in enumerate(key)} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(cipher_alphabet), 26): char = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 char = alphabet[i - offset] cipher_alphabet[alphabet[i]] = char return cipher_alphabet def encipher(message: str, cipher_map: dict[str, str]) -> str: """ Enciphers a message given a cipher map. :param message: Message to encipher :param cipher_map: Cipher map :return: enciphered string >>> encipher('Hello World!!', create_cipher_map('Goodbye!!')) 'CYJJM VMQJB!!' """ return "".join(cipher_map.get(ch, ch) for ch in message.upper()) def decipher(message: str, cipher_map: dict[str, str]) -> str: """ Deciphers a message given a cipher map :param message: Message to decipher :param cipher_map: Dictionary mapping to use :return: Deciphered string >>> cipher_map = create_cipher_map('Goodbye!!') >>> decipher(encipher('Hello World!!', cipher_map), cipher_map) 'HELLO WORLD!!' """ # Reverse our cipher mappings rev_cipher_map = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(ch, ch) for ch in message.upper()) def main() -> None: """ Handles I/O :return: void """ message = input("Enter message to encode or decode: ").strip() key = input("Enter keyword: ").strip() option = input("Encipher or decipher? E/D:").strip()[0].lower() try: func = {"e": encipher, "d": decipher}[option] except KeyError: raise KeyError("invalid input option") cipher_map = create_cipher_map(key) print(func(message, cipher_map)) if __name__ == "__main__": import doctest doctest.testmod() main()
def remove_duplicates(key: str) -> str: """ Removes duplicate alphabetic characters in a keyword (letter is ignored after its first appearance). :param key: Keyword to use :return: String with duplicates removed >>> remove_duplicates('Hello World!!') 'Helo Wrd' """ key_no_dups = "" for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def create_cipher_map(key: str) -> dict[str, str]: """ Returns a cipher map given a keyword. :param key: keyword to use :return: dictionary cipher map """ # Create a list of the letters in the alphabet alphabet = [chr(i + 65) for i in range(26)] # Remove duplicate characters from key key = remove_duplicates(key.upper()) offset = len(key) # First fill cipher with key characters cipher_alphabet = {alphabet[i]: char for i, char in enumerate(key)} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(cipher_alphabet), 26): char = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 char = alphabet[i - offset] cipher_alphabet[alphabet[i]] = char return cipher_alphabet def encipher(message: str, cipher_map: dict[str, str]) -> str: """ Enciphers a message given a cipher map. :param message: Message to encipher :param cipher_map: Cipher map :return: enciphered string >>> encipher('Hello World!!', create_cipher_map('Goodbye!!')) 'CYJJM VMQJB!!' """ return "".join(cipher_map.get(ch, ch) for ch in message.upper()) def decipher(message: str, cipher_map: dict[str, str]) -> str: """ Deciphers a message given a cipher map :param message: Message to decipher :param cipher_map: Dictionary mapping to use :return: Deciphered string >>> cipher_map = create_cipher_map('Goodbye!!') >>> decipher(encipher('Hello World!!', cipher_map), cipher_map) 'HELLO WORLD!!' """ # Reverse our cipher mappings rev_cipher_map = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(ch, ch) for ch in message.upper()) def main() -> None: """ Handles I/O :return: void """ message = input("Enter message to encode or decode: ").strip() key = input("Enter keyword: ").strip() option = input("Encipher or decipher? E/D:").strip()[0].lower() try: func = {"e": encipher, "d": decipher}[option] except KeyError: raise KeyError("invalid input option") cipher_map = create_cipher_map(key) print(func(message, cipher_map)) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def min_path_sum(grid: list) -> int: """ Find the path from top left to bottom right of array of numbers with the lowest possible sum and return the sum along this path. >>> min_path_sum([ ... [1, 3, 1], ... [1, 5, 1], ... [4, 2, 1], ... ]) 7 >>> min_path_sum([ ... [1, 0, 5, 6, 7], ... [8, 9, 0, 4, 2], ... [4, 4, 4, 5, 1], ... [9, 6, 3, 1, 0], ... [8, 4, 3, 2, 7], ... ]) 20 >>> min_path_sum(None) Traceback (most recent call last): ... TypeError: The grid does not contain the appropriate information >>> min_path_sum([[]]) Traceback (most recent call last): ... TypeError: The grid does not contain the appropriate information """ if not grid or not grid[0]: raise TypeError("The grid does not contain the appropriate information") for cell_n in range(1, len(grid[0])): grid[0][cell_n] += grid[0][cell_n - 1] row_above = grid[0] for row_n in range(1, len(grid)): current_row = grid[row_n] grid[row_n] = fill_row(current_row, row_above) row_above = grid[row_n] return grid[-1][-1] def fill_row(current_row: list, row_above: list) -> list: """ >>> fill_row([2, 2, 2], [1, 2, 3]) [3, 4, 5] """ current_row[0] += row_above[0] for cell_n in range(1, len(current_row)): current_row[cell_n] += min(current_row[cell_n - 1], row_above[cell_n]) return current_row if __name__ == "__main__": import doctest doctest.testmod()
def min_path_sum(grid: list) -> int: """ Find the path from top left to bottom right of array of numbers with the lowest possible sum and return the sum along this path. >>> min_path_sum([ ... [1, 3, 1], ... [1, 5, 1], ... [4, 2, 1], ... ]) 7 >>> min_path_sum([ ... [1, 0, 5, 6, 7], ... [8, 9, 0, 4, 2], ... [4, 4, 4, 5, 1], ... [9, 6, 3, 1, 0], ... [8, 4, 3, 2, 7], ... ]) 20 >>> min_path_sum(None) Traceback (most recent call last): ... TypeError: The grid does not contain the appropriate information >>> min_path_sum([[]]) Traceback (most recent call last): ... TypeError: The grid does not contain the appropriate information """ if not grid or not grid[0]: raise TypeError("The grid does not contain the appropriate information") for cell_n in range(1, len(grid[0])): grid[0][cell_n] += grid[0][cell_n - 1] row_above = grid[0] for row_n in range(1, len(grid)): current_row = grid[row_n] grid[row_n] = fill_row(current_row, row_above) row_above = grid[row_n] return grid[-1][-1] def fill_row(current_row: list, row_above: list) -> list: """ >>> fill_row([2, 2, 2], [1, 2, 3]) [3, 4, 5] """ current_row[0] += row_above[0] for cell_n in range(1, len(current_row)): current_row[cell_n] += min(current_row[cell_n - 1], row_above[cell_n]) return current_row if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. """ def solution(limit=28123): """ Finds the sum of all the positive integers which cannot be written as the sum of two abundant numbers as described by the statement above. >>> solution() 4179871 """ sum_divs = [1] * (limit + 1) for i in range(2, int(limit**0.5) + 1): sum_divs[i * i] += i for k in range(i + 1, limit // i + 1): sum_divs[k * i] += k + i abundants = set() res = 0 for n in range(1, limit + 1): if sum_divs[n] > n: abundants.add(n) if not any((n - a in abundants) for a in abundants): res += n return res if __name__ == "__main__": print(solution())
""" A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. """ def solution(limit=28123): """ Finds the sum of all the positive integers which cannot be written as the sum of two abundant numbers as described by the statement above. >>> solution() 4179871 """ sum_divs = [1] * (limit + 1) for i in range(2, int(limit**0.5) + 1): sum_divs[i * i] += i for k in range(i + 1, limit // i + 1): sum_divs[k * i] += k + i abundants = set() res = 0 for n in range(1, limit + 1): if sum_divs[n] > n: abundants.add(n) if not any((n - a in abundants) for a in abundants): res += n return res if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter """ Create 2nd-order IIR filters with Butterworth design. Code based on https://webaudio.github.io/Audio-EQ-Cookbook/audio-eq-cookbook.html Alternatively you can use scipy.signal.butter, which should yield the same results. """ def make_lowpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 ) -> IIRFilter: """ Creates a low-pass filter >>> filter = make_lowpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.004277569313094809, 0.008555138626189618, 0.004277569313094809] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = (1 - _cos) / 2 b1 = 1 - _cos a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b0]) return filt def make_highpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 ) -> IIRFilter: """ Creates a high-pass filter >>> filter = make_highpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.9957224306869052, -1.9914448613738105, 0.9957224306869052] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = (1 + _cos) / 2 b1 = -1 - _cos a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b0]) return filt def make_bandpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 ) -> IIRFilter: """ Creates a band-pass filter >>> filter = make_bandpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.06526309611002579, 0, -0.06526309611002579] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = _sin / 2 b1 = 0 b2 = -b0 a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_allpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 ) -> IIRFilter: """ Creates an all-pass filter >>> filter = make_allpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.9077040443587427, -1.9828897227476208, 1.0922959556412573] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = 1 - alpha b1 = -2 * _cos b2 = 1 + alpha filt = IIRFilter(2) filt.set_coefficients([b2, b1, b0], [b0, b1, b2]) return filt def make_peak( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2), # noqa: B008 ) -> IIRFilter: """ Creates a peak filter >>> filter = make_peak(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0653405327119334, -1.9828897227476208, 0.9346594672880666, 1.1303715025601122, -1.9828897227476208, 0.8696284974398878] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) b0 = 1 + alpha * big_a b1 = -2 * _cos b2 = 1 - alpha * big_a a0 = 1 + alpha / big_a a1 = -2 * _cos a2 = 1 - alpha / big_a filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_lowshelf( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2), # noqa: B008 ) -> IIRFilter: """ Creates a low-shelf filter >>> filter = make_lowshelf(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [3.0409336710888786, -5.608870992220748, 2.602157875636628, 3.139954022810743, -5.591841778072785, 2.5201667380627257] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) pmc = (big_a + 1) - (big_a - 1) * _cos ppmc = (big_a + 1) + (big_a - 1) * _cos mpc = (big_a - 1) - (big_a + 1) * _cos pmpc = (big_a - 1) + (big_a + 1) * _cos aa2 = 2 * sqrt(big_a) * alpha b0 = big_a * (pmc + aa2) b1 = 2 * big_a * mpc b2 = big_a * (pmc - aa2) a0 = ppmc + aa2 a1 = -2 * pmpc a2 = ppmc - aa2 filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_highshelf( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2), # noqa: B008 ) -> IIRFilter: """ Creates a high-shelf filter >>> filter = make_highshelf(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [2.2229172136088806, -3.9587208137297303, 1.7841414181566304, 4.295432981120543, -7.922740859457287, 3.6756456963725253] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) pmc = (big_a + 1) - (big_a - 1) * _cos ppmc = (big_a + 1) + (big_a - 1) * _cos mpc = (big_a - 1) - (big_a + 1) * _cos pmpc = (big_a - 1) + (big_a + 1) * _cos aa2 = 2 * sqrt(big_a) * alpha b0 = big_a * (ppmc + aa2) b1 = -2 * big_a * pmpc b2 = big_a * (ppmc - aa2) a0 = pmc + aa2 a1 = 2 * mpc a2 = pmc - aa2 filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt
from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter """ Create 2nd-order IIR filters with Butterworth design. Code based on https://webaudio.github.io/Audio-EQ-Cookbook/audio-eq-cookbook.html Alternatively you can use scipy.signal.butter, which should yield the same results. """ def make_lowpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 ) -> IIRFilter: """ Creates a low-pass filter >>> filter = make_lowpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.004277569313094809, 0.008555138626189618, 0.004277569313094809] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = (1 - _cos) / 2 b1 = 1 - _cos a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b0]) return filt def make_highpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 ) -> IIRFilter: """ Creates a high-pass filter >>> filter = make_highpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.9957224306869052, -1.9914448613738105, 0.9957224306869052] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = (1 + _cos) / 2 b1 = -1 - _cos a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b0]) return filt def make_bandpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 ) -> IIRFilter: """ Creates a band-pass filter >>> filter = make_bandpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.06526309611002579, 0, -0.06526309611002579] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = _sin / 2 b1 = 0 b2 = -b0 a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_allpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) # noqa: B008 ) -> IIRFilter: """ Creates an all-pass filter >>> filter = make_allpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.9077040443587427, -1.9828897227476208, 1.0922959556412573] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = 1 - alpha b1 = -2 * _cos b2 = 1 + alpha filt = IIRFilter(2) filt.set_coefficients([b2, b1, b0], [b0, b1, b2]) return filt def make_peak( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2), # noqa: B008 ) -> IIRFilter: """ Creates a peak filter >>> filter = make_peak(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0653405327119334, -1.9828897227476208, 0.9346594672880666, 1.1303715025601122, -1.9828897227476208, 0.8696284974398878] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) b0 = 1 + alpha * big_a b1 = -2 * _cos b2 = 1 - alpha * big_a a0 = 1 + alpha / big_a a1 = -2 * _cos a2 = 1 - alpha / big_a filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_lowshelf( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2), # noqa: B008 ) -> IIRFilter: """ Creates a low-shelf filter >>> filter = make_lowshelf(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [3.0409336710888786, -5.608870992220748, 2.602157875636628, 3.139954022810743, -5.591841778072785, 2.5201667380627257] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) pmc = (big_a + 1) - (big_a - 1) * _cos ppmc = (big_a + 1) + (big_a - 1) * _cos mpc = (big_a - 1) - (big_a + 1) * _cos pmpc = (big_a - 1) + (big_a + 1) * _cos aa2 = 2 * sqrt(big_a) * alpha b0 = big_a * (pmc + aa2) b1 = 2 * big_a * mpc b2 = big_a * (pmc - aa2) a0 = ppmc + aa2 a1 = -2 * pmpc a2 = ppmc - aa2 filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_highshelf( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2), # noqa: B008 ) -> IIRFilter: """ Creates a high-shelf filter >>> filter = make_highshelf(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [2.2229172136088806, -3.9587208137297303, 1.7841414181566304, 4.295432981120543, -7.922740859457287, 3.6756456963725253] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) pmc = (big_a + 1) - (big_a - 1) * _cos ppmc = (big_a + 1) + (big_a - 1) * _cos mpc = (big_a - 1) - (big_a + 1) * _cos pmpc = (big_a - 1) + (big_a + 1) * _cos aa2 = 2 * sqrt(big_a) * alpha b0 = big_a * (ppmc + aa2) b1 = -2 * big_a * pmpc b2 = big_a * (ppmc - aa2) a0 = pmc + aa2 a1 = 2 * mpc a2 = pmc - aa2 filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Fast Polynomial Multiplication using radix-2 fast Fourier Transform. """ import mpmath # for roots of unity import numpy as np class FFT: """ Fast Polynomial Multiplication using radix-2 fast Fourier Transform. Reference: https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#The_radix-2_DIT_case For polynomials of degree m and n the algorithms has complexity O(n*logn + m*logm) The main part of the algorithm is split in two parts: 1) __DFT: We compute the discrete fourier transform (DFT) of A and B using a bottom-up dynamic approach - 2) __multiply: Once we obtain the DFT of A*B, we can similarly invert it to obtain A*B The class FFT takes two polynomials A and B with complex coefficients as arguments; The two polynomials should be represented as a sequence of coefficients starting from the free term. Thus, for instance x + 2*x^3 could be represented as [0,1,0,2] or (0,1,0,2). The constructor adds some zeros at the end so that the polynomials have the same length which is a power of 2 at least the length of their product. Example: Create two polynomials as sequences >>> A = [0, 1, 0, 2] # x+2x^3 >>> B = (2, 3, 4, 0) # 2+3x+4x^2 Create an FFT object with them >>> x = FFT(A, B) Print product >>> x.product # 2x + 3x^2 + 8x^3 + 4x^4 + 6x^5 [(-0+0j), (2+0j), (3+0j), (8+0j), (6+0j), (8+0j)] __str__ test >>> print(x) A = 0*x^0 + 1*x^1 + 2*x^0 + 3*x^2 B = 0*x^2 + 1*x^3 + 2*x^4 A*B = 0*x^(-0+0j) + 1*x^(2+0j) + 2*x^(3+0j) + 3*x^(8+0j) + 4*x^(6+0j) + 5*x^(8+0j) """ def __init__(self, poly_a=None, poly_b=None): # Input as list self.polyA = list(poly_a or [0])[:] self.polyB = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() self.len_A = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() self.len_B = len(self.polyB) # Add 0 to make lengths equal a power of 2 self.c_max_length = int( 2 ** np.ceil(np.log2(len(self.polyA) + len(self.polyB) - 1)) ) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform self.root = complex(mpmath.root(x=1, n=self.c_max_length, k=1)) # The product self.product = self.__multiply() # Discrete fourier transform of A and B def __dft(self, which): if which == "A": dft = [[x] for x in self.polyA] else: dft = [[x] for x in self.polyB] # Corner case if len(dft) <= 1: return dft[0] # next_ncol = self.c_max_length // 2 while next_ncol > 0: new_dft = [[] for i in range(next_ncol)] root = self.root**next_ncol # First half of next step current_root = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step current_root = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update dft = new_dft next_ncol = next_ncol // 2 return dft[0] # multiply the DFTs of A and B and find A*B def __multiply(self): dft_a = self.__dft("A") dft_b = self.__dft("B") inverce_c = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT next_ncol = 2 while next_ncol <= self.c_max_length: new_inverse_c = [[] for i in range(next_ncol)] root = self.root ** (next_ncol // 2) current_root = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2 ) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root # Update inverce_c = new_inverse_c next_ncol *= 2 # Unpack inverce_c = [round(x[0].real, 8) + round(x[0].imag, 8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c # Overwrite __str__ for print(); Shows A, B and A*B def __str__(self): a = "A = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyA[: self.len_A]) ) b = "B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyB[: self.len_B]) ) c = "A*B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.product) ) return "\n".join((a, b, c)) # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
""" Fast Polynomial Multiplication using radix-2 fast Fourier Transform. """ import mpmath # for roots of unity import numpy as np class FFT: """ Fast Polynomial Multiplication using radix-2 fast Fourier Transform. Reference: https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#The_radix-2_DIT_case For polynomials of degree m and n the algorithms has complexity O(n*logn + m*logm) The main part of the algorithm is split in two parts: 1) __DFT: We compute the discrete fourier transform (DFT) of A and B using a bottom-up dynamic approach - 2) __multiply: Once we obtain the DFT of A*B, we can similarly invert it to obtain A*B The class FFT takes two polynomials A and B with complex coefficients as arguments; The two polynomials should be represented as a sequence of coefficients starting from the free term. Thus, for instance x + 2*x^3 could be represented as [0,1,0,2] or (0,1,0,2). The constructor adds some zeros at the end so that the polynomials have the same length which is a power of 2 at least the length of their product. Example: Create two polynomials as sequences >>> A = [0, 1, 0, 2] # x+2x^3 >>> B = (2, 3, 4, 0) # 2+3x+4x^2 Create an FFT object with them >>> x = FFT(A, B) Print product >>> x.product # 2x + 3x^2 + 8x^3 + 4x^4 + 6x^5 [(-0+0j), (2+0j), (3+0j), (8+0j), (6+0j), (8+0j)] __str__ test >>> print(x) A = 0*x^0 + 1*x^1 + 2*x^0 + 3*x^2 B = 0*x^2 + 1*x^3 + 2*x^4 A*B = 0*x^(-0+0j) + 1*x^(2+0j) + 2*x^(3+0j) + 3*x^(8+0j) + 4*x^(6+0j) + 5*x^(8+0j) """ def __init__(self, poly_a=None, poly_b=None): # Input as list self.polyA = list(poly_a or [0])[:] self.polyB = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() self.len_A = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() self.len_B = len(self.polyB) # Add 0 to make lengths equal a power of 2 self.c_max_length = int( 2 ** np.ceil(np.log2(len(self.polyA) + len(self.polyB) - 1)) ) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform self.root = complex(mpmath.root(x=1, n=self.c_max_length, k=1)) # The product self.product = self.__multiply() # Discrete fourier transform of A and B def __dft(self, which): if which == "A": dft = [[x] for x in self.polyA] else: dft = [[x] for x in self.polyB] # Corner case if len(dft) <= 1: return dft[0] # next_ncol = self.c_max_length // 2 while next_ncol > 0: new_dft = [[] for i in range(next_ncol)] root = self.root**next_ncol # First half of next step current_root = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step current_root = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update dft = new_dft next_ncol = next_ncol // 2 return dft[0] # multiply the DFTs of A and B and find A*B def __multiply(self): dft_a = self.__dft("A") dft_b = self.__dft("B") inverce_c = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT next_ncol = 2 while next_ncol <= self.c_max_length: new_inverse_c = [[] for i in range(next_ncol)] root = self.root ** (next_ncol // 2) current_root = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2 ) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root # Update inverce_c = new_inverse_c next_ncol *= 2 # Unpack inverce_c = [round(x[0].real, 8) + round(x[0].imag, 8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c # Overwrite __str__ for print(); Shows A, B and A*B def __str__(self): a = "A = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyA[: self.len_A]) ) b = "B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyB[: self.len_B]) ) c = "A*B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.product) ) return "\n".join((a, b, c)) # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Binary Tree Traversal ## Overview The combination of binary trees being data structures and traversal being an algorithm relates to classic problems, either directly or indirectly. > If you can grasp the traversal of binary trees, the traversal of other complicated trees will be easy for you. The following are some common ways to traverse trees. - Depth First Traversals (DFS): In-order, Pre-order, Post-order - Level Order Traversal or Breadth First or Traversal (BFS) There are applications for both DFS and BFS. Stack can be used to simplify the process of DFS traversal. Besides, since tree is a recursive data structure, recursion and stack are two key points for DFS. Graph for DFS: ![binary-tree-traversal-dfs](https://tva1.sinaimg.cn/large/007S8ZIlly1ghluhzhynsg30dw0dw3yl.gif) The key point of BFS is how to determine whether the traversal of each level has been completed. The answer is to use a variable as a flag to represent the end of the traversal of current level. ## Pre-order Traversal The traversal order of pre-order traversal is `root-left-right`. Algorithm Pre-order 1. Visit the root node and push it into a stack. 2. Pop a node from the stack, and push its right and left child node into the stack respectively. 3. Repeat step 2. Conclusion: This problem involves the classic recursive data structure (i.e. a binary tree), and the algorithm above demonstrates how a simplified solution can be reached by using a stack. If you look at the bigger picture, you'll find that the process of traversal is as followed. `Visit the left subtrees respectively from top to bottom, and visit the right subtrees respectively from bottom to top`. If we are to implement it from this perspective, things will be somewhat different. For the `top to bottom` part we can simply use recursion, and for the `bottom to top` part we can turn to stack. ## In-order Traversal The traversal order of in-order traversal is `left-root-right`. So the root node is not printed first. Things are getting a bit complicated here. Algorithm In-order 1. Visit the root and push it into a stack. 2. If there is a left child node, push it into the stack. Repeat this process until a leaf node reached. > At this point the root node and all the left nodes are in the stack. 3. Start popping nodes from the stack. If a node has a right child node, push the child node into the stack. Repeat step 2. It's worth pointing out that the in-order traversal of a binary search tree (BST) is a sorted array, which is helpful for coming up simplified solutions for some problems. ## Post-order Traversal The traversal order of post-order traversal is `left-right-root`. This one is a bit of a challenge. It deserves the `hard` tag of LeetCode. In this case, the root node is printed not as the first but the last one. A cunning way to do it is to: Record whether the current node has been visited. If 1) it's a leaf node or 2) both its left and right subtrees have been traversed, then it can be popped from the stack. As for `1) it's a leaf node`, you can easily tell whether a node is a leaf if both its left and right are `null`. As for `2) both its left and right subtrees have been traversed`, we only need a variable to record whether a node has been visited or not. In the worst case, we need to record the status for every single node and the space complexity is `O(n)`. But if you come to think about it, as we are using a stack and start printing the result from the leaf nodes, it makes sense that we only record the status for the current node popping from the stack, reducing the space complexity to `O(1)`. ## Level Order Traversal The key point of level order traversal is how do we know whether the traversal of each level is done. The answer is that we use a variable as a flag representing the end of the traversal of the current level. ![binary-tree-traversal-bfs](https://tva1.sinaimg.cn/large/007S8ZIlly1ghlui1tpoug30dw0dw3yl.gif) Algorithm Level-order 1. Visit the root node, put it in a FIFO queue, put in the queue a special flag (we are using `null` here). 2. Dequeue a node. 3. If the node equals `null`, it means that all nodes of the current level have been visited. If the queue is empty, we do nothing. Or else we put in another `null`. 4. If the node is not `null`, meaning the traversal of current level has not finished yet, we enqueue its left subtree and right subtree respectively. ## Bi-color marking We know that there is a tri-color marking in garbage collection algorithm, which works as described below. - The white color represents "not visited". - The gray color represents "not all child nodes visited". - The black color represents "all child nodes visited". Enlightened by tri-color marking, a bi-color marking method can be invented to solve all three traversal problems with one solution. The core idea is as follow. - Use a color to mark whether a node has been visited or not. Nodes yet to be visited are marked as white and visited nodes are marked as gray. - If we are visiting a white node, turn it into gray, and push its right child node, itself, and it's left child node into the stack respectively. - If we are visiting a gray node, print it. Implementation of pre-order and post-order traversal algorithms can be easily done by changing the order of pushing the child nodes into the stack. Reference: [LeetCode](https://github.com/azl397985856/leetcode/blob/master/thinkings/binary-tree-traversal.en.md)
# Binary Tree Traversal ## Overview The combination of binary trees being data structures and traversal being an algorithm relates to classic problems, either directly or indirectly. > If you can grasp the traversal of binary trees, the traversal of other complicated trees will be easy for you. The following are some common ways to traverse trees. - Depth First Traversals (DFS): In-order, Pre-order, Post-order - Level Order Traversal or Breadth First or Traversal (BFS) There are applications for both DFS and BFS. Stack can be used to simplify the process of DFS traversal. Besides, since tree is a recursive data structure, recursion and stack are two key points for DFS. Graph for DFS: ![binary-tree-traversal-dfs](https://tva1.sinaimg.cn/large/007S8ZIlly1ghluhzhynsg30dw0dw3yl.gif) The key point of BFS is how to determine whether the traversal of each level has been completed. The answer is to use a variable as a flag to represent the end of the traversal of current level. ## Pre-order Traversal The traversal order of pre-order traversal is `root-left-right`. Algorithm Pre-order 1. Visit the root node and push it into a stack. 2. Pop a node from the stack, and push its right and left child node into the stack respectively. 3. Repeat step 2. Conclusion: This problem involves the classic recursive data structure (i.e. a binary tree), and the algorithm above demonstrates how a simplified solution can be reached by using a stack. If you look at the bigger picture, you'll find that the process of traversal is as followed. `Visit the left subtrees respectively from top to bottom, and visit the right subtrees respectively from bottom to top`. If we are to implement it from this perspective, things will be somewhat different. For the `top to bottom` part we can simply use recursion, and for the `bottom to top` part we can turn to stack. ## In-order Traversal The traversal order of in-order traversal is `left-root-right`. So the root node is not printed first. Things are getting a bit complicated here. Algorithm In-order 1. Visit the root and push it into a stack. 2. If there is a left child node, push it into the stack. Repeat this process until a leaf node reached. > At this point the root node and all the left nodes are in the stack. 3. Start popping nodes from the stack. If a node has a right child node, push the child node into the stack. Repeat step 2. It's worth pointing out that the in-order traversal of a binary search tree (BST) is a sorted array, which is helpful for coming up simplified solutions for some problems. ## Post-order Traversal The traversal order of post-order traversal is `left-right-root`. This one is a bit of a challenge. It deserves the `hard` tag of LeetCode. In this case, the root node is printed not as the first but the last one. A cunning way to do it is to: Record whether the current node has been visited. If 1) it's a leaf node or 2) both its left and right subtrees have been traversed, then it can be popped from the stack. As for `1) it's a leaf node`, you can easily tell whether a node is a leaf if both its left and right are `null`. As for `2) both its left and right subtrees have been traversed`, we only need a variable to record whether a node has been visited or not. In the worst case, we need to record the status for every single node and the space complexity is `O(n)`. But if you come to think about it, as we are using a stack and start printing the result from the leaf nodes, it makes sense that we only record the status for the current node popping from the stack, reducing the space complexity to `O(1)`. ## Level Order Traversal The key point of level order traversal is how do we know whether the traversal of each level is done. The answer is that we use a variable as a flag representing the end of the traversal of the current level. ![binary-tree-traversal-bfs](https://tva1.sinaimg.cn/large/007S8ZIlly1ghlui1tpoug30dw0dw3yl.gif) Algorithm Level-order 1. Visit the root node, put it in a FIFO queue, put in the queue a special flag (we are using `null` here). 2. Dequeue a node. 3. If the node equals `null`, it means that all nodes of the current level have been visited. If the queue is empty, we do nothing. Or else we put in another `null`. 4. If the node is not `null`, meaning the traversal of current level has not finished yet, we enqueue its left subtree and right subtree respectively. ## Bi-color marking We know that there is a tri-color marking in garbage collection algorithm, which works as described below. - The white color represents "not visited". - The gray color represents "not all child nodes visited". - The black color represents "all child nodes visited". Enlightened by tri-color marking, a bi-color marking method can be invented to solve all three traversal problems with one solution. The core idea is as follow. - Use a color to mark whether a node has been visited or not. Nodes yet to be visited are marked as white and visited nodes are marked as gray. - If we are visiting a white node, turn it into gray, and push its right child node, itself, and it's left child node into the stack respectively. - If we are visiting a gray node, print it. Implementation of pre-order and post-order traversal algorithms can be easily done by changing the order of pushing the child nodes into the stack. Reference: [LeetCode](https://github.com/azl397985856/leetcode/blob/master/thinkings/binary-tree-traversal.en.md)
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Knight Tour Intro: https://www.youtube.com/watch?v=ab_dY3dZFHM from __future__ import annotations def get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]: """ Find all the valid positions a knight can move to from the current position. >>> get_valid_pos((1, 3), 4) [(2, 1), (0, 1), (3, 2)] """ y, x = position positions = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] permissible_positions = [] for position in positions: y_test, x_test = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(position) return permissible_positions def is_complete(board: list[list[int]]) -> bool: """ Check if the board (matrix) has been completely filled with non-zero values. >>> is_complete([[1]]) True >>> is_complete([[1, 2], [3, 0]]) False """ return not any(elem == 0 for row in board for elem in row) def open_knight_tour_helper( board: list[list[int]], pos: tuple[int, int], curr: int ) -> bool: """ Helper function to solve knight tour problem. """ if is_complete(board): return True for position in get_valid_pos(pos, len(board)): y, x = position if board[y][x] == 0: board[y][x] = curr + 1 if open_knight_tour_helper(board, position, curr + 1): return True board[y][x] = 0 return False def open_knight_tour(n: int) -> list[list[int]]: """ Find the solution for the knight tour problem for a board of size n. Raises ValueError if the tour cannot be performed for the given size. >>> open_knight_tour(1) [[1]] >>> open_knight_tour(2) Traceback (most recent call last): ... ValueError: Open Kight Tour cannot be performed on a board of size 2 """ board = [[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): board[i][j] = 1 if open_knight_tour_helper(board, (i, j), 1): return board board[i][j] = 0 raise ValueError(f"Open Kight Tour cannot be performed on a board of size {n}") if __name__ == "__main__": import doctest doctest.testmod()
# Knight Tour Intro: https://www.youtube.com/watch?v=ab_dY3dZFHM from __future__ import annotations def get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]: """ Find all the valid positions a knight can move to from the current position. >>> get_valid_pos((1, 3), 4) [(2, 1), (0, 1), (3, 2)] """ y, x = position positions = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] permissible_positions = [] for position in positions: y_test, x_test = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(position) return permissible_positions def is_complete(board: list[list[int]]) -> bool: """ Check if the board (matrix) has been completely filled with non-zero values. >>> is_complete([[1]]) True >>> is_complete([[1, 2], [3, 0]]) False """ return not any(elem == 0 for row in board for elem in row) def open_knight_tour_helper( board: list[list[int]], pos: tuple[int, int], curr: int ) -> bool: """ Helper function to solve knight tour problem. """ if is_complete(board): return True for position in get_valid_pos(pos, len(board)): y, x = position if board[y][x] == 0: board[y][x] = curr + 1 if open_knight_tour_helper(board, position, curr + 1): return True board[y][x] = 0 return False def open_knight_tour(n: int) -> list[list[int]]: """ Find the solution for the knight tour problem for a board of size n. Raises ValueError if the tour cannot be performed for the given size. >>> open_knight_tour(1) [[1]] >>> open_knight_tour(2) Traceback (most recent call last): ... ValueError: Open Kight Tour cannot be performed on a board of size 2 """ board = [[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): board[i][j] = 1 if open_knight_tour_helper(board, (i, j), 1): return board board[i][j] = 0 raise ValueError(f"Open Kight Tour cannot be performed on a board of size {n}") if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/python """ A Framework of Back Propagation Neural Network(BP) model Easy to use: * add many layers as you want !!! * clearly see how the loss decreasing Easy to expand: * more activation functions * more loss functions * more optimization method Author: Stephen Lee Github : https://github.com/RiptideBo Date: 2017.11.23 """ import numpy as np from matplotlib import pyplot as plt def sigmoid(x): return 1 / (1 + np.exp(-1 * x)) class DenseLayer: """ Layers of BP neural network """ def __init__( self, units, activation=None, learning_rate=None, is_input_layer=False ): """ common connected layer of bp network :param units: numbers of neural units :param activation: activation function :param learning_rate: learning rate for paras :param is_input_layer: whether it is input layer or not """ self.units = units self.weight = None self.bias = None self.activation = activation if learning_rate is None: learning_rate = 0.3 self.learn_rate = learning_rate self.is_input_layer = is_input_layer def initializer(self, back_units): self.weight = np.asmatrix(np.random.normal(0, 0.5, (self.units, back_units))) self.bias = np.asmatrix(np.random.normal(0, 0.5, self.units)).T if self.activation is None: self.activation = sigmoid def cal_gradient(self): # activation function may be sigmoid or linear if self.activation == sigmoid: gradient_mat = np.dot(self.output, (1 - self.output).T) gradient_activation = np.diag(np.diag(gradient_mat)) else: gradient_activation = 1 return gradient_activation def forward_propagation(self, xdata): self.xdata = xdata if self.is_input_layer: # input layer self.wx_plus_b = xdata self.output = xdata return xdata else: self.wx_plus_b = np.dot(self.weight, self.xdata) - self.bias self.output = self.activation(self.wx_plus_b) return self.output def back_propagation(self, gradient): gradient_activation = self.cal_gradient() # i * i 维 gradient = np.asmatrix(np.dot(gradient.T, gradient_activation)) self._gradient_weight = np.asmatrix(self.xdata) self._gradient_bias = -1 self._gradient_x = self.weight self.gradient_weight = np.dot(gradient.T, self._gradient_weight.T) self.gradient_bias = gradient * self._gradient_bias self.gradient = np.dot(gradient, self._gradient_x).T # upgrade: the Negative gradient direction self.weight = self.weight - self.learn_rate * self.gradient_weight self.bias = self.bias - self.learn_rate * self.gradient_bias.T # updates the weights and bias according to learning rate (0.3 if undefined) return self.gradient class BPNN: """ Back Propagation Neural Network model """ def __init__(self): self.layers = [] self.train_mse = [] self.fig_loss = plt.figure() self.ax_loss = self.fig_loss.add_subplot(1, 1, 1) def add_layer(self, layer): self.layers.append(layer) def build(self): for i, layer in enumerate(self.layers[:]): if i < 1: layer.is_input_layer = True else: layer.initializer(self.layers[i - 1].units) def summary(self): for i, layer in enumerate(self.layers[:]): print(f"------- layer {i} -------") print("weight.shape ", np.shape(layer.weight)) print("bias.shape ", np.shape(layer.bias)) def train(self, xdata, ydata, train_round, accuracy): self.train_round = train_round self.accuracy = accuracy self.ax_loss.hlines(self.accuracy, 0, self.train_round * 1.1) x_shape = np.shape(xdata) for _ in range(train_round): all_loss = 0 for row in range(x_shape[0]): _xdata = np.asmatrix(xdata[row, :]).T _ydata = np.asmatrix(ydata[row, :]).T # forward propagation for layer in self.layers: _xdata = layer.forward_propagation(_xdata) loss, gradient = self.cal_loss(_ydata, _xdata) all_loss = all_loss + loss # back propagation: the input_layer does not upgrade for layer in self.layers[:0:-1]: gradient = layer.back_propagation(gradient) mse = all_loss / x_shape[0] self.train_mse.append(mse) self.plot_loss() if mse < self.accuracy: print("----达到精度----") return mse def cal_loss(self, ydata, ydata_): self.loss = np.sum(np.power((ydata - ydata_), 2)) self.loss_gradient = 2 * (ydata_ - ydata) # vector (shape is the same as _ydata.shape) return self.loss, self.loss_gradient def plot_loss(self): if self.ax_loss.lines: self.ax_loss.lines.remove(self.ax_loss.lines[0]) self.ax_loss.plot(self.train_mse, "r-") plt.ion() plt.xlabel("step") plt.ylabel("loss") plt.show() plt.pause(0.1) def example(): x = np.random.randn(10, 10) y = np.asarray( [ [0.8, 0.4], [0.4, 0.3], [0.34, 0.45], [0.67, 0.32], [0.88, 0.67], [0.78, 0.77], [0.55, 0.66], [0.55, 0.43], [0.54, 0.1], [0.1, 0.5], ] ) model = BPNN() for i in (10, 20, 30, 2): model.add_layer(DenseLayer(i)) model.build() model.summary() model.train(xdata=x, ydata=y, train_round=100, accuracy=0.01) if __name__ == "__main__": example()
#!/usr/bin/python """ A Framework of Back Propagation Neural Network(BP) model Easy to use: * add many layers as you want !!! * clearly see how the loss decreasing Easy to expand: * more activation functions * more loss functions * more optimization method Author: Stephen Lee Github : https://github.com/RiptideBo Date: 2017.11.23 """ import numpy as np from matplotlib import pyplot as plt def sigmoid(x): return 1 / (1 + np.exp(-1 * x)) class DenseLayer: """ Layers of BP neural network """ def __init__( self, units, activation=None, learning_rate=None, is_input_layer=False ): """ common connected layer of bp network :param units: numbers of neural units :param activation: activation function :param learning_rate: learning rate for paras :param is_input_layer: whether it is input layer or not """ self.units = units self.weight = None self.bias = None self.activation = activation if learning_rate is None: learning_rate = 0.3 self.learn_rate = learning_rate self.is_input_layer = is_input_layer def initializer(self, back_units): self.weight = np.asmatrix(np.random.normal(0, 0.5, (self.units, back_units))) self.bias = np.asmatrix(np.random.normal(0, 0.5, self.units)).T if self.activation is None: self.activation = sigmoid def cal_gradient(self): # activation function may be sigmoid or linear if self.activation == sigmoid: gradient_mat = np.dot(self.output, (1 - self.output).T) gradient_activation = np.diag(np.diag(gradient_mat)) else: gradient_activation = 1 return gradient_activation def forward_propagation(self, xdata): self.xdata = xdata if self.is_input_layer: # input layer self.wx_plus_b = xdata self.output = xdata return xdata else: self.wx_plus_b = np.dot(self.weight, self.xdata) - self.bias self.output = self.activation(self.wx_plus_b) return self.output def back_propagation(self, gradient): gradient_activation = self.cal_gradient() # i * i 维 gradient = np.asmatrix(np.dot(gradient.T, gradient_activation)) self._gradient_weight = np.asmatrix(self.xdata) self._gradient_bias = -1 self._gradient_x = self.weight self.gradient_weight = np.dot(gradient.T, self._gradient_weight.T) self.gradient_bias = gradient * self._gradient_bias self.gradient = np.dot(gradient, self._gradient_x).T # upgrade: the Negative gradient direction self.weight = self.weight - self.learn_rate * self.gradient_weight self.bias = self.bias - self.learn_rate * self.gradient_bias.T # updates the weights and bias according to learning rate (0.3 if undefined) return self.gradient class BPNN: """ Back Propagation Neural Network model """ def __init__(self): self.layers = [] self.train_mse = [] self.fig_loss = plt.figure() self.ax_loss = self.fig_loss.add_subplot(1, 1, 1) def add_layer(self, layer): self.layers.append(layer) def build(self): for i, layer in enumerate(self.layers[:]): if i < 1: layer.is_input_layer = True else: layer.initializer(self.layers[i - 1].units) def summary(self): for i, layer in enumerate(self.layers[:]): print(f"------- layer {i} -------") print("weight.shape ", np.shape(layer.weight)) print("bias.shape ", np.shape(layer.bias)) def train(self, xdata, ydata, train_round, accuracy): self.train_round = train_round self.accuracy = accuracy self.ax_loss.hlines(self.accuracy, 0, self.train_round * 1.1) x_shape = np.shape(xdata) for _ in range(train_round): all_loss = 0 for row in range(x_shape[0]): _xdata = np.asmatrix(xdata[row, :]).T _ydata = np.asmatrix(ydata[row, :]).T # forward propagation for layer in self.layers: _xdata = layer.forward_propagation(_xdata) loss, gradient = self.cal_loss(_ydata, _xdata) all_loss = all_loss + loss # back propagation: the input_layer does not upgrade for layer in self.layers[:0:-1]: gradient = layer.back_propagation(gradient) mse = all_loss / x_shape[0] self.train_mse.append(mse) self.plot_loss() if mse < self.accuracy: print("----达到精度----") return mse def cal_loss(self, ydata, ydata_): self.loss = np.sum(np.power((ydata - ydata_), 2)) self.loss_gradient = 2 * (ydata_ - ydata) # vector (shape is the same as _ydata.shape) return self.loss, self.loss_gradient def plot_loss(self): if self.ax_loss.lines: self.ax_loss.lines.remove(self.ax_loss.lines[0]) self.ax_loss.plot(self.train_mse, "r-") plt.ion() plt.xlabel("step") plt.ylabel("loss") plt.show() plt.pause(0.1) def example(): x = np.random.randn(10, 10) y = np.asarray( [ [0.8, 0.4], [0.4, 0.3], [0.34, 0.45], [0.67, 0.32], [0.88, 0.67], [0.78, 0.77], [0.55, 0.66], [0.55, 0.43], [0.54, 0.1], [0.1, 0.5], ] ) model = BPNN() for i in (10, 20, 30, 2): model.add_layer(DenseLayer(i)) model.build() model.summary() model.train(xdata=x, ydata=y, train_round=100, accuracy=0.01) if __name__ == "__main__": example()
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 >>> solution(-7) 0 """ return sum(e for e in range(3, n) if e % 3 == 0 or e % 5 == 0) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 >>> solution(-7) 0 """ return sum(e for e in range(3, n) if e % 3 == 0 or e % 5 == 0) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def kth_permutation(k, n): """ Finds k'th lexicographic permutation (in increasing order) of 0,1,2,...n-1 in O(n^2) time. Examples: First permutation is always 0,1,2,...n >>> kth_permutation(0,5) [0, 1, 2, 3, 4] The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3], [0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3], [1,2,3,0], [1,3,0,2] >>> kth_permutation(10,4) [1, 3, 0, 2] """ # Factorails from 1! to (n-1)! factorials = [1] for i in range(2, n): factorials.append(factorials[-1] * i) assert 0 <= k < factorials[-1] * n, "k out of bounds" permutation = [] elements = list(range(n)) # Find permutation while factorials: factorial = factorials.pop() number, k = divmod(k, factorial) permutation.append(elements[number]) elements.remove(elements[number]) permutation.append(elements[0]) return permutation if __name__ == "__main__": import doctest doctest.testmod()
def kth_permutation(k, n): """ Finds k'th lexicographic permutation (in increasing order) of 0,1,2,...n-1 in O(n^2) time. Examples: First permutation is always 0,1,2,...n >>> kth_permutation(0,5) [0, 1, 2, 3, 4] The order of permutation of 0,1,2,3 is [0,1,2,3], [0,1,3,2], [0,2,1,3], [0,2,3,1], [0,3,1,2], [0,3,2,1], [1,0,2,3], [1,0,3,2], [1,2,0,3], [1,2,3,0], [1,3,0,2] >>> kth_permutation(10,4) [1, 3, 0, 2] """ # Factorails from 1! to (n-1)! factorials = [1] for i in range(2, n): factorials.append(factorials[-1] * i) assert 0 <= k < factorials[-1] * n, "k out of bounds" permutation = [] elements = list(range(n)) # Find permutation while factorials: factorial = factorials.pop() number, k = divmod(k, factorial) permutation.append(elements[number]) elements.remove(elements[number]) permutation.append(elements[0]) return permutation if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
INF = float("inf") class Dinic: def __init__(self, n): self.lvl = [0] * n self.ptr = [0] * n self.q = [0] * n self.adj = [[] for _ in range(n)] """ Here we will add our edges containing with the following parameters: vertex closest to source, vertex closest to sink and flow capacity through that edge ... """ def add_edge(self, a, b, c, rcap=0): self.adj[a].append([b, len(self.adj[b]), c, 0]) self.adj[b].append([a, len(self.adj[a]) - 1, rcap, 0]) # This is a sample depth first search to be used at max_flow def depth_first_search(self, vertex, sink, flow): if vertex == sink or not flow: return flow for i in range(self.ptr[vertex], len(self.adj[vertex])): e = self.adj[vertex][i] if self.lvl[e[0]] == self.lvl[vertex] + 1: p = self.depth_first_search(e[0], sink, min(flow, e[2] - e[3])) if p: self.adj[vertex][i][3] += p self.adj[e[0]][e[1]][3] -= p return p self.ptr[vertex] = self.ptr[vertex] + 1 return 0 # Here we calculate the flow that reaches the sink def max_flow(self, source, sink): flow, self.q[0] = 0, source for l in range(31): # noqa: E741 l = 30 maybe faster for random data while True: self.lvl, self.ptr = [0] * len(self.q), [0] * len(self.q) qi, qe, self.lvl[source] = 0, 1, 1 while qi < qe and not self.lvl[sink]: v = self.q[qi] qi += 1 for e in self.adj[v]: if not self.lvl[e[0]] and (e[2] - e[3]) >> (30 - l): self.q[qe] = e[0] qe += 1 self.lvl[e[0]] = self.lvl[v] + 1 p = self.depth_first_search(source, sink, INF) while p: flow += p p = self.depth_first_search(source, sink, INF) if not self.lvl[sink]: break return flow # Example to use """ Will be a bipartite graph, than it has the vertices near the source(4) and the vertices near the sink(4) """ # Here we make a graphs with 10 vertex(source and sink includes) graph = Dinic(10) source = 0 sink = 9 """ Now we add the vertices next to the font in the font with 1 capacity in this edge (source -> source vertices) """ for vertex in range(1, 5): graph.add_edge(source, vertex, 1) """ We will do the same thing for the vertices near the sink, but from vertex to sink (sink vertices -> sink) """ for vertex in range(5, 9): graph.add_edge(vertex, sink, 1) """ Finally we add the verices near the sink to the vertices near the source. (source vertices -> sink vertices) """ for vertex in range(1, 5): graph.add_edge(vertex, vertex + 4, 1) # Now we can know that is the maximum flow(source -> sink) print(graph.max_flow(source, sink))
INF = float("inf") class Dinic: def __init__(self, n): self.lvl = [0] * n self.ptr = [0] * n self.q = [0] * n self.adj = [[] for _ in range(n)] """ Here we will add our edges containing with the following parameters: vertex closest to source, vertex closest to sink and flow capacity through that edge ... """ def add_edge(self, a, b, c, rcap=0): self.adj[a].append([b, len(self.adj[b]), c, 0]) self.adj[b].append([a, len(self.adj[a]) - 1, rcap, 0]) # This is a sample depth first search to be used at max_flow def depth_first_search(self, vertex, sink, flow): if vertex == sink or not flow: return flow for i in range(self.ptr[vertex], len(self.adj[vertex])): e = self.adj[vertex][i] if self.lvl[e[0]] == self.lvl[vertex] + 1: p = self.depth_first_search(e[0], sink, min(flow, e[2] - e[3])) if p: self.adj[vertex][i][3] += p self.adj[e[0]][e[1]][3] -= p return p self.ptr[vertex] = self.ptr[vertex] + 1 return 0 # Here we calculate the flow that reaches the sink def max_flow(self, source, sink): flow, self.q[0] = 0, source for l in range(31): # noqa: E741 l = 30 maybe faster for random data while True: self.lvl, self.ptr = [0] * len(self.q), [0] * len(self.q) qi, qe, self.lvl[source] = 0, 1, 1 while qi < qe and not self.lvl[sink]: v = self.q[qi] qi += 1 for e in self.adj[v]: if not self.lvl[e[0]] and (e[2] - e[3]) >> (30 - l): self.q[qe] = e[0] qe += 1 self.lvl[e[0]] = self.lvl[v] + 1 p = self.depth_first_search(source, sink, INF) while p: flow += p p = self.depth_first_search(source, sink, INF) if not self.lvl[sink]: break return flow # Example to use """ Will be a bipartite graph, than it has the vertices near the source(4) and the vertices near the sink(4) """ # Here we make a graphs with 10 vertex(source and sink includes) graph = Dinic(10) source = 0 sink = 9 """ Now we add the vertices next to the font in the font with 1 capacity in this edge (source -> source vertices) """ for vertex in range(1, 5): graph.add_edge(source, vertex, 1) """ We will do the same thing for the vertices near the sink, but from vertex to sink (sink vertices -> sink) """ for vertex in range(5, 9): graph.add_edge(vertex, sink, 1) """ Finally we add the verices near the sink to the vertices near the source. (source vertices -> sink vertices) """ for vertex in range(1, 5): graph.add_edge(vertex, vertex + 4, 1) # Now we can know that is the maximum flow(source -> sink) print(graph.max_flow(source, sink))
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,988
fix: mypy 0.991 issues
fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T16:54:56Z"
"2022-11-15T17:29:14Z"
4ce8ad9ce6e554360089e77e088df6dd8b4a69df
8bfd1c844b388cb78b03952c7da28f07f3838fd1
fix: mypy 0.991 issues. fixes: #7987 Note that `matrix/matrix_class.py` had CRLF line endings, that was converted to LF line endings and that's the major diff you're seeing. The actual diff is: ```diff diff --git a/matrix/matrix_class.py b/matrix/matrix_class.py index a73e8b92..2b4edc3c 100644 --- a/matrix/matrix_class.py +++ b/matrix/matrix_class.py @@ -345,7 +345,7 @@ class Matrix: if other == 0: return self.identity() if other < 0: - if self.is_invertable: + if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( "Only invertable matrices can be raised to a negative power" ``` ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def modular_division(a: int, b: int, n: int) -> int: """ Modular Division : An efficient algorithm for dividing b by a modulo n. GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) Given three integers a, b, and n, such that gcd(a,n)=1 and n>1, the algorithm should return an integer x such that 0≤x≤n−1, and b/a=x(modn) (that is, b=ax(modn)). Theorem: a has a multiplicative inverse modulo n iff gcd(a,n) = 1 This find x = b*a^(-1) mod n Uses ExtendedEuclid to find the inverse of a >>> modular_division(4,8,5) 2 >>> modular_division(3,8,5) 1 >>> modular_division(4, 11, 5) 4 """ assert n > 1 and a > 0 and greatest_common_divisor(a, n) == 1 (d, t, s) = extended_gcd(n, a) # Implemented below x = (b * s) % n return x def invert_modulo(a: int, n: int) -> int: """ This function find the inverses of a i.e., a^(-1) >>> invert_modulo(2, 5) 3 >>> invert_modulo(8,7) 1 """ (b, x) = extended_euclid(a, n) # Implemented below if b < 0: b = (b % n + n) % n return b # ------------------ Finding Modular division using invert_modulo ------------------- def modular_division2(a: int, b: int, n: int) -> int: """ This function used the above inversion of a to find x = (b*a^(-1))mod n >>> modular_division2(4,8,5) 2 >>> modular_division2(3,8,5) 1 >>> modular_division2(4, 11, 5) 4 """ s = invert_modulo(a, n) x = (b * s) % n return x def extended_gcd(a: int, b: int) -> tuple[int, int, int]: """ Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x and y, then d = gcd(a,b) >>> extended_gcd(10, 6) (2, -1, 2) >>> extended_gcd(7, 5) (1, -2, 3) ** extended_gcd function is used when d = gcd(a,b) is required in output """ assert a >= 0 and b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 and b % d == 0 assert d == a * x + b * y return (d, x, y) def extended_euclid(a: int, b: int) -> tuple[int, int]: """ Extended Euclid >>> extended_euclid(10, 6) (-1, 2) >>> extended_euclid(7, 5) (-2, 3) """ if b == 0: return (1, 0) (x, y) = extended_euclid(b, a % b) k = a // b return (y, x - k * y) def greatest_common_divisor(a: int, b: int) -> int: """ Euclid's Lemma : d divides a and b, if and only if d divides a-b and b Euclid's Algorithm >>> greatest_common_divisor(7,5) 1 Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co-prime if the only positive integer (factor) that divides both of them is 1 i.e., gcd(a,b) = 1. >>> greatest_common_divisor(121, 11) 11 """ if a < b: a, b = b, a while a % b != 0: a, b = b, a % b return b if __name__ == "__main__": from doctest import testmod testmod(name="modular_division", verbose=True) testmod(name="modular_division2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="extended_euclid", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
from __future__ import annotations def modular_division(a: int, b: int, n: int) -> int: """ Modular Division : An efficient algorithm for dividing b by a modulo n. GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) Given three integers a, b, and n, such that gcd(a,n)=1 and n>1, the algorithm should return an integer x such that 0≤x≤n−1, and b/a=x(modn) (that is, b=ax(modn)). Theorem: a has a multiplicative inverse modulo n iff gcd(a,n) = 1 This find x = b*a^(-1) mod n Uses ExtendedEuclid to find the inverse of a >>> modular_division(4,8,5) 2 >>> modular_division(3,8,5) 1 >>> modular_division(4, 11, 5) 4 """ assert n > 1 and a > 0 and greatest_common_divisor(a, n) == 1 (d, t, s) = extended_gcd(n, a) # Implemented below x = (b * s) % n return x def invert_modulo(a: int, n: int) -> int: """ This function find the inverses of a i.e., a^(-1) >>> invert_modulo(2, 5) 3 >>> invert_modulo(8,7) 1 """ (b, x) = extended_euclid(a, n) # Implemented below if b < 0: b = (b % n + n) % n return b # ------------------ Finding Modular division using invert_modulo ------------------- def modular_division2(a: int, b: int, n: int) -> int: """ This function used the above inversion of a to find x = (b*a^(-1))mod n >>> modular_division2(4,8,5) 2 >>> modular_division2(3,8,5) 1 >>> modular_division2(4, 11, 5) 4 """ s = invert_modulo(a, n) x = (b * s) % n return x def extended_gcd(a: int, b: int) -> tuple[int, int, int]: """ Extended Euclid's Algorithm : If d divides a and b and d = a*x + b*y for integers x and y, then d = gcd(a,b) >>> extended_gcd(10, 6) (2, -1, 2) >>> extended_gcd(7, 5) (1, -2, 3) ** extended_gcd function is used when d = gcd(a,b) is required in output """ assert a >= 0 and b >= 0 if b == 0: d, x, y = a, 1, 0 else: (d, p, q) = extended_gcd(b, a % b) x = q y = p - q * (a // b) assert a % d == 0 and b % d == 0 assert d == a * x + b * y return (d, x, y) def extended_euclid(a: int, b: int) -> tuple[int, int]: """ Extended Euclid >>> extended_euclid(10, 6) (-1, 2) >>> extended_euclid(7, 5) (-2, 3) """ if b == 0: return (1, 0) (x, y) = extended_euclid(b, a % b) k = a // b return (y, x - k * y) def greatest_common_divisor(a: int, b: int) -> int: """ Euclid's Lemma : d divides a and b, if and only if d divides a-b and b Euclid's Algorithm >>> greatest_common_divisor(7,5) 1 Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co-prime if the only positive integer (factor) that divides both of them is 1 i.e., gcd(a,b) = 1. >>> greatest_common_divisor(121, 11) 11 """ if a < b: a, b = b, a while a % b != 0: a, b = b, a % b return b if __name__ == "__main__": from doctest import testmod testmod(name="modular_division", verbose=True) testmod(name="modular_division2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_gcd", verbose=True) testmod(name="extended_euclid", verbose=True) testmod(name="greatest_common_divisor", verbose=True)
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from copy import deepcopy class FenwickTree: """ Fenwick Tree More info: https://en.wikipedia.org/wiki/Fenwick_tree """ def __init__(self, arr: list[int] = None, size: int = None) -> None: """ Constructor for the Fenwick tree Parameters: arr (list): list of elements to initialize the tree with (optional) size (int): size of the Fenwick tree (if arr is None) """ if arr is None and size is not None: self.size = size self.tree = [0] * size elif arr is not None: self.init(arr) else: raise ValueError("Either arr or size must be specified") def init(self, arr: list[int]) -> None: """ Initialize the Fenwick tree with arr in O(N) Parameters: arr (list): list of elements to initialize the tree with Returns: None >>> a = [1, 2, 3, 4, 5] >>> f1 = FenwickTree(a) >>> f2 = FenwickTree(size=len(a)) >>> for index, value in enumerate(a): ... f2.add(index, value) >>> f1.tree == f2.tree True """ self.size = len(arr) self.tree = deepcopy(arr) for i in range(1, self.size): j = self.next_(i) if j < self.size: self.tree[j] += self.tree[i] def get_array(self) -> list[int]: """ Get the Normal Array of the Fenwick tree in O(N) Returns: list: Normal Array of the Fenwick tree >>> a = [i for i in range(128)] >>> f = FenwickTree(a) >>> f.get_array() == a True """ arr = self.tree[:] for i in range(self.size - 1, 0, -1): j = self.next_(i) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def next_(index: int) -> int: return index + (index & (-index)) @staticmethod def prev(index: int) -> int: return index - (index & (-index)) def add(self, index: int, value: int) -> None: """ Add a value to index in O(lg N) Parameters: index (int): index to add value to value (int): value to add to index Returns: None >>> f = FenwickTree([1, 2, 3, 4, 5]) >>> f.add(0, 1) >>> f.add(1, 2) >>> f.add(2, 3) >>> f.add(3, 4) >>> f.add(4, 5) >>> f.get_array() [2, 4, 6, 8, 10] """ if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value index = self.next_(index) def update(self, index: int, value: int) -> None: """ Set the value of index in O(lg N) Parameters: index (int): index to set value to value (int): value to set in index Returns: None >>> f = FenwickTree([5, 4, 3, 2, 1]) >>> f.update(0, 1) >>> f.update(1, 2) >>> f.update(2, 3) >>> f.update(3, 4) >>> f.update(4, 5) >>> f.get_array() [1, 2, 3, 4, 5] """ self.add(index, value - self.get(index)) def prefix(self, right: int) -> int: """ Prefix sum of all elements in [0, right) in O(lg N) Parameters: right (int): right bound of the query (exclusive) Returns: int: sum of all elements in [0, right) >>> a = [i for i in range(128)] >>> f = FenwickTree(a) >>> res = True >>> for i in range(len(a)): ... res = res and f.prefix(i) == sum(a[:i]) >>> res True """ if right == 0: return 0 result = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] right = self.prev(right) return result def query(self, left: int, right: int) -> int: """ Query the sum of all elements in [left, right) in O(lg N) Parameters: left (int): left bound of the query (inclusive) right (int): right bound of the query (exclusive) Returns: int: sum of all elements in [left, right) >>> a = [i for i in range(128)] >>> f = FenwickTree(a) >>> res = True >>> for i in range(len(a)): ... for j in range(i + 1, len(a)): ... res = res and f.query(i, j) == sum(a[i:j]) >>> res True """ return self.prefix(right) - self.prefix(left) def get(self, index: int) -> int: """ Get value at index in O(lg N) Parameters: index (int): index to get the value Returns: int: Value of element at index >>> a = [i for i in range(128)] >>> f = FenwickTree(a) >>> res = True >>> for i in range(len(a)): ... res = res and f.get(i) == a[i] >>> res True """ return self.query(index, index + 1) def rank_query(self, value: int) -> int: """ Find the largest index with prefix(i) <= value in O(lg N) NOTE: Requires that all values are non-negative! Parameters: value (int): value to find the largest index of Returns: -1: if value is smaller than all elements in prefix sum int: largest index with prefix(i) <= value >>> f = FenwickTree([1, 2, 0, 3, 0, 5]) >>> f.rank_query(0) -1 >>> f.rank_query(2) 0 >>> f.rank_query(1) 0 >>> f.rank_query(3) 2 >>> f.rank_query(5) 2 >>> f.rank_query(6) 4 >>> f.rank_query(11) 5 """ value -= self.tree[0] if value < 0: return -1 j = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 i = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
from copy import deepcopy class FenwickTree: """ Fenwick Tree More info: https://en.wikipedia.org/wiki/Fenwick_tree """ def __init__(self, arr: list[int] | None = None, size: int | None = None) -> None: """ Constructor for the Fenwick tree Parameters: arr (list): list of elements to initialize the tree with (optional) size (int): size of the Fenwick tree (if arr is None) """ if arr is None and size is not None: self.size = size self.tree = [0] * size elif arr is not None: self.init(arr) else: raise ValueError("Either arr or size must be specified") def init(self, arr: list[int]) -> None: """ Initialize the Fenwick tree with arr in O(N) Parameters: arr (list): list of elements to initialize the tree with Returns: None >>> a = [1, 2, 3, 4, 5] >>> f1 = FenwickTree(a) >>> f2 = FenwickTree(size=len(a)) >>> for index, value in enumerate(a): ... f2.add(index, value) >>> f1.tree == f2.tree True """ self.size = len(arr) self.tree = deepcopy(arr) for i in range(1, self.size): j = self.next_(i) if j < self.size: self.tree[j] += self.tree[i] def get_array(self) -> list[int]: """ Get the Normal Array of the Fenwick tree in O(N) Returns: list: Normal Array of the Fenwick tree >>> a = [i for i in range(128)] >>> f = FenwickTree(a) >>> f.get_array() == a True """ arr = self.tree[:] for i in range(self.size - 1, 0, -1): j = self.next_(i) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def next_(index: int) -> int: return index + (index & (-index)) @staticmethod def prev(index: int) -> int: return index - (index & (-index)) def add(self, index: int, value: int) -> None: """ Add a value to index in O(lg N) Parameters: index (int): index to add value to value (int): value to add to index Returns: None >>> f = FenwickTree([1, 2, 3, 4, 5]) >>> f.add(0, 1) >>> f.add(1, 2) >>> f.add(2, 3) >>> f.add(3, 4) >>> f.add(4, 5) >>> f.get_array() [2, 4, 6, 8, 10] """ if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value index = self.next_(index) def update(self, index: int, value: int) -> None: """ Set the value of index in O(lg N) Parameters: index (int): index to set value to value (int): value to set in index Returns: None >>> f = FenwickTree([5, 4, 3, 2, 1]) >>> f.update(0, 1) >>> f.update(1, 2) >>> f.update(2, 3) >>> f.update(3, 4) >>> f.update(4, 5) >>> f.get_array() [1, 2, 3, 4, 5] """ self.add(index, value - self.get(index)) def prefix(self, right: int) -> int: """ Prefix sum of all elements in [0, right) in O(lg N) Parameters: right (int): right bound of the query (exclusive) Returns: int: sum of all elements in [0, right) >>> a = [i for i in range(128)] >>> f = FenwickTree(a) >>> res = True >>> for i in range(len(a)): ... res = res and f.prefix(i) == sum(a[:i]) >>> res True """ if right == 0: return 0 result = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] right = self.prev(right) return result def query(self, left: int, right: int) -> int: """ Query the sum of all elements in [left, right) in O(lg N) Parameters: left (int): left bound of the query (inclusive) right (int): right bound of the query (exclusive) Returns: int: sum of all elements in [left, right) >>> a = [i for i in range(128)] >>> f = FenwickTree(a) >>> res = True >>> for i in range(len(a)): ... for j in range(i + 1, len(a)): ... res = res and f.query(i, j) == sum(a[i:j]) >>> res True """ return self.prefix(right) - self.prefix(left) def get(self, index: int) -> int: """ Get value at index in O(lg N) Parameters: index (int): index to get the value Returns: int: Value of element at index >>> a = [i for i in range(128)] >>> f = FenwickTree(a) >>> res = True >>> for i in range(len(a)): ... res = res and f.get(i) == a[i] >>> res True """ return self.query(index, index + 1) def rank_query(self, value: int) -> int: """ Find the largest index with prefix(i) <= value in O(lg N) NOTE: Requires that all values are non-negative! Parameters: value (int): value to find the largest index of Returns: -1: if value is smaller than all elements in prefix sum int: largest index with prefix(i) <= value >>> f = FenwickTree([1, 2, 0, 3, 0, 5]) >>> f.rank_query(0) -1 >>> f.rank_query(2) 0 >>> f.rank_query(1) 0 >>> f.rank_query(3) 2 >>> f.rank_query(5) 2 >>> f.rank_query(6) 4 >>> f.rank_query(11) 5 """ value -= self.tree[0] if value < 0: return -1 j = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 i = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Author Alexandre De Zotti Draws Julia sets of quadratic polynomials and exponential maps. More specifically, this iterates the function a fixed number of times then plots whether the absolute value of the last iterate is greater than a fixed threshold (named "escape radius"). For the exponential map this is not really an escape radius but rather a convenient way to approximate the Julia set with bounded orbits. The examples presented here are: - The Cauliflower Julia set, see e.g. https://en.wikipedia.org/wiki/File:Julia_z2%2B0,25.png - Other examples from https://en.wikipedia.org/wiki/Julia_set - An exponential map Julia set, ambiantly homeomorphic to the examples in https://www.math.univ-toulouse.fr/~cheritat/GalII/galery.html and https://ddd.uab.cat/pub/pubmat/02141493v43n1/02141493v43n1p27.pdf Remark: Some overflow runtime warnings are suppressed. This is because of the way the iteration loop is implemented, using numpy's efficient computations. Overflows and infinites are replaced after each step by a large number. """ import warnings from collections.abc import Callable from typing import Any import numpy from matplotlib import pyplot c_cauliflower = 0.25 + 0.0j c_polynomial_1 = -0.4 + 0.6j c_polynomial_2 = -0.1 + 0.651j c_exponential = -2.0 nb_iterations = 56 window_size = 2.0 nb_pixels = 666 def eval_exponential(c_parameter: complex, z_values: numpy.ndarray) -> numpy.ndarray: """ Evaluate $e^z + c$. >>> eval_exponential(0, 0) 1.0 >>> abs(eval_exponential(1, numpy.pi*1.j)) < 1e-15 True >>> abs(eval_exponential(1.j, 0)-1-1.j) < 1e-15 True """ return numpy.exp(z_values) + c_parameter def eval_quadratic_polynomial( c_parameter: complex, z_values: numpy.ndarray ) -> numpy.ndarray: """ >>> eval_quadratic_polynomial(0, 2) 4 >>> eval_quadratic_polynomial(-1, 1) 0 >>> round(eval_quadratic_polynomial(1.j, 0).imag) 1 >>> round(eval_quadratic_polynomial(1.j, 0).real) 0 """ return z_values * z_values + c_parameter def prepare_grid(window_size: float, nb_pixels: int) -> numpy.ndarray: """ Create a grid of complex values of size nb_pixels*nb_pixels with real and imaginary parts ranging from -window_size to window_size (inclusive). Returns a numpy array. >>> prepare_grid(1,3) array([[-1.-1.j, -1.+0.j, -1.+1.j], [ 0.-1.j, 0.+0.j, 0.+1.j], [ 1.-1.j, 1.+0.j, 1.+1.j]]) """ x = numpy.linspace(-window_size, window_size, nb_pixels) x = x.reshape((nb_pixels, 1)) y = numpy.linspace(-window_size, window_size, nb_pixels) y = y.reshape((1, nb_pixels)) return x + 1.0j * y def iterate_function( eval_function: Callable[[Any, numpy.ndarray], numpy.ndarray], function_params: Any, nb_iterations: int, z_0: numpy.ndarray, infinity: float = None, ) -> numpy.ndarray: """ Iterate the function "eval_function" exactly nb_iterations times. The first argument of the function is a parameter which is contained in function_params. The variable z_0 is an array that contains the initial values to iterate from. This function returns the final iterates. >>> iterate_function(eval_quadratic_polynomial, 0, 3, numpy.array([0,1,2])).shape (3,) >>> numpy.round(iterate_function(eval_quadratic_polynomial, ... 0, ... 3, ... numpy.array([0,1,2]))[0]) 0j >>> numpy.round(iterate_function(eval_quadratic_polynomial, ... 0, ... 3, ... numpy.array([0,1,2]))[1]) (1+0j) >>> numpy.round(iterate_function(eval_quadratic_polynomial, ... 0, ... 3, ... numpy.array([0,1,2]))[2]) (256+0j) """ z_n = z_0.astype("complex64") for _ in range(nb_iterations): z_n = eval_function(function_params, z_n) if infinity is not None: numpy.nan_to_num(z_n, copy=False, nan=infinity) z_n[abs(z_n) == numpy.inf] = infinity return z_n def show_results( function_label: str, function_params: Any, escape_radius: float, z_final: numpy.ndarray, ) -> None: """ Plots of whether the absolute value of z_final is greater than the value of escape_radius. Adds the function_label and function_params to the title. >>> show_results('80', 0, 1, numpy.array([[0,1,.5],[.4,2,1.1],[.2,1,1.3]])) """ abs_z_final = (abs(z_final)).transpose() abs_z_final[:, :] = abs_z_final[::-1, :] pyplot.matshow(abs_z_final < escape_radius) pyplot.title(f"Julia set of ${function_label}$, $c={function_params}$") pyplot.show() def ignore_overflow_warnings() -> None: """ Ignore some overflow and invalid value warnings. >>> ignore_overflow_warnings() """ warnings.filterwarnings( "ignore", category=RuntimeWarning, message="overflow encountered in multiply" ) warnings.filterwarnings( "ignore", category=RuntimeWarning, message="invalid value encountered in multiply", ) warnings.filterwarnings( "ignore", category=RuntimeWarning, message="overflow encountered in absolute" ) warnings.filterwarnings( "ignore", category=RuntimeWarning, message="overflow encountered in exp" ) if __name__ == "__main__": z_0 = prepare_grid(window_size, nb_pixels) ignore_overflow_warnings() # See file header for explanations nb_iterations = 24 escape_radius = 2 * abs(c_cauliflower) + 1 z_final = iterate_function( eval_quadratic_polynomial, c_cauliflower, nb_iterations, z_0, infinity=1.1 * escape_radius, ) show_results("z^2+c", c_cauliflower, escape_radius, z_final) nb_iterations = 64 escape_radius = 2 * abs(c_polynomial_1) + 1 z_final = iterate_function( eval_quadratic_polynomial, c_polynomial_1, nb_iterations, z_0, infinity=1.1 * escape_radius, ) show_results("z^2+c", c_polynomial_1, escape_radius, z_final) nb_iterations = 161 escape_radius = 2 * abs(c_polynomial_2) + 1 z_final = iterate_function( eval_quadratic_polynomial, c_polynomial_2, nb_iterations, z_0, infinity=1.1 * escape_radius, ) show_results("z^2+c", c_polynomial_2, escape_radius, z_final) nb_iterations = 12 escape_radius = 10000.0 z_final = iterate_function( eval_exponential, c_exponential, nb_iterations, z_0 + 2, infinity=1.0e10, ) show_results("e^z+c", c_exponential, escape_radius, z_final)
"""Author Alexandre De Zotti Draws Julia sets of quadratic polynomials and exponential maps. More specifically, this iterates the function a fixed number of times then plots whether the absolute value of the last iterate is greater than a fixed threshold (named "escape radius"). For the exponential map this is not really an escape radius but rather a convenient way to approximate the Julia set with bounded orbits. The examples presented here are: - The Cauliflower Julia set, see e.g. https://en.wikipedia.org/wiki/File:Julia_z2%2B0,25.png - Other examples from https://en.wikipedia.org/wiki/Julia_set - An exponential map Julia set, ambiantly homeomorphic to the examples in https://www.math.univ-toulouse.fr/~cheritat/GalII/galery.html and https://ddd.uab.cat/pub/pubmat/02141493v43n1/02141493v43n1p27.pdf Remark: Some overflow runtime warnings are suppressed. This is because of the way the iteration loop is implemented, using numpy's efficient computations. Overflows and infinites are replaced after each step by a large number. """ import warnings from collections.abc import Callable from typing import Any import numpy from matplotlib import pyplot c_cauliflower = 0.25 + 0.0j c_polynomial_1 = -0.4 + 0.6j c_polynomial_2 = -0.1 + 0.651j c_exponential = -2.0 nb_iterations = 56 window_size = 2.0 nb_pixels = 666 def eval_exponential(c_parameter: complex, z_values: numpy.ndarray) -> numpy.ndarray: """ Evaluate $e^z + c$. >>> eval_exponential(0, 0) 1.0 >>> abs(eval_exponential(1, numpy.pi*1.j)) < 1e-15 True >>> abs(eval_exponential(1.j, 0)-1-1.j) < 1e-15 True """ return numpy.exp(z_values) + c_parameter def eval_quadratic_polynomial( c_parameter: complex, z_values: numpy.ndarray ) -> numpy.ndarray: """ >>> eval_quadratic_polynomial(0, 2) 4 >>> eval_quadratic_polynomial(-1, 1) 0 >>> round(eval_quadratic_polynomial(1.j, 0).imag) 1 >>> round(eval_quadratic_polynomial(1.j, 0).real) 0 """ return z_values * z_values + c_parameter def prepare_grid(window_size: float, nb_pixels: int) -> numpy.ndarray: """ Create a grid of complex values of size nb_pixels*nb_pixels with real and imaginary parts ranging from -window_size to window_size (inclusive). Returns a numpy array. >>> prepare_grid(1,3) array([[-1.-1.j, -1.+0.j, -1.+1.j], [ 0.-1.j, 0.+0.j, 0.+1.j], [ 1.-1.j, 1.+0.j, 1.+1.j]]) """ x = numpy.linspace(-window_size, window_size, nb_pixels) x = x.reshape((nb_pixels, 1)) y = numpy.linspace(-window_size, window_size, nb_pixels) y = y.reshape((1, nb_pixels)) return x + 1.0j * y def iterate_function( eval_function: Callable[[Any, numpy.ndarray], numpy.ndarray], function_params: Any, nb_iterations: int, z_0: numpy.ndarray, infinity: float | None = None, ) -> numpy.ndarray: """ Iterate the function "eval_function" exactly nb_iterations times. The first argument of the function is a parameter which is contained in function_params. The variable z_0 is an array that contains the initial values to iterate from. This function returns the final iterates. >>> iterate_function(eval_quadratic_polynomial, 0, 3, numpy.array([0,1,2])).shape (3,) >>> numpy.round(iterate_function(eval_quadratic_polynomial, ... 0, ... 3, ... numpy.array([0,1,2]))[0]) 0j >>> numpy.round(iterate_function(eval_quadratic_polynomial, ... 0, ... 3, ... numpy.array([0,1,2]))[1]) (1+0j) >>> numpy.round(iterate_function(eval_quadratic_polynomial, ... 0, ... 3, ... numpy.array([0,1,2]))[2]) (256+0j) """ z_n = z_0.astype("complex64") for _ in range(nb_iterations): z_n = eval_function(function_params, z_n) if infinity is not None: numpy.nan_to_num(z_n, copy=False, nan=infinity) z_n[abs(z_n) == numpy.inf] = infinity return z_n def show_results( function_label: str, function_params: Any, escape_radius: float, z_final: numpy.ndarray, ) -> None: """ Plots of whether the absolute value of z_final is greater than the value of escape_radius. Adds the function_label and function_params to the title. >>> show_results('80', 0, 1, numpy.array([[0,1,.5],[.4,2,1.1],[.2,1,1.3]])) """ abs_z_final = (abs(z_final)).transpose() abs_z_final[:, :] = abs_z_final[::-1, :] pyplot.matshow(abs_z_final < escape_radius) pyplot.title(f"Julia set of ${function_label}$, $c={function_params}$") pyplot.show() def ignore_overflow_warnings() -> None: """ Ignore some overflow and invalid value warnings. >>> ignore_overflow_warnings() """ warnings.filterwarnings( "ignore", category=RuntimeWarning, message="overflow encountered in multiply" ) warnings.filterwarnings( "ignore", category=RuntimeWarning, message="invalid value encountered in multiply", ) warnings.filterwarnings( "ignore", category=RuntimeWarning, message="overflow encountered in absolute" ) warnings.filterwarnings( "ignore", category=RuntimeWarning, message="overflow encountered in exp" ) if __name__ == "__main__": z_0 = prepare_grid(window_size, nb_pixels) ignore_overflow_warnings() # See file header for explanations nb_iterations = 24 escape_radius = 2 * abs(c_cauliflower) + 1 z_final = iterate_function( eval_quadratic_polynomial, c_cauliflower, nb_iterations, z_0, infinity=1.1 * escape_radius, ) show_results("z^2+c", c_cauliflower, escape_radius, z_final) nb_iterations = 64 escape_radius = 2 * abs(c_polynomial_1) + 1 z_final = iterate_function( eval_quadratic_polynomial, c_polynomial_1, nb_iterations, z_0, infinity=1.1 * escape_radius, ) show_results("z^2+c", c_polynomial_1, escape_radius, z_final) nb_iterations = 161 escape_radius = 2 * abs(c_polynomial_2) + 1 z_final = iterate_function( eval_quadratic_polynomial, c_polynomial_2, nb_iterations, z_0, infinity=1.1 * escape_radius, ) show_results("z^2+c", c_polynomial_2, escape_radius, z_final) nb_iterations = 12 escape_radius = 10000.0 z_final = iterate_function( eval_exponential, c_exponential, nb_iterations, z_0 + 2, infinity=1.0e10, ) show_results("e^z+c", c_exponential, escape_radius, z_final)
1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import unittest import numpy as np def schur_complement( mat_a: np.ndarray, mat_b: np.ndarray, mat_c: np.ndarray, pseudo_inv: np.ndarray = None, ) -> np.ndarray: """ Schur complement of a symmetric matrix X given as a 2x2 block matrix consisting of matrices A, B and C. Matrix A must be quadratic and non-singular. In case A is singular, a pseudo-inverse may be provided using the pseudo_inv argument. Link to Wiki: https://en.wikipedia.org/wiki/Schur_complement See also Convex Optimization – Boyd and Vandenberghe, A.5.5 >>> import numpy as np >>> a = np.array([[1, 2], [2, 1]]) >>> b = np.array([[0, 3], [3, 0]]) >>> c = np.array([[2, 1], [6, 3]]) >>> schur_complement(a, b, c) array([[ 5., -5.], [ 0., 6.]]) """ shape_a = np.shape(mat_a) shape_b = np.shape(mat_b) shape_c = np.shape(mat_c) if shape_a[0] != shape_b[0]: raise ValueError( f"Expected the same number of rows for A and B. \ Instead found A of size {shape_a} and B of size {shape_b}" ) if shape_b[1] != shape_c[1]: raise ValueError( f"Expected the same number of columns for B and C. \ Instead found B of size {shape_b} and C of size {shape_c}" ) a_inv = pseudo_inv if a_inv is None: try: a_inv = np.linalg.inv(mat_a) except np.linalg.LinAlgError: raise ValueError( "Input matrix A is not invertible. Cannot compute Schur complement." ) return mat_c - mat_b.T @ a_inv @ mat_b class TestSchurComplement(unittest.TestCase): def test_schur_complement(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1], [6, 3]]) s = schur_complement(a, b, c) input_matrix = np.block([[a, b], [b.T, c]]) det_x = np.linalg.det(input_matrix) det_a = np.linalg.det(a) det_s = np.linalg.det(s) self.assertAlmostEqual(det_x, det_a * det_s) def test_improper_a_b_dimensions(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1], [6, 3]]) with self.assertRaises(ValueError): schur_complement(a, b, c) def test_improper_b_c_dimensions(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1, 3], [6, 3, 5]]) with self.assertRaises(ValueError): schur_complement(a, b, c) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
import unittest import numpy as np def schur_complement( mat_a: np.ndarray, mat_b: np.ndarray, mat_c: np.ndarray, pseudo_inv: np.ndarray | None = None, ) -> np.ndarray: """ Schur complement of a symmetric matrix X given as a 2x2 block matrix consisting of matrices A, B and C. Matrix A must be quadratic and non-singular. In case A is singular, a pseudo-inverse may be provided using the pseudo_inv argument. Link to Wiki: https://en.wikipedia.org/wiki/Schur_complement See also Convex Optimization – Boyd and Vandenberghe, A.5.5 >>> import numpy as np >>> a = np.array([[1, 2], [2, 1]]) >>> b = np.array([[0, 3], [3, 0]]) >>> c = np.array([[2, 1], [6, 3]]) >>> schur_complement(a, b, c) array([[ 5., -5.], [ 0., 6.]]) """ shape_a = np.shape(mat_a) shape_b = np.shape(mat_b) shape_c = np.shape(mat_c) if shape_a[0] != shape_b[0]: raise ValueError( f"Expected the same number of rows for A and B. \ Instead found A of size {shape_a} and B of size {shape_b}" ) if shape_b[1] != shape_c[1]: raise ValueError( f"Expected the same number of columns for B and C. \ Instead found B of size {shape_b} and C of size {shape_c}" ) a_inv = pseudo_inv if a_inv is None: try: a_inv = np.linalg.inv(mat_a) except np.linalg.LinAlgError: raise ValueError( "Input matrix A is not invertible. Cannot compute Schur complement." ) return mat_c - mat_b.T @ a_inv @ mat_b class TestSchurComplement(unittest.TestCase): def test_schur_complement(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1], [6, 3]]) s = schur_complement(a, b, c) input_matrix = np.block([[a, b], [b.T, c]]) det_x = np.linalg.det(input_matrix) det_a = np.linalg.det(a) det_s = np.linalg.det(s) self.assertAlmostEqual(det_x, det_a * det_s) def test_improper_a_b_dimensions(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1], [6, 3]]) with self.assertRaises(ValueError): schur_complement(a, b, c) def test_improper_b_c_dimensions(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1, 3], [6, 3, 5]]) with self.assertRaises(ValueError): schur_complement(a, b, c) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Linear Discriminant Analysis Assumptions About Data : 1. The input variables has a gaussian distribution. 2. The variance calculated for each input variables by class grouping is the same. 3. The mix of classes in your training set is representative of the problem. Learning The Model : The LDA model requires the estimation of statistics from the training data : 1. Mean of each input value for each class. 2. Probability of an instance belong to each class. 3. Covariance for the input data for each class Calculate the class means : mean(x) = 1/n ( for i = 1 to i = n --> sum(xi)) Calculate the class probabilities : P(y = 0) = count(y = 0) / (count(y = 0) + count(y = 1)) P(y = 1) = count(y = 1) / (count(y = 0) + count(y = 1)) Calculate the variance : We can calculate the variance for dataset in two steps : 1. Calculate the squared difference for each input variable from the group mean. 2. Calculate the mean of the squared difference. ------------------------------------------------ Squared_Difference = (x - mean(k)) ** 2 Variance = (1 / (count(x) - count(classes))) * (for i = 1 to i = n --> sum(Squared_Difference(xi))) Making Predictions : discriminant(x) = x * (mean / variance) - ((mean ** 2) / (2 * variance)) + Ln(probability) --------------------------------------------------------------------------- After calculating the discriminant value for each class, the class with the largest discriminant value is taken as the prediction. Author: @EverLookNeverSee """ from collections.abc import Callable from math import log from os import name, system from random import gauss, seed from typing import TypeVar # Make a training dataset drawn from a gaussian distribution def gaussian_distribution(mean: float, std_dev: float, instance_count: int) -> list: """ Generate gaussian distribution instances based-on given mean and standard deviation :param mean: mean value of class :param std_dev: value of standard deviation entered by usr or default value of it :param instance_count: instance number of class :return: a list containing generated values based-on given mean, std_dev and instance_count >>> gaussian_distribution(5.0, 1.0, 20) # doctest: +NORMALIZE_WHITESPACE [6.288184753155463, 6.4494456086997705, 5.066335808938262, 4.235456349028368, 3.9078267848958586, 5.031334516831717, 3.977896829989127, 3.56317055489747, 5.199311976483754, 5.133374604658605, 5.546468300338232, 4.086029056264687, 5.005005283626573, 4.935258239627312, 3.494170998739258, 5.537997178661033, 5.320711100998849, 7.3891120432406865, 5.202969177309964, 4.855297691835079] """ seed(1) return [gauss(mean, std_dev) for _ in range(instance_count)] # Make corresponding Y flags to detecting classes def y_generator(class_count: int, instance_count: list) -> list: """ Generate y values for corresponding classes :param class_count: Number of classes(data groupings) in dataset :param instance_count: number of instances in class :return: corresponding values for data groupings in dataset >>> y_generator(1, [10]) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> y_generator(2, [5, 10]) [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] >>> y_generator(4, [10, 5, 15, 20]) # doctest: +NORMALIZE_WHITESPACE [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] """ return [k for k in range(class_count) for _ in range(instance_count[k])] # Calculate the class means def calculate_mean(instance_count: int, items: list) -> float: """ Calculate given class mean :param instance_count: Number of instances in class :param items: items that related to specific class(data grouping) :return: calculated actual mean of considered class >>> items = gaussian_distribution(5.0, 1.0, 20) >>> calculate_mean(len(items), items) 5.011267842911003 """ # the sum of all items divided by number of instances return sum(items) / instance_count # Calculate the class probabilities def calculate_probabilities(instance_count: int, total_count: int) -> float: """ Calculate the probability that a given instance will belong to which class :param instance_count: number of instances in class :param total_count: the number of all instances :return: value of probability for considered class >>> calculate_probabilities(20, 60) 0.3333333333333333 >>> calculate_probabilities(30, 100) 0.3 """ # number of instances in specific class divided by number of all instances return instance_count / total_count # Calculate the variance def calculate_variance(items: list, means: list, total_count: int) -> float: """ Calculate the variance :param items: a list containing all items(gaussian distribution of all classes) :param means: a list containing real mean values of each class :param total_count: the number of all instances :return: calculated variance for considered dataset >>> items = gaussian_distribution(5.0, 1.0, 20) >>> means = [5.011267842911003] >>> total_count = 20 >>> calculate_variance([items], means, total_count) 0.9618530973487491 """ squared_diff = [] # An empty list to store all squared differences # iterate over number of elements in items for i in range(len(items)): # for loop iterates over number of elements in inner layer of items for j in range(len(items[i])): # appending squared differences to 'squared_diff' list squared_diff.append((items[i][j] - means[i]) ** 2) # one divided by (the number of all instances - number of classes) multiplied by # sum of all squared differences n_classes = len(means) # Number of classes in dataset return 1 / (total_count - n_classes) * sum(squared_diff) # Making predictions def predict_y_values( x_items: list, means: list, variance: float, probabilities: list ) -> list: """This function predicts new indexes(groups for our data) :param x_items: a list containing all items(gaussian distribution of all classes) :param means: a list containing real mean values of each class :param variance: calculated value of variance by calculate_variance function :param probabilities: a list containing all probabilities of classes :return: a list containing predicted Y values >>> x_items = [[6.288184753155463, 6.4494456086997705, 5.066335808938262, ... 4.235456349028368, 3.9078267848958586, 5.031334516831717, ... 3.977896829989127, 3.56317055489747, 5.199311976483754, ... 5.133374604658605, 5.546468300338232, 4.086029056264687, ... 5.005005283626573, 4.935258239627312, 3.494170998739258, ... 5.537997178661033, 5.320711100998849, 7.3891120432406865, ... 5.202969177309964, 4.855297691835079], [11.288184753155463, ... 11.44944560869977, 10.066335808938263, 9.235456349028368, ... 8.907826784895859, 10.031334516831716, 8.977896829989128, ... 8.56317055489747, 10.199311976483754, 10.133374604658606, ... 10.546468300338232, 9.086029056264687, 10.005005283626572, ... 9.935258239627313, 8.494170998739259, 10.537997178661033, ... 10.320711100998848, 12.389112043240686, 10.202969177309964, ... 9.85529769183508], [16.288184753155463, 16.449445608699772, ... 15.066335808938263, 14.235456349028368, 13.907826784895859, ... 15.031334516831716, 13.977896829989128, 13.56317055489747, ... 15.199311976483754, 15.133374604658606, 15.546468300338232, ... 14.086029056264687, 15.005005283626572, 14.935258239627313, ... 13.494170998739259, 15.537997178661033, 15.320711100998848, ... 17.389112043240686, 15.202969177309964, 14.85529769183508]] >>> means = [5.011267842911003, 10.011267842911003, 15.011267842911002] >>> variance = 0.9618530973487494 >>> probabilities = [0.3333333333333333, 0.3333333333333333, 0.3333333333333333] >>> predict_y_values(x_items, means, variance, ... probabilities) # doctest: +NORMALIZE_WHITESPACE [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] """ # An empty list to store generated discriminant values of all items in dataset for # each class results = [] # for loop iterates over number of elements in list for i in range(len(x_items)): # for loop iterates over number of inner items of each element for j in range(len(x_items[i])): temp = [] # to store all discriminant values of each item as a list # for loop iterates over number of classes we have in our dataset for k in range(len(x_items)): # appending values of discriminants for each class to 'temp' list temp.append( x_items[i][j] * (means[k] / variance) - (means[k] ** 2 / (2 * variance)) + log(probabilities[k]) ) # appending discriminant values of each item to 'results' list results.append(temp) return [result.index(max(result)) for result in results] # Calculating Accuracy def accuracy(actual_y: list, predicted_y: list) -> float: """ Calculate the value of accuracy based-on predictions :param actual_y:a list containing initial Y values generated by 'y_generator' function :param predicted_y: a list containing predicted Y values generated by 'predict_y_values' function :return: percentage of accuracy >>> actual_y = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, ... 1, 1 ,1 ,1 ,1 ,1 ,1] >>> predicted_y = [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, ... 0, 0, 1, 1, 1, 0, 1, 1, 1] >>> accuracy(actual_y, predicted_y) 50.0 >>> actual_y = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, ... 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] >>> predicted_y = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, ... 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] >>> accuracy(actual_y, predicted_y) 100.0 """ # iterate over one element of each list at a time (zip mode) # prediction is correct if actual Y value equals to predicted Y value correct = sum(1 for i, j in zip(actual_y, predicted_y) if i == j) # percentage of accuracy equals to number of correct predictions divided by number # of all data and multiplied by 100 return (correct / len(actual_y)) * 100 num = TypeVar("num") def valid_input( input_type: Callable[[object], num], # Usually float or int input_msg: str, err_msg: str, condition: Callable[[num], bool] = lambda x: True, default: str = None, ) -> num: """ Ask for user value and validate that it fulfill a condition. :input_type: user input expected type of value :input_msg: message to show user in the screen :err_msg: message to show in the screen in case of error :condition: function that represents the condition that user input is valid. :default: Default value in case the user does not type anything :return: user's input """ while True: try: user_input = input_type(input(input_msg).strip() or default) if condition(user_input): return user_input else: print(f"{user_input}: {err_msg}") continue except ValueError: print( f"{user_input}: Incorrect input type, expected {input_type.__name__!r}" ) # Main Function def main(): """This function starts execution phase""" while True: print(" Linear Discriminant Analysis ".center(50, "*")) print("*" * 50, "\n") print("First of all we should specify the number of classes that") print("we want to generate as training dataset") # Trying to get number of classes n_classes = valid_input( input_type=int, condition=lambda x: x > 0, input_msg="Enter the number of classes (Data Groupings): ", err_msg="Number of classes should be positive!", ) print("-" * 100) # Trying to get the value of standard deviation std_dev = valid_input( input_type=float, condition=lambda x: x >= 0, input_msg=( "Enter the value of standard deviation" "(Default value is 1.0 for all classes): " ), err_msg="Standard deviation should not be negative!", default="1.0", ) print("-" * 100) # Trying to get number of instances in classes and theirs means to generate # dataset counts = [] # An empty list to store instance counts of classes in dataset for i in range(n_classes): user_count = valid_input( input_type=int, condition=lambda x: x > 0, input_msg=(f"Enter The number of instances for class_{i+1}: "), err_msg="Number of instances should be positive!", ) counts.append(user_count) print("-" * 100) # An empty list to store values of user-entered means of classes user_means = [] for a in range(n_classes): user_mean = valid_input( input_type=float, input_msg=(f"Enter the value of mean for class_{a+1}: "), err_msg="This is an invalid value.", ) user_means.append(user_mean) print("-" * 100) print("Standard deviation: ", std_dev) # print out the number of instances in classes in separated line for i, count in enumerate(counts, 1): print(f"Number of instances in class_{i} is: {count}") print("-" * 100) # print out mean values of classes separated line for i, user_mean in enumerate(user_means, 1): print(f"Mean of class_{i} is: {user_mean}") print("-" * 100) # Generating training dataset drawn from gaussian distribution x = [ gaussian_distribution(user_means[j], std_dev, counts[j]) for j in range(n_classes) ] print("Generated Normal Distribution: \n", x) print("-" * 100) # Generating Ys to detecting corresponding classes y = y_generator(n_classes, counts) print("Generated Corresponding Ys: \n", y) print("-" * 100) # Calculating the value of actual mean for each class actual_means = [calculate_mean(counts[k], x[k]) for k in range(n_classes)] # for loop iterates over number of elements in 'actual_means' list and print # out them in separated line for i, actual_mean in enumerate(actual_means, 1): print(f"Actual(Real) mean of class_{i} is: {actual_mean}") print("-" * 100) # Calculating the value of probabilities for each class probabilities = [ calculate_probabilities(counts[i], sum(counts)) for i in range(n_classes) ] # for loop iterates over number of elements in 'probabilities' list and print # out them in separated line for i, probability in enumerate(probabilities, 1): print(f"Probability of class_{i} is: {probability}") print("-" * 100) # Calculating the values of variance for each class variance = calculate_variance(x, actual_means, sum(counts)) print("Variance: ", variance) print("-" * 100) # Predicting Y values # storing predicted Y values in 'pre_indexes' variable pre_indexes = predict_y_values(x, actual_means, variance, probabilities) print("-" * 100) # Calculating Accuracy of the model print(f"Accuracy: {accuracy(y, pre_indexes)}") print("-" * 100) print(" DONE ".center(100, "+")) if input("Press any key to restart or 'q' for quit: ").strip().lower() == "q": print("\n" + "GoodBye!".center(100, "-") + "\n") break system("cls" if name == "nt" else "clear") if __name__ == "__main__": main()
""" Linear Discriminant Analysis Assumptions About Data : 1. The input variables has a gaussian distribution. 2. The variance calculated for each input variables by class grouping is the same. 3. The mix of classes in your training set is representative of the problem. Learning The Model : The LDA model requires the estimation of statistics from the training data : 1. Mean of each input value for each class. 2. Probability of an instance belong to each class. 3. Covariance for the input data for each class Calculate the class means : mean(x) = 1/n ( for i = 1 to i = n --> sum(xi)) Calculate the class probabilities : P(y = 0) = count(y = 0) / (count(y = 0) + count(y = 1)) P(y = 1) = count(y = 1) / (count(y = 0) + count(y = 1)) Calculate the variance : We can calculate the variance for dataset in two steps : 1. Calculate the squared difference for each input variable from the group mean. 2. Calculate the mean of the squared difference. ------------------------------------------------ Squared_Difference = (x - mean(k)) ** 2 Variance = (1 / (count(x) - count(classes))) * (for i = 1 to i = n --> sum(Squared_Difference(xi))) Making Predictions : discriminant(x) = x * (mean / variance) - ((mean ** 2) / (2 * variance)) + Ln(probability) --------------------------------------------------------------------------- After calculating the discriminant value for each class, the class with the largest discriminant value is taken as the prediction. Author: @EverLookNeverSee """ from collections.abc import Callable from math import log from os import name, system from random import gauss, seed from typing import TypeVar # Make a training dataset drawn from a gaussian distribution def gaussian_distribution(mean: float, std_dev: float, instance_count: int) -> list: """ Generate gaussian distribution instances based-on given mean and standard deviation :param mean: mean value of class :param std_dev: value of standard deviation entered by usr or default value of it :param instance_count: instance number of class :return: a list containing generated values based-on given mean, std_dev and instance_count >>> gaussian_distribution(5.0, 1.0, 20) # doctest: +NORMALIZE_WHITESPACE [6.288184753155463, 6.4494456086997705, 5.066335808938262, 4.235456349028368, 3.9078267848958586, 5.031334516831717, 3.977896829989127, 3.56317055489747, 5.199311976483754, 5.133374604658605, 5.546468300338232, 4.086029056264687, 5.005005283626573, 4.935258239627312, 3.494170998739258, 5.537997178661033, 5.320711100998849, 7.3891120432406865, 5.202969177309964, 4.855297691835079] """ seed(1) return [gauss(mean, std_dev) for _ in range(instance_count)] # Make corresponding Y flags to detecting classes def y_generator(class_count: int, instance_count: list) -> list: """ Generate y values for corresponding classes :param class_count: Number of classes(data groupings) in dataset :param instance_count: number of instances in class :return: corresponding values for data groupings in dataset >>> y_generator(1, [10]) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >>> y_generator(2, [5, 10]) [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] >>> y_generator(4, [10, 5, 15, 20]) # doctest: +NORMALIZE_WHITESPACE [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] """ return [k for k in range(class_count) for _ in range(instance_count[k])] # Calculate the class means def calculate_mean(instance_count: int, items: list) -> float: """ Calculate given class mean :param instance_count: Number of instances in class :param items: items that related to specific class(data grouping) :return: calculated actual mean of considered class >>> items = gaussian_distribution(5.0, 1.0, 20) >>> calculate_mean(len(items), items) 5.011267842911003 """ # the sum of all items divided by number of instances return sum(items) / instance_count # Calculate the class probabilities def calculate_probabilities(instance_count: int, total_count: int) -> float: """ Calculate the probability that a given instance will belong to which class :param instance_count: number of instances in class :param total_count: the number of all instances :return: value of probability for considered class >>> calculate_probabilities(20, 60) 0.3333333333333333 >>> calculate_probabilities(30, 100) 0.3 """ # number of instances in specific class divided by number of all instances return instance_count / total_count # Calculate the variance def calculate_variance(items: list, means: list, total_count: int) -> float: """ Calculate the variance :param items: a list containing all items(gaussian distribution of all classes) :param means: a list containing real mean values of each class :param total_count: the number of all instances :return: calculated variance for considered dataset >>> items = gaussian_distribution(5.0, 1.0, 20) >>> means = [5.011267842911003] >>> total_count = 20 >>> calculate_variance([items], means, total_count) 0.9618530973487491 """ squared_diff = [] # An empty list to store all squared differences # iterate over number of elements in items for i in range(len(items)): # for loop iterates over number of elements in inner layer of items for j in range(len(items[i])): # appending squared differences to 'squared_diff' list squared_diff.append((items[i][j] - means[i]) ** 2) # one divided by (the number of all instances - number of classes) multiplied by # sum of all squared differences n_classes = len(means) # Number of classes in dataset return 1 / (total_count - n_classes) * sum(squared_diff) # Making predictions def predict_y_values( x_items: list, means: list, variance: float, probabilities: list ) -> list: """This function predicts new indexes(groups for our data) :param x_items: a list containing all items(gaussian distribution of all classes) :param means: a list containing real mean values of each class :param variance: calculated value of variance by calculate_variance function :param probabilities: a list containing all probabilities of classes :return: a list containing predicted Y values >>> x_items = [[6.288184753155463, 6.4494456086997705, 5.066335808938262, ... 4.235456349028368, 3.9078267848958586, 5.031334516831717, ... 3.977896829989127, 3.56317055489747, 5.199311976483754, ... 5.133374604658605, 5.546468300338232, 4.086029056264687, ... 5.005005283626573, 4.935258239627312, 3.494170998739258, ... 5.537997178661033, 5.320711100998849, 7.3891120432406865, ... 5.202969177309964, 4.855297691835079], [11.288184753155463, ... 11.44944560869977, 10.066335808938263, 9.235456349028368, ... 8.907826784895859, 10.031334516831716, 8.977896829989128, ... 8.56317055489747, 10.199311976483754, 10.133374604658606, ... 10.546468300338232, 9.086029056264687, 10.005005283626572, ... 9.935258239627313, 8.494170998739259, 10.537997178661033, ... 10.320711100998848, 12.389112043240686, 10.202969177309964, ... 9.85529769183508], [16.288184753155463, 16.449445608699772, ... 15.066335808938263, 14.235456349028368, 13.907826784895859, ... 15.031334516831716, 13.977896829989128, 13.56317055489747, ... 15.199311976483754, 15.133374604658606, 15.546468300338232, ... 14.086029056264687, 15.005005283626572, 14.935258239627313, ... 13.494170998739259, 15.537997178661033, 15.320711100998848, ... 17.389112043240686, 15.202969177309964, 14.85529769183508]] >>> means = [5.011267842911003, 10.011267842911003, 15.011267842911002] >>> variance = 0.9618530973487494 >>> probabilities = [0.3333333333333333, 0.3333333333333333, 0.3333333333333333] >>> predict_y_values(x_items, means, variance, ... probabilities) # doctest: +NORMALIZE_WHITESPACE [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] """ # An empty list to store generated discriminant values of all items in dataset for # each class results = [] # for loop iterates over number of elements in list for i in range(len(x_items)): # for loop iterates over number of inner items of each element for j in range(len(x_items[i])): temp = [] # to store all discriminant values of each item as a list # for loop iterates over number of classes we have in our dataset for k in range(len(x_items)): # appending values of discriminants for each class to 'temp' list temp.append( x_items[i][j] * (means[k] / variance) - (means[k] ** 2 / (2 * variance)) + log(probabilities[k]) ) # appending discriminant values of each item to 'results' list results.append(temp) return [result.index(max(result)) for result in results] # Calculating Accuracy def accuracy(actual_y: list, predicted_y: list) -> float: """ Calculate the value of accuracy based-on predictions :param actual_y:a list containing initial Y values generated by 'y_generator' function :param predicted_y: a list containing predicted Y values generated by 'predict_y_values' function :return: percentage of accuracy >>> actual_y = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, ... 1, 1 ,1 ,1 ,1 ,1 ,1] >>> predicted_y = [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, ... 0, 0, 1, 1, 1, 0, 1, 1, 1] >>> accuracy(actual_y, predicted_y) 50.0 >>> actual_y = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, ... 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] >>> predicted_y = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, ... 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] >>> accuracy(actual_y, predicted_y) 100.0 """ # iterate over one element of each list at a time (zip mode) # prediction is correct if actual Y value equals to predicted Y value correct = sum(1 for i, j in zip(actual_y, predicted_y) if i == j) # percentage of accuracy equals to number of correct predictions divided by number # of all data and multiplied by 100 return (correct / len(actual_y)) * 100 num = TypeVar("num") def valid_input( input_type: Callable[[object], num], # Usually float or int input_msg: str, err_msg: str, condition: Callable[[num], bool] = lambda x: True, default: str | None = None, ) -> num: """ Ask for user value and validate that it fulfill a condition. :input_type: user input expected type of value :input_msg: message to show user in the screen :err_msg: message to show in the screen in case of error :condition: function that represents the condition that user input is valid. :default: Default value in case the user does not type anything :return: user's input """ while True: try: user_input = input_type(input(input_msg).strip() or default) if condition(user_input): return user_input else: print(f"{user_input}: {err_msg}") continue except ValueError: print( f"{user_input}: Incorrect input type, expected {input_type.__name__!r}" ) # Main Function def main(): """This function starts execution phase""" while True: print(" Linear Discriminant Analysis ".center(50, "*")) print("*" * 50, "\n") print("First of all we should specify the number of classes that") print("we want to generate as training dataset") # Trying to get number of classes n_classes = valid_input( input_type=int, condition=lambda x: x > 0, input_msg="Enter the number of classes (Data Groupings): ", err_msg="Number of classes should be positive!", ) print("-" * 100) # Trying to get the value of standard deviation std_dev = valid_input( input_type=float, condition=lambda x: x >= 0, input_msg=( "Enter the value of standard deviation" "(Default value is 1.0 for all classes): " ), err_msg="Standard deviation should not be negative!", default="1.0", ) print("-" * 100) # Trying to get number of instances in classes and theirs means to generate # dataset counts = [] # An empty list to store instance counts of classes in dataset for i in range(n_classes): user_count = valid_input( input_type=int, condition=lambda x: x > 0, input_msg=(f"Enter The number of instances for class_{i+1}: "), err_msg="Number of instances should be positive!", ) counts.append(user_count) print("-" * 100) # An empty list to store values of user-entered means of classes user_means = [] for a in range(n_classes): user_mean = valid_input( input_type=float, input_msg=(f"Enter the value of mean for class_{a+1}: "), err_msg="This is an invalid value.", ) user_means.append(user_mean) print("-" * 100) print("Standard deviation: ", std_dev) # print out the number of instances in classes in separated line for i, count in enumerate(counts, 1): print(f"Number of instances in class_{i} is: {count}") print("-" * 100) # print out mean values of classes separated line for i, user_mean in enumerate(user_means, 1): print(f"Mean of class_{i} is: {user_mean}") print("-" * 100) # Generating training dataset drawn from gaussian distribution x = [ gaussian_distribution(user_means[j], std_dev, counts[j]) for j in range(n_classes) ] print("Generated Normal Distribution: \n", x) print("-" * 100) # Generating Ys to detecting corresponding classes y = y_generator(n_classes, counts) print("Generated Corresponding Ys: \n", y) print("-" * 100) # Calculating the value of actual mean for each class actual_means = [calculate_mean(counts[k], x[k]) for k in range(n_classes)] # for loop iterates over number of elements in 'actual_means' list and print # out them in separated line for i, actual_mean in enumerate(actual_means, 1): print(f"Actual(Real) mean of class_{i} is: {actual_mean}") print("-" * 100) # Calculating the value of probabilities for each class probabilities = [ calculate_probabilities(counts[i], sum(counts)) for i in range(n_classes) ] # for loop iterates over number of elements in 'probabilities' list and print # out them in separated line for i, probability in enumerate(probabilities, 1): print(f"Probability of class_{i} is: {probability}") print("-" * 100) # Calculating the values of variance for each class variance = calculate_variance(x, actual_means, sum(counts)) print("Variance: ", variance) print("-" * 100) # Predicting Y values # storing predicted Y values in 'pre_indexes' variable pre_indexes = predict_y_values(x, actual_means, variance, probabilities) print("-" * 100) # Calculating Accuracy of the model print(f"Accuracy: {accuracy(y, pre_indexes)}") print("-" * 100) print(" DONE ".center(100, "+")) if input("Press any key to restart or 'q' for quit: ").strip().lower() == "q": print("\n" + "GoodBye!".center(100, "-") + "\n") break system("cls" if name == "nt" else "clear") if __name__ == "__main__": main()
1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 74: https://projecteuler.net/problem=74 The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145: 1! + 4! + 5! = 1 + 24 + 120 = 145 Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist: 169 → 363601 → 1454 → 169 871 → 45361 → 871 872 → 45362 → 872 It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example, 69 → 363600 → 1454 → 169 → 363601 (→ 1454) 78 → 45360 → 871 → 45361 (→ 871) 540 → 145 (→ 145) Starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting number below one million is sixty terms. How many chains, with a starting number below one million, contain exactly sixty non-repeating terms? """ DIGIT_FACTORIALS = { "0": 1, "1": 1, "2": 2, "3": 6, "4": 24, "5": 120, "6": 720, "7": 5040, "8": 40320, "9": 362880, } CACHE_SUM_DIGIT_FACTORIALS = {145: 145} CHAIN_LENGTH_CACHE = { 145: 0, 169: 3, 36301: 3, 1454: 3, 871: 2, 45361: 2, 872: 2, } def sum_digit_factorials(n: int) -> int: """ Return the sum of the factorial of the digits of n. >>> sum_digit_factorials(145) 145 >>> sum_digit_factorials(45361) 871 >>> sum_digit_factorials(540) 145 """ if n in CACHE_SUM_DIGIT_FACTORIALS: return CACHE_SUM_DIGIT_FACTORIALS[n] ret = sum(DIGIT_FACTORIALS[let] for let in str(n)) CACHE_SUM_DIGIT_FACTORIALS[n] = ret return ret def chain_length(n: int, previous: set = None) -> int: """ Calculate the length of the chain of non-repeating terms starting with n. Previous is a set containing the previous member of the chain. >>> chain_length(10101) 11 >>> chain_length(555) 20 >>> chain_length(178924) 39 """ previous = previous or set() if n in CHAIN_LENGTH_CACHE: return CHAIN_LENGTH_CACHE[n] next_number = sum_digit_factorials(n) if next_number in previous: CHAIN_LENGTH_CACHE[n] = 0 return 0 else: previous.add(n) ret = 1 + chain_length(next_number, previous) CHAIN_LENGTH_CACHE[n] = ret return ret def solution(num_terms: int = 60, max_start: int = 1000000) -> int: """ Return the number of chains with a starting number below one million which contain exactly n non-repeating terms. >>> solution(10,1000) 28 """ return sum(1 for i in range(1, max_start) if chain_length(i) == num_terms) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 74: https://projecteuler.net/problem=74 The number 145 is well known for the property that the sum of the factorial of its digits is equal to 145: 1! + 4! + 5! = 1 + 24 + 120 = 145 Perhaps less well known is 169, in that it produces the longest chain of numbers that link back to 169; it turns out that there are only three such loops that exist: 169 → 363601 → 1454 → 169 871 → 45361 → 871 872 → 45362 → 872 It is not difficult to prove that EVERY starting number will eventually get stuck in a loop. For example, 69 → 363600 → 1454 → 169 → 363601 (→ 1454) 78 → 45360 → 871 → 45361 (→ 871) 540 → 145 (→ 145) Starting with 69 produces a chain of five non-repeating terms, but the longest non-repeating chain with a starting number below one million is sixty terms. How many chains, with a starting number below one million, contain exactly sixty non-repeating terms? """ DIGIT_FACTORIALS = { "0": 1, "1": 1, "2": 2, "3": 6, "4": 24, "5": 120, "6": 720, "7": 5040, "8": 40320, "9": 362880, } CACHE_SUM_DIGIT_FACTORIALS = {145: 145} CHAIN_LENGTH_CACHE = { 145: 0, 169: 3, 36301: 3, 1454: 3, 871: 2, 45361: 2, 872: 2, } def sum_digit_factorials(n: int) -> int: """ Return the sum of the factorial of the digits of n. >>> sum_digit_factorials(145) 145 >>> sum_digit_factorials(45361) 871 >>> sum_digit_factorials(540) 145 """ if n in CACHE_SUM_DIGIT_FACTORIALS: return CACHE_SUM_DIGIT_FACTORIALS[n] ret = sum(DIGIT_FACTORIALS[let] for let in str(n)) CACHE_SUM_DIGIT_FACTORIALS[n] = ret return ret def chain_length(n: int, previous: set | None = None) -> int: """ Calculate the length of the chain of non-repeating terms starting with n. Previous is a set containing the previous member of the chain. >>> chain_length(10101) 11 >>> chain_length(555) 20 >>> chain_length(178924) 39 """ previous = previous or set() if n in CHAIN_LENGTH_CACHE: return CHAIN_LENGTH_CACHE[n] next_number = sum_digit_factorials(n) if next_number in previous: CHAIN_LENGTH_CACHE[n] = 0 return 0 else: previous.add(n) ret = 1 + chain_length(next_number, previous) CHAIN_LENGTH_CACHE[n] = ret return ret def solution(num_terms: int = 60, max_start: int = 1000000) -> int: """ Return the number of chains with a starting number below one million which contain exactly n non-repeating terms. >>> solution(10,1000) 28 """ return sum(1 for i in range(1, max_start) if chain_length(i) == num_terms) if __name__ == "__main__": print(f"{solution() = }")
1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import operator def strand_sort(arr: list, reverse: bool = False, solution: list = None) -> list: """ Strand sort implementation source: https://en.wikipedia.org/wiki/Strand_sort :param arr: Unordered input list :param reverse: Descent ordering flag :param solution: Ordered items container Examples: >>> strand_sort([4, 2, 5, 3, 0, 1]) [0, 1, 2, 3, 4, 5] >>> strand_sort([4, 2, 5, 3, 0, 1], reverse=True) [5, 4, 3, 2, 1, 0] """ _operator = operator.lt if reverse else operator.gt solution = solution or [] if not arr: return solution sublist = [arr.pop(0)] for i, item in enumerate(arr): if _operator(item, sublist[-1]): sublist.append(item) arr.pop(i) # merging sublist into solution list if not solution: solution.extend(sublist) else: while sublist: item = sublist.pop(0) for i, xx in enumerate(solution): if not _operator(item, xx): solution.insert(i, item) break else: solution.append(item) strand_sort(arr, reverse, solution) return solution if __name__ == "__main__": assert strand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5] assert strand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1]
import operator def strand_sort(arr: list, reverse: bool = False, solution: list | None = None) -> list: """ Strand sort implementation source: https://en.wikipedia.org/wiki/Strand_sort :param arr: Unordered input list :param reverse: Descent ordering flag :param solution: Ordered items container Examples: >>> strand_sort([4, 2, 5, 3, 0, 1]) [0, 1, 2, 3, 4, 5] >>> strand_sort([4, 2, 5, 3, 0, 1], reverse=True) [5, 4, 3, 2, 1, 0] """ _operator = operator.lt if reverse else operator.gt solution = solution or [] if not arr: return solution sublist = [arr.pop(0)] for i, item in enumerate(arr): if _operator(item, sublist[-1]): sublist.append(item) arr.pop(i) # merging sublist into solution list if not solution: solution.extend(sublist) else: while sublist: item = sublist.pop(0) for i, xx in enumerate(solution): if not _operator(item, xx): solution.insert(i, item) break else: solution.append(item) strand_sort(arr, reverse, solution) return solution if __name__ == "__main__": assert strand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5] assert strand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1]
1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" author : Mayank Kumar Jha (mk9440) """ from __future__ import annotations def find_max_sub_array(a, low, high): if low == high: return low, high, a[low] else: mid = (low + high) // 2 left_low, left_high, left_sum = find_max_sub_array(a, low, mid) right_low, right_high, right_sum = find_max_sub_array(a, mid + 1, high) cross_left, cross_right, cross_sum = find_max_cross_sum(a, low, mid, high) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum else: return cross_left, cross_right, cross_sum def find_max_cross_sum(a, low, mid, high): left_sum, max_left = -999999999, -1 right_sum, max_right = -999999999, -1 summ = 0 for i in range(mid, low - 1, -1): summ += a[i] if summ > left_sum: left_sum = summ max_left = i summ = 0 for i in range(mid + 1, high + 1): summ += a[i] if summ > right_sum: right_sum = summ max_right = i return max_left, max_right, (left_sum + right_sum) def max_sub_array(nums: list[int]) -> int: """ Finds the contiguous subarray which has the largest sum and return its sum. >>> max_sub_array([-2, 1, -3, 4, -1, 2, 1, -5, 4]) 6 An empty (sub)array has sum 0. >>> max_sub_array([]) 0 If all elements are negative, the largest subarray would be the empty array, having the sum 0. >>> max_sub_array([-1, -2, -3]) 0 >>> max_sub_array([5, -2, -3]) 5 >>> max_sub_array([31, -41, 59, 26, -53, 58, 97, -93, -23, 84]) 187 """ best = 0 current = 0 for i in nums: current += i if current < 0: current = 0 best = max(best, current) return best if __name__ == "__main__": """ A random simulation of this algorithm. """ import time from random import randint from matplotlib import pyplot as plt inputs = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000] tim = [] for i in inputs: li = [randint(1, i) for j in range(i)] strt = time.time() (find_max_sub_array(li, 0, len(li) - 1)) end = time.time() tim.append(end - strt) print("No of Inputs Time Taken") for i in range(len(inputs)): print(inputs[i], "\t\t", tim[i]) plt.plot(inputs, tim) plt.xlabel("Number of Inputs") plt.ylabel("Time taken in seconds ") plt.show()
""" author : Mayank Kumar Jha (mk9440) """ from __future__ import annotations def find_max_sub_array(a, low, high): if low == high: return low, high, a[low] else: mid = (low + high) // 2 left_low, left_high, left_sum = find_max_sub_array(a, low, mid) right_low, right_high, right_sum = find_max_sub_array(a, mid + 1, high) cross_left, cross_right, cross_sum = find_max_cross_sum(a, low, mid, high) if left_sum >= right_sum and left_sum >= cross_sum: return left_low, left_high, left_sum elif right_sum >= left_sum and right_sum >= cross_sum: return right_low, right_high, right_sum else: return cross_left, cross_right, cross_sum def find_max_cross_sum(a, low, mid, high): left_sum, max_left = -999999999, -1 right_sum, max_right = -999999999, -1 summ = 0 for i in range(mid, low - 1, -1): summ += a[i] if summ > left_sum: left_sum = summ max_left = i summ = 0 for i in range(mid + 1, high + 1): summ += a[i] if summ > right_sum: right_sum = summ max_right = i return max_left, max_right, (left_sum + right_sum) def max_sub_array(nums: list[int]) -> int: """ Finds the contiguous subarray which has the largest sum and return its sum. >>> max_sub_array([-2, 1, -3, 4, -1, 2, 1, -5, 4]) 6 An empty (sub)array has sum 0. >>> max_sub_array([]) 0 If all elements are negative, the largest subarray would be the empty array, having the sum 0. >>> max_sub_array([-1, -2, -3]) 0 >>> max_sub_array([5, -2, -3]) 5 >>> max_sub_array([31, -41, 59, 26, -53, 58, 97, -93, -23, 84]) 187 """ best = 0 current = 0 for i in nums: current += i if current < 0: current = 0 best = max(best, current) return best if __name__ == "__main__": """ A random simulation of this algorithm. """ import time from random import randint from matplotlib import pyplot as plt inputs = [10, 100, 1000, 10000, 50000, 100000, 200000, 300000, 400000, 500000] tim = [] for i in inputs: li = [randint(1, i) for j in range(i)] strt = time.time() (find_max_sub_array(li, 0, len(li) - 1)) end = time.time() tim.append(end - strt) print("No of Inputs Time Taken") for i in range(len(inputs)): print(inputs[i], "\t\t", tim[i]) plt.plot(inputs, tim) plt.xlabel("Number of Inputs") plt.ylabel("Time taken in seconds ") plt.show()
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
NUMBERS_PLUS_LETTER = "Input must be a string of 8 numbers plus letter" LOOKUP_LETTERS = "TRWAGMYFPDXBNJZSQVHLCKE" def is_spain_national_id(spanish_id: str) -> bool: """ Spain National Id is a string composed by 8 numbers plus a letter The letter in fact is not part of the ID, it acts as a validator, checking you didn't do a mistake when entering it on a system or are giving a fake one. https://en.wikipedia.org/wiki/Documento_Nacional_de_Identidad_(Spain)#Number >>> is_spain_national_id("12345678Z") True >>> is_spain_national_id("12345678z") # It is case-insensitive True >>> is_spain_national_id("12345678x") False >>> is_spain_national_id("12345678I") False >>> is_spain_national_id("12345678-Z") # Some systems add a dash True >>> is_spain_national_id("12345678") Traceback (most recent call last): ... ValueError: Input must be a string of 8 numbers plus letter >>> is_spain_national_id("123456709") Traceback (most recent call last): ... ValueError: Input must be a string of 8 numbers plus letter >>> is_spain_national_id("1234567--Z") Traceback (most recent call last): ... ValueError: Input must be a string of 8 numbers plus letter >>> is_spain_national_id("1234Z") Traceback (most recent call last): ... ValueError: Input must be a string of 8 numbers plus letter >>> is_spain_national_id("1234ZzZZ") Traceback (most recent call last): ... ValueError: Input must be a string of 8 numbers plus letter >>> is_spain_national_id(12345678) Traceback (most recent call last): ... TypeError: Expected string as input, found int """ if not isinstance(spanish_id, str): raise TypeError(f"Expected string as input, found {type(spanish_id).__name__}") spanish_id_clean = spanish_id.replace("-", "").upper() if len(spanish_id_clean) != 9: raise ValueError(NUMBERS_PLUS_LETTER) try: number = int(spanish_id_clean[0:8]) letter = spanish_id_clean[8] except ValueError as ex: raise ValueError(NUMBERS_PLUS_LETTER) from ex if letter.isdigit(): raise ValueError(NUMBERS_PLUS_LETTER) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
NUMBERS_PLUS_LETTER = "Input must be a string of 8 numbers plus letter" LOOKUP_LETTERS = "TRWAGMYFPDXBNJZSQVHLCKE" def is_spain_national_id(spanish_id: str) -> bool: """ Spain National Id is a string composed by 8 numbers plus a letter The letter in fact is not part of the ID, it acts as a validator, checking you didn't do a mistake when entering it on a system or are giving a fake one. https://en.wikipedia.org/wiki/Documento_Nacional_de_Identidad_(Spain)#Number >>> is_spain_national_id("12345678Z") True >>> is_spain_national_id("12345678z") # It is case-insensitive True >>> is_spain_national_id("12345678x") False >>> is_spain_national_id("12345678I") False >>> is_spain_national_id("12345678-Z") # Some systems add a dash True >>> is_spain_national_id("12345678") Traceback (most recent call last): ... ValueError: Input must be a string of 8 numbers plus letter >>> is_spain_national_id("123456709") Traceback (most recent call last): ... ValueError: Input must be a string of 8 numbers plus letter >>> is_spain_national_id("1234567--Z") Traceback (most recent call last): ... ValueError: Input must be a string of 8 numbers plus letter >>> is_spain_national_id("1234Z") Traceback (most recent call last): ... ValueError: Input must be a string of 8 numbers plus letter >>> is_spain_national_id("1234ZzZZ") Traceback (most recent call last): ... ValueError: Input must be a string of 8 numbers plus letter >>> is_spain_national_id(12345678) Traceback (most recent call last): ... TypeError: Expected string as input, found int """ if not isinstance(spanish_id, str): raise TypeError(f"Expected string as input, found {type(spanish_id).__name__}") spanish_id_clean = spanish_id.replace("-", "").upper() if len(spanish_id_clean) != 9: raise ValueError(NUMBERS_PLUS_LETTER) try: number = int(spanish_id_clean[0:8]) letter = spanish_id_clean[8] except ValueError as ex: raise ValueError(NUMBERS_PLUS_LETTER) from ex if letter.isdigit(): raise ValueError(NUMBERS_PLUS_LETTER) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Created by susmith98 from collections import Counter from timeit import timeit # Problem Description: # Check if characters of the given string can be rearranged to form a palindrome. # Counter is faster for long strings and non-Counter is faster for short strings. def can_string_be_rearranged_as_palindrome_counter( input_str: str = "", ) -> bool: """ A Palindrome is a String that reads the same forward as it does backwards. Examples of Palindromes mom, dad, malayalam >>> can_string_be_rearranged_as_palindrome_counter("Momo") True >>> can_string_be_rearranged_as_palindrome_counter("Mother") False >>> can_string_be_rearranged_as_palindrome_counter("Father") False >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama") True """ return sum(c % 2 for c in Counter(input_str.replace(" ", "").lower()).values()) < 2 def can_string_be_rearranged_as_palindrome(input_str: str = "") -> bool: """ A Palindrome is a String that reads the same forward as it does backwards. Examples of Palindromes mom, dad, malayalam >>> can_string_be_rearranged_as_palindrome("Momo") True >>> can_string_be_rearranged_as_palindrome("Mother") False >>> can_string_be_rearranged_as_palindrome("Father") False >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama") True """ if len(input_str) == 0: return True lower_case_input_str = input_str.replace(" ", "").lower() # character_freq_dict: Stores the frequency of every character in the input string character_freq_dict: dict[str, int] = {} for character in lower_case_input_str: character_freq_dict[character] = character_freq_dict.get(character, 0) + 1 """ Above line of code is equivalent to: 1) Getting the frequency of current character till previous index >>> character_freq = character_freq_dict.get(character, 0) 2) Incrementing the frequency of current character by 1 >>> character_freq = character_freq + 1 3) Updating the frequency of current character >>> character_freq_dict[character] = character_freq """ """ OBSERVATIONS: Even length palindrome -> Every character appears even no.of times. Odd length palindrome -> Every character appears even no.of times except for one character. LOGIC: Step 1: We'll count number of characters that appear odd number of times i.e oddChar Step 2:If we find more than 1 character that appears odd number of times, It is not possible to rearrange as a palindrome """ odd_char = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def benchmark(input_str: str = "") -> None: """ Benchmark code for comparing above 2 functions """ print("\nFor string = ", input_str, ":") print( "> can_string_be_rearranged_as_palindrome_counter()", "\tans =", can_string_be_rearranged_as_palindrome_counter(input_str), "\ttime =", timeit( "z.can_string_be_rearranged_as_palindrome_counter(z.check_str)", setup="import __main__ as z", ), "seconds", ) print( "> can_string_be_rearranged_as_palindrome()", "\tans =", can_string_be_rearranged_as_palindrome(input_str), "\ttime =", timeit( "z.can_string_be_rearranged_as_palindrome(z.check_str)", setup="import __main__ as z", ), "seconds", ) if __name__ == "__main__": check_str = input( "Enter string to determine if it can be rearranged as a palindrome or not: " ).strip() benchmark(check_str) status = can_string_be_rearranged_as_palindrome_counter(check_str) print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
# Created by susmith98 from collections import Counter from timeit import timeit # Problem Description: # Check if characters of the given string can be rearranged to form a palindrome. # Counter is faster for long strings and non-Counter is faster for short strings. def can_string_be_rearranged_as_palindrome_counter( input_str: str = "", ) -> bool: """ A Palindrome is a String that reads the same forward as it does backwards. Examples of Palindromes mom, dad, malayalam >>> can_string_be_rearranged_as_palindrome_counter("Momo") True >>> can_string_be_rearranged_as_palindrome_counter("Mother") False >>> can_string_be_rearranged_as_palindrome_counter("Father") False >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama") True """ return sum(c % 2 for c in Counter(input_str.replace(" ", "").lower()).values()) < 2 def can_string_be_rearranged_as_palindrome(input_str: str = "") -> bool: """ A Palindrome is a String that reads the same forward as it does backwards. Examples of Palindromes mom, dad, malayalam >>> can_string_be_rearranged_as_palindrome("Momo") True >>> can_string_be_rearranged_as_palindrome("Mother") False >>> can_string_be_rearranged_as_palindrome("Father") False >>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama") True """ if len(input_str) == 0: return True lower_case_input_str = input_str.replace(" ", "").lower() # character_freq_dict: Stores the frequency of every character in the input string character_freq_dict: dict[str, int] = {} for character in lower_case_input_str: character_freq_dict[character] = character_freq_dict.get(character, 0) + 1 """ Above line of code is equivalent to: 1) Getting the frequency of current character till previous index >>> character_freq = character_freq_dict.get(character, 0) 2) Incrementing the frequency of current character by 1 >>> character_freq = character_freq + 1 3) Updating the frequency of current character >>> character_freq_dict[character] = character_freq """ """ OBSERVATIONS: Even length palindrome -> Every character appears even no.of times. Odd length palindrome -> Every character appears even no.of times except for one character. LOGIC: Step 1: We'll count number of characters that appear odd number of times i.e oddChar Step 2:If we find more than 1 character that appears odd number of times, It is not possible to rearrange as a palindrome """ odd_char = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def benchmark(input_str: str = "") -> None: """ Benchmark code for comparing above 2 functions """ print("\nFor string = ", input_str, ":") print( "> can_string_be_rearranged_as_palindrome_counter()", "\tans =", can_string_be_rearranged_as_palindrome_counter(input_str), "\ttime =", timeit( "z.can_string_be_rearranged_as_palindrome_counter(z.check_str)", setup="import __main__ as z", ), "seconds", ) print( "> can_string_be_rearranged_as_palindrome()", "\tans =", can_string_be_rearranged_as_palindrome(input_str), "\ttime =", timeit( "z.can_string_be_rearranged_as_palindrome(z.check_str)", setup="import __main__ as z", ), "seconds", ) if __name__ == "__main__": check_str = input( "Enter string to determine if it can be rearranged as a palindrome or not: " ).strip() benchmark(check_str) status = can_string_be_rearranged_as_palindrome_counter(check_str) print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementation of sequential minimal optimization (SMO) for support vector machines (SVM). Sequential minimal optimization (SMO) is an algorithm for solving the quadratic programming (QP) problem that arises during the training of support vector machines. It was invented by John Platt in 1998. Input: 0: type: numpy.ndarray. 1: first column of ndarray must be tags of samples, must be 1 or -1. 2: rows of ndarray represent samples. Usage: Command: python3 sequential_minimum_optimization.py Code: from sequential_minimum_optimization import SmoSVM, Kernel kernel = Kernel(kernel='poly', degree=3., coef0=1., gamma=0.5) init_alphas = np.zeros(train.shape[0]) SVM = SmoSVM(train=train, alpha_list=init_alphas, kernel_func=kernel, cost=0.4, b=0.0, tolerance=0.001) SVM.fit() predict = SVM.predict(test_samples) Reference: https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/smo-book.pdf https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-98-14.pdf """ import os import sys import urllib.request import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.datasets import make_blobs, make_circles from sklearn.preprocessing import StandardScaler CANCER_DATASET_URL = ( "https://archive.ics.uci.edu/ml/machine-learning-databases/" "breast-cancer-wisconsin/wdbc.data" ) class SmoSVM: def __init__( self, train, kernel_func, alpha_list=None, cost=0.4, b=0.0, tolerance=0.001, auto_norm=True, ): self._init = True self._auto_norm = auto_norm self._c = np.float64(cost) self._b = np.float64(b) self._tol = np.float64(tolerance) if tolerance > 0.0001 else np.float64(0.001) self.tags = train[:, 0] self.samples = self._norm(train[:, 1:]) if self._auto_norm else train[:, 1:] self.alphas = alpha_list if alpha_list is not None else np.zeros(train.shape[0]) self.Kernel = kernel_func self._eps = 0.001 self._all_samples = list(range(self.length)) self._K_matrix = self._calculate_k_matrix() self._error = np.zeros(self.length) self._unbound = [] self.choose_alpha = self._choose_alphas() # Calculate alphas using SMO algorithm def fit(self): k = self._k state = None while True: # 1: Find alpha1, alpha2 try: i1, i2 = self.choose_alpha.send(state) state = None except StopIteration: print("Optimization done!\nEvery sample satisfy the KKT condition!") break # 2: calculate new alpha2 and new alpha1 y1, y2 = self.tags[i1], self.tags[i2] a1, a2 = self.alphas[i1].copy(), self.alphas[i2].copy() e1, e2 = self._e(i1), self._e(i2) args = (i1, i2, a1, a2, e1, e2, y1, y2) a1_new, a2_new = self._get_new_alpha(*args) if not a1_new and not a2_new: state = False continue self.alphas[i1], self.alphas[i2] = a1_new, a2_new # 3: update threshold(b) b1_new = np.float64( -e1 - y1 * k(i1, i1) * (a1_new - a1) - y2 * k(i2, i1) * (a2_new - a2) + self._b ) b2_new = np.float64( -e2 - y2 * k(i2, i2) * (a2_new - a2) - y1 * k(i1, i2) * (a1_new - a1) + self._b ) if 0.0 < a1_new < self._c: b = b1_new if 0.0 < a2_new < self._c: b = b2_new if not (np.float64(0) < a2_new < self._c) and not ( np.float64(0) < a1_new < self._c ): b = (b1_new + b2_new) / 2.0 b_old = self._b self._b = b # 4: update error value,here we only calculate those non-bound samples' # error self._unbound = [i for i in self._all_samples if self._is_unbound(i)] for s in self.unbound: if s == i1 or s == i2: continue self._error[s] += ( y1 * (a1_new - a1) * k(i1, s) + y2 * (a2_new - a2) * k(i2, s) + (self._b - b_old) ) # if i1 or i2 is non-bound,update there error value to zero if self._is_unbound(i1): self._error[i1] = 0 if self._is_unbound(i2): self._error[i2] = 0 # Predict test samples def predict(self, test_samples, classify=True): if test_samples.shape[1] > self.samples.shape[1]: raise ValueError( "Test samples' feature length does not equal to that of train samples" ) if self._auto_norm: test_samples = self._norm(test_samples) results = [] for test_sample in test_samples: result = self._predict(test_sample) if classify: results.append(1 if result > 0 else -1) else: results.append(result) return np.array(results) # Check if alpha violate KKT condition def _check_obey_kkt(self, index): alphas = self.alphas tol = self._tol r = self._e(index) * self.tags[index] c = self._c return (r < -tol and alphas[index] < c) or (r > tol and alphas[index] > 0.0) # Get value calculated from kernel function def _k(self, i1, i2): # for test samples,use Kernel function if isinstance(i2, np.ndarray): return self.Kernel(self.samples[i1], i2) # for train samples,Kernel values have been saved in matrix else: return self._K_matrix[i1, i2] # Get sample's error def _e(self, index): """ Two cases: 1:Sample[index] is non-bound,Fetch error from list: _error 2:sample[index] is bound,Use predicted value deduct true value: g(xi) - yi """ # get from error data if self._is_unbound(index): return self._error[index] # get by g(xi) - yi else: gx = np.dot(self.alphas * self.tags, self._K_matrix[:, index]) + self._b yi = self.tags[index] return gx - yi # Calculate Kernel matrix of all possible i1,i2 ,saving time def _calculate_k_matrix(self): k_matrix = np.zeros([self.length, self.length]) for i in self._all_samples: for j in self._all_samples: k_matrix[i, j] = np.float64( self.Kernel(self.samples[i, :], self.samples[j, :]) ) return k_matrix # Predict test sample's tag def _predict(self, sample): k = self._k predicted_value = ( np.sum( [ self.alphas[i1] * self.tags[i1] * k(i1, sample) for i1 in self._all_samples ] ) + self._b ) return predicted_value # Choose alpha1 and alpha2 def _choose_alphas(self): locis = yield from self._choose_a1() if not locis: return return locis def _choose_a1(self): """ Choose first alpha ;steps: 1:First loop over all sample 2:Second loop over all non-bound samples till all non-bound samples does not voilate kkt condition. 3:Repeat this two process endlessly,till all samples does not voilate kkt condition samples after first loop. """ while True: all_not_obey = True # all sample print("scanning all sample!") for i1 in [i for i in self._all_samples if self._check_obey_kkt(i)]: all_not_obey = False yield from self._choose_a2(i1) # non-bound sample print("scanning non-bound sample!") while True: not_obey = True for i1 in [ i for i in self._all_samples if self._check_obey_kkt(i) and self._is_unbound(i) ]: not_obey = False yield from self._choose_a2(i1) if not_obey: print("all non-bound samples fit the KKT condition!") break if all_not_obey: print("all samples fit the KKT condition! Optimization done!") break return False def _choose_a2(self, i1): """ Choose the second alpha by using heuristic algorithm ;steps: 1: Choose alpha2 which gets the maximum step size (|E1 - E2|). 2: Start in a random point,loop over all non-bound samples till alpha1 and alpha2 are optimized. 3: Start in a random point,loop over all samples till alpha1 and alpha2 are optimized. """ self._unbound = [i for i in self._all_samples if self._is_unbound(i)] if len(self.unbound) > 0: tmp_error = self._error.copy().tolist() tmp_error_dict = { index: value for index, value in enumerate(tmp_error) if self._is_unbound(index) } if self._e(i1) >= 0: i2 = min(tmp_error_dict, key=lambda index: tmp_error_dict[index]) else: i2 = max(tmp_error_dict, key=lambda index: tmp_error_dict[index]) cmd = yield i1, i2 if cmd is None: return for i2 in np.roll(self.unbound, np.random.choice(self.length)): cmd = yield i1, i2 if cmd is None: return for i2 in np.roll(self._all_samples, np.random.choice(self.length)): cmd = yield i1, i2 if cmd is None: return # Get the new alpha2 and new alpha1 def _get_new_alpha(self, i1, i2, a1, a2, e1, e2, y1, y2): k = self._k if i1 == i2: return None, None # calculate L and H which bound the new alpha2 s = y1 * y2 if s == -1: l, h = max(0.0, a2 - a1), min(self._c, self._c + a2 - a1) else: l, h = max(0.0, a2 + a1 - self._c), min(self._c, a2 + a1) if l == h: # noqa: E741 return None, None # calculate eta k11 = k(i1, i1) k22 = k(i2, i2) k12 = k(i1, i2) # select the new alpha2 which could get the minimal objectives if (eta := k11 + k22 - 2.0 * k12) > 0.0: a2_new_unc = a2 + (y2 * (e1 - e2)) / eta # a2_new has a boundary if a2_new_unc >= h: a2_new = h elif a2_new_unc <= l: a2_new = l else: a2_new = a2_new_unc else: b = self._b l1 = a1 + s * (a2 - l) h1 = a1 + s * (a2 - h) # way 1 f1 = y1 * (e1 + b) - a1 * k(i1, i1) - s * a2 * k(i1, i2) f2 = y2 * (e2 + b) - a2 * k(i2, i2) - s * a1 * k(i1, i2) ol = ( l1 * f1 + l * f2 + 1 / 2 * l1**2 * k(i1, i1) + 1 / 2 * l**2 * k(i2, i2) + s * l * l1 * k(i1, i2) ) oh = ( h1 * f1 + h * f2 + 1 / 2 * h1**2 * k(i1, i1) + 1 / 2 * h**2 * k(i2, i2) + s * h * h1 * k(i1, i2) ) """ # way 2 Use objective function check which alpha2 new could get the minimal objectives """ if ol < (oh - self._eps): a2_new = l elif ol > oh + self._eps: a2_new = h else: a2_new = a2 # a1_new has a boundary too a1_new = a1 + s * (a2 - a2_new) if a1_new < 0: a2_new += s * a1_new a1_new = 0 if a1_new > self._c: a2_new += s * (a1_new - self._c) a1_new = self._c return a1_new, a2_new # Normalise data using min_max way def _norm(self, data): if self._init: self._min = np.min(data, axis=0) self._max = np.max(data, axis=0) self._init = False return (data - self._min) / (self._max - self._min) else: return (data - self._min) / (self._max - self._min) def _is_unbound(self, index): if 0.0 < self.alphas[index] < self._c: return True else: return False def _is_support(self, index): if self.alphas[index] > 0: return True else: return False @property def unbound(self): return self._unbound @property def support(self): return [i for i in range(self.length) if self._is_support(i)] @property def length(self): return self.samples.shape[0] class Kernel: def __init__(self, kernel, degree=1.0, coef0=0.0, gamma=1.0): self.degree = np.float64(degree) self.coef0 = np.float64(coef0) self.gamma = np.float64(gamma) self._kernel_name = kernel self._kernel = self._get_kernel(kernel_name=kernel) self._check() def _polynomial(self, v1, v2): return (self.gamma * np.inner(v1, v2) + self.coef0) ** self.degree def _linear(self, v1, v2): return np.inner(v1, v2) + self.coef0 def _rbf(self, v1, v2): return np.exp(-1 * (self.gamma * np.linalg.norm(v1 - v2) ** 2)) def _check(self): if self._kernel == self._rbf: if self.gamma < 0: raise ValueError("gamma value must greater than 0") def _get_kernel(self, kernel_name): maps = {"linear": self._linear, "poly": self._polynomial, "rbf": self._rbf} return maps[kernel_name] def __call__(self, v1, v2): return self._kernel(v1, v2) def __repr__(self): return self._kernel_name def count_time(func): def call_func(*args, **kwargs): import time start_time = time.time() func(*args, **kwargs) end_time = time.time() print(f"smo algorithm cost {end_time - start_time} seconds") return call_func @count_time def test_cancel_data(): print("Hello!\nStart test svm by smo algorithm!") # 0: download dataset and load into pandas' dataframe if not os.path.exists(r"cancel_data.csv"): request = urllib.request.Request( CANCER_DATASET_URL, headers={"User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"}, ) response = urllib.request.urlopen(request) content = response.read().decode("utf-8") with open(r"cancel_data.csv", "w") as f: f.write(content) data = pd.read_csv(r"cancel_data.csv", header=None) # 1: pre-processing data del data[data.columns.tolist()[0]] data = data.dropna(axis=0) data = data.replace({"M": np.float64(1), "B": np.float64(-1)}) samples = np.array(data)[:, :] # 2: dividing data into train_data data and test_data data train_data, test_data = samples[:328, :], samples[328:, :] test_tags, test_samples = test_data[:, 0], test_data[:, 1:] # 3: choose kernel function,and set initial alphas to zero(optional) mykernel = Kernel(kernel="rbf", degree=5, coef0=1, gamma=0.5) al = np.zeros(train_data.shape[0]) # 4: calculating best alphas using SMO algorithm and predict test_data samples mysvm = SmoSVM( train=train_data, kernel_func=mykernel, alpha_list=al, cost=0.4, b=0.0, tolerance=0.001, ) mysvm.fit() predict = mysvm.predict(test_samples) # 5: check accuracy score = 0 test_num = test_tags.shape[0] for i in range(test_tags.shape[0]): if test_tags[i] == predict[i]: score += 1 print(f"\nall: {test_num}\nright: {score}\nfalse: {test_num - score}") print(f"Rough Accuracy: {score / test_tags.shape[0]}") def test_demonstration(): # change stdout print("\nStart plot,please wait!!!") sys.stdout = open(os.devnull, "w") ax1 = plt.subplot2grid((2, 2), (0, 0)) ax2 = plt.subplot2grid((2, 2), (0, 1)) ax3 = plt.subplot2grid((2, 2), (1, 0)) ax4 = plt.subplot2grid((2, 2), (1, 1)) ax1.set_title("linear svm,cost:0.1") test_linear_kernel(ax1, cost=0.1) ax2.set_title("linear svm,cost:500") test_linear_kernel(ax2, cost=500) ax3.set_title("rbf kernel svm,cost:0.1") test_rbf_kernel(ax3, cost=0.1) ax4.set_title("rbf kernel svm,cost:500") test_rbf_kernel(ax4, cost=500) sys.stdout = sys.__stdout__ print("Plot done!!!") def test_linear_kernel(ax, cost): train_x, train_y = make_blobs( n_samples=500, centers=2, n_features=2, random_state=1 ) train_y[train_y == 0] = -1 scaler = StandardScaler() train_x_scaled = scaler.fit_transform(train_x, train_y) train_data = np.hstack((train_y.reshape(500, 1), train_x_scaled)) mykernel = Kernel(kernel="linear", degree=5, coef0=1, gamma=0.5) mysvm = SmoSVM( train=train_data, kernel_func=mykernel, cost=cost, tolerance=0.001, auto_norm=False, ) mysvm.fit() plot_partition_boundary(mysvm, train_data, ax=ax) def test_rbf_kernel(ax, cost): train_x, train_y = make_circles( n_samples=500, noise=0.1, factor=0.1, random_state=1 ) train_y[train_y == 0] = -1 scaler = StandardScaler() train_x_scaled = scaler.fit_transform(train_x, train_y) train_data = np.hstack((train_y.reshape(500, 1), train_x_scaled)) mykernel = Kernel(kernel="rbf", degree=5, coef0=1, gamma=0.5) mysvm = SmoSVM( train=train_data, kernel_func=mykernel, cost=cost, tolerance=0.001, auto_norm=False, ) mysvm.fit() plot_partition_boundary(mysvm, train_data, ax=ax) def plot_partition_boundary( model, train_data, ax, resolution=100, colors=("b", "k", "r") ): """ We can not get the optimum w of our kernel svm model which is different from linear svm. For this reason, we generate randomly distributed points with high desity and prediced values of these points are calculated by using our tained model. Then we could use this prediced values to draw contour map. And this contour map can represent svm's partition boundary. """ train_data_x = train_data[:, 1] train_data_y = train_data[:, 2] train_data_tags = train_data[:, 0] xrange = np.linspace(train_data_x.min(), train_data_x.max(), resolution) yrange = np.linspace(train_data_y.min(), train_data_y.max(), resolution) test_samples = np.array([(x, y) for x in xrange for y in yrange]).reshape( resolution * resolution, 2 ) test_tags = model.predict(test_samples, classify=False) grid = test_tags.reshape((len(xrange), len(yrange))) # Plot contour map which represents the partition boundary ax.contour( xrange, yrange, np.mat(grid).T, levels=(-1, 0, 1), linestyles=("--", "-", "--"), linewidths=(1, 1, 1), colors=colors, ) # Plot all train samples ax.scatter( train_data_x, train_data_y, c=train_data_tags, cmap=plt.cm.Dark2, lw=0, alpha=0.5, ) # Plot support vectors support = model.support ax.scatter( train_data_x[support], train_data_y[support], c=train_data_tags[support], cmap=plt.cm.Dark2, ) if __name__ == "__main__": test_cancel_data() test_demonstration() plt.show()
""" Implementation of sequential minimal optimization (SMO) for support vector machines (SVM). Sequential minimal optimization (SMO) is an algorithm for solving the quadratic programming (QP) problem that arises during the training of support vector machines. It was invented by John Platt in 1998. Input: 0: type: numpy.ndarray. 1: first column of ndarray must be tags of samples, must be 1 or -1. 2: rows of ndarray represent samples. Usage: Command: python3 sequential_minimum_optimization.py Code: from sequential_minimum_optimization import SmoSVM, Kernel kernel = Kernel(kernel='poly', degree=3., coef0=1., gamma=0.5) init_alphas = np.zeros(train.shape[0]) SVM = SmoSVM(train=train, alpha_list=init_alphas, kernel_func=kernel, cost=0.4, b=0.0, tolerance=0.001) SVM.fit() predict = SVM.predict(test_samples) Reference: https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/smo-book.pdf https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-98-14.pdf """ import os import sys import urllib.request import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.datasets import make_blobs, make_circles from sklearn.preprocessing import StandardScaler CANCER_DATASET_URL = ( "https://archive.ics.uci.edu/ml/machine-learning-databases/" "breast-cancer-wisconsin/wdbc.data" ) class SmoSVM: def __init__( self, train, kernel_func, alpha_list=None, cost=0.4, b=0.0, tolerance=0.001, auto_norm=True, ): self._init = True self._auto_norm = auto_norm self._c = np.float64(cost) self._b = np.float64(b) self._tol = np.float64(tolerance) if tolerance > 0.0001 else np.float64(0.001) self.tags = train[:, 0] self.samples = self._norm(train[:, 1:]) if self._auto_norm else train[:, 1:] self.alphas = alpha_list if alpha_list is not None else np.zeros(train.shape[0]) self.Kernel = kernel_func self._eps = 0.001 self._all_samples = list(range(self.length)) self._K_matrix = self._calculate_k_matrix() self._error = np.zeros(self.length) self._unbound = [] self.choose_alpha = self._choose_alphas() # Calculate alphas using SMO algorithm def fit(self): k = self._k state = None while True: # 1: Find alpha1, alpha2 try: i1, i2 = self.choose_alpha.send(state) state = None except StopIteration: print("Optimization done!\nEvery sample satisfy the KKT condition!") break # 2: calculate new alpha2 and new alpha1 y1, y2 = self.tags[i1], self.tags[i2] a1, a2 = self.alphas[i1].copy(), self.alphas[i2].copy() e1, e2 = self._e(i1), self._e(i2) args = (i1, i2, a1, a2, e1, e2, y1, y2) a1_new, a2_new = self._get_new_alpha(*args) if not a1_new and not a2_new: state = False continue self.alphas[i1], self.alphas[i2] = a1_new, a2_new # 3: update threshold(b) b1_new = np.float64( -e1 - y1 * k(i1, i1) * (a1_new - a1) - y2 * k(i2, i1) * (a2_new - a2) + self._b ) b2_new = np.float64( -e2 - y2 * k(i2, i2) * (a2_new - a2) - y1 * k(i1, i2) * (a1_new - a1) + self._b ) if 0.0 < a1_new < self._c: b = b1_new if 0.0 < a2_new < self._c: b = b2_new if not (np.float64(0) < a2_new < self._c) and not ( np.float64(0) < a1_new < self._c ): b = (b1_new + b2_new) / 2.0 b_old = self._b self._b = b # 4: update error value,here we only calculate those non-bound samples' # error self._unbound = [i for i in self._all_samples if self._is_unbound(i)] for s in self.unbound: if s == i1 or s == i2: continue self._error[s] += ( y1 * (a1_new - a1) * k(i1, s) + y2 * (a2_new - a2) * k(i2, s) + (self._b - b_old) ) # if i1 or i2 is non-bound,update there error value to zero if self._is_unbound(i1): self._error[i1] = 0 if self._is_unbound(i2): self._error[i2] = 0 # Predict test samples def predict(self, test_samples, classify=True): if test_samples.shape[1] > self.samples.shape[1]: raise ValueError( "Test samples' feature length does not equal to that of train samples" ) if self._auto_norm: test_samples = self._norm(test_samples) results = [] for test_sample in test_samples: result = self._predict(test_sample) if classify: results.append(1 if result > 0 else -1) else: results.append(result) return np.array(results) # Check if alpha violate KKT condition def _check_obey_kkt(self, index): alphas = self.alphas tol = self._tol r = self._e(index) * self.tags[index] c = self._c return (r < -tol and alphas[index] < c) or (r > tol and alphas[index] > 0.0) # Get value calculated from kernel function def _k(self, i1, i2): # for test samples,use Kernel function if isinstance(i2, np.ndarray): return self.Kernel(self.samples[i1], i2) # for train samples,Kernel values have been saved in matrix else: return self._K_matrix[i1, i2] # Get sample's error def _e(self, index): """ Two cases: 1:Sample[index] is non-bound,Fetch error from list: _error 2:sample[index] is bound,Use predicted value deduct true value: g(xi) - yi """ # get from error data if self._is_unbound(index): return self._error[index] # get by g(xi) - yi else: gx = np.dot(self.alphas * self.tags, self._K_matrix[:, index]) + self._b yi = self.tags[index] return gx - yi # Calculate Kernel matrix of all possible i1,i2 ,saving time def _calculate_k_matrix(self): k_matrix = np.zeros([self.length, self.length]) for i in self._all_samples: for j in self._all_samples: k_matrix[i, j] = np.float64( self.Kernel(self.samples[i, :], self.samples[j, :]) ) return k_matrix # Predict test sample's tag def _predict(self, sample): k = self._k predicted_value = ( np.sum( [ self.alphas[i1] * self.tags[i1] * k(i1, sample) for i1 in self._all_samples ] ) + self._b ) return predicted_value # Choose alpha1 and alpha2 def _choose_alphas(self): locis = yield from self._choose_a1() if not locis: return return locis def _choose_a1(self): """ Choose first alpha ;steps: 1:First loop over all sample 2:Second loop over all non-bound samples till all non-bound samples does not voilate kkt condition. 3:Repeat this two process endlessly,till all samples does not voilate kkt condition samples after first loop. """ while True: all_not_obey = True # all sample print("scanning all sample!") for i1 in [i for i in self._all_samples if self._check_obey_kkt(i)]: all_not_obey = False yield from self._choose_a2(i1) # non-bound sample print("scanning non-bound sample!") while True: not_obey = True for i1 in [ i for i in self._all_samples if self._check_obey_kkt(i) and self._is_unbound(i) ]: not_obey = False yield from self._choose_a2(i1) if not_obey: print("all non-bound samples fit the KKT condition!") break if all_not_obey: print("all samples fit the KKT condition! Optimization done!") break return False def _choose_a2(self, i1): """ Choose the second alpha by using heuristic algorithm ;steps: 1: Choose alpha2 which gets the maximum step size (|E1 - E2|). 2: Start in a random point,loop over all non-bound samples till alpha1 and alpha2 are optimized. 3: Start in a random point,loop over all samples till alpha1 and alpha2 are optimized. """ self._unbound = [i for i in self._all_samples if self._is_unbound(i)] if len(self.unbound) > 0: tmp_error = self._error.copy().tolist() tmp_error_dict = { index: value for index, value in enumerate(tmp_error) if self._is_unbound(index) } if self._e(i1) >= 0: i2 = min(tmp_error_dict, key=lambda index: tmp_error_dict[index]) else: i2 = max(tmp_error_dict, key=lambda index: tmp_error_dict[index]) cmd = yield i1, i2 if cmd is None: return for i2 in np.roll(self.unbound, np.random.choice(self.length)): cmd = yield i1, i2 if cmd is None: return for i2 in np.roll(self._all_samples, np.random.choice(self.length)): cmd = yield i1, i2 if cmd is None: return # Get the new alpha2 and new alpha1 def _get_new_alpha(self, i1, i2, a1, a2, e1, e2, y1, y2): k = self._k if i1 == i2: return None, None # calculate L and H which bound the new alpha2 s = y1 * y2 if s == -1: l, h = max(0.0, a2 - a1), min(self._c, self._c + a2 - a1) else: l, h = max(0.0, a2 + a1 - self._c), min(self._c, a2 + a1) if l == h: # noqa: E741 return None, None # calculate eta k11 = k(i1, i1) k22 = k(i2, i2) k12 = k(i1, i2) # select the new alpha2 which could get the minimal objectives if (eta := k11 + k22 - 2.0 * k12) > 0.0: a2_new_unc = a2 + (y2 * (e1 - e2)) / eta # a2_new has a boundary if a2_new_unc >= h: a2_new = h elif a2_new_unc <= l: a2_new = l else: a2_new = a2_new_unc else: b = self._b l1 = a1 + s * (a2 - l) h1 = a1 + s * (a2 - h) # way 1 f1 = y1 * (e1 + b) - a1 * k(i1, i1) - s * a2 * k(i1, i2) f2 = y2 * (e2 + b) - a2 * k(i2, i2) - s * a1 * k(i1, i2) ol = ( l1 * f1 + l * f2 + 1 / 2 * l1**2 * k(i1, i1) + 1 / 2 * l**2 * k(i2, i2) + s * l * l1 * k(i1, i2) ) oh = ( h1 * f1 + h * f2 + 1 / 2 * h1**2 * k(i1, i1) + 1 / 2 * h**2 * k(i2, i2) + s * h * h1 * k(i1, i2) ) """ # way 2 Use objective function check which alpha2 new could get the minimal objectives """ if ol < (oh - self._eps): a2_new = l elif ol > oh + self._eps: a2_new = h else: a2_new = a2 # a1_new has a boundary too a1_new = a1 + s * (a2 - a2_new) if a1_new < 0: a2_new += s * a1_new a1_new = 0 if a1_new > self._c: a2_new += s * (a1_new - self._c) a1_new = self._c return a1_new, a2_new # Normalise data using min_max way def _norm(self, data): if self._init: self._min = np.min(data, axis=0) self._max = np.max(data, axis=0) self._init = False return (data - self._min) / (self._max - self._min) else: return (data - self._min) / (self._max - self._min) def _is_unbound(self, index): if 0.0 < self.alphas[index] < self._c: return True else: return False def _is_support(self, index): if self.alphas[index] > 0: return True else: return False @property def unbound(self): return self._unbound @property def support(self): return [i for i in range(self.length) if self._is_support(i)] @property def length(self): return self.samples.shape[0] class Kernel: def __init__(self, kernel, degree=1.0, coef0=0.0, gamma=1.0): self.degree = np.float64(degree) self.coef0 = np.float64(coef0) self.gamma = np.float64(gamma) self._kernel_name = kernel self._kernel = self._get_kernel(kernel_name=kernel) self._check() def _polynomial(self, v1, v2): return (self.gamma * np.inner(v1, v2) + self.coef0) ** self.degree def _linear(self, v1, v2): return np.inner(v1, v2) + self.coef0 def _rbf(self, v1, v2): return np.exp(-1 * (self.gamma * np.linalg.norm(v1 - v2) ** 2)) def _check(self): if self._kernel == self._rbf: if self.gamma < 0: raise ValueError("gamma value must greater than 0") def _get_kernel(self, kernel_name): maps = {"linear": self._linear, "poly": self._polynomial, "rbf": self._rbf} return maps[kernel_name] def __call__(self, v1, v2): return self._kernel(v1, v2) def __repr__(self): return self._kernel_name def count_time(func): def call_func(*args, **kwargs): import time start_time = time.time() func(*args, **kwargs) end_time = time.time() print(f"smo algorithm cost {end_time - start_time} seconds") return call_func @count_time def test_cancel_data(): print("Hello!\nStart test svm by smo algorithm!") # 0: download dataset and load into pandas' dataframe if not os.path.exists(r"cancel_data.csv"): request = urllib.request.Request( CANCER_DATASET_URL, headers={"User-Agent": "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)"}, ) response = urllib.request.urlopen(request) content = response.read().decode("utf-8") with open(r"cancel_data.csv", "w") as f: f.write(content) data = pd.read_csv(r"cancel_data.csv", header=None) # 1: pre-processing data del data[data.columns.tolist()[0]] data = data.dropna(axis=0) data = data.replace({"M": np.float64(1), "B": np.float64(-1)}) samples = np.array(data)[:, :] # 2: dividing data into train_data data and test_data data train_data, test_data = samples[:328, :], samples[328:, :] test_tags, test_samples = test_data[:, 0], test_data[:, 1:] # 3: choose kernel function,and set initial alphas to zero(optional) mykernel = Kernel(kernel="rbf", degree=5, coef0=1, gamma=0.5) al = np.zeros(train_data.shape[0]) # 4: calculating best alphas using SMO algorithm and predict test_data samples mysvm = SmoSVM( train=train_data, kernel_func=mykernel, alpha_list=al, cost=0.4, b=0.0, tolerance=0.001, ) mysvm.fit() predict = mysvm.predict(test_samples) # 5: check accuracy score = 0 test_num = test_tags.shape[0] for i in range(test_tags.shape[0]): if test_tags[i] == predict[i]: score += 1 print(f"\nall: {test_num}\nright: {score}\nfalse: {test_num - score}") print(f"Rough Accuracy: {score / test_tags.shape[0]}") def test_demonstration(): # change stdout print("\nStart plot,please wait!!!") sys.stdout = open(os.devnull, "w") ax1 = plt.subplot2grid((2, 2), (0, 0)) ax2 = plt.subplot2grid((2, 2), (0, 1)) ax3 = plt.subplot2grid((2, 2), (1, 0)) ax4 = plt.subplot2grid((2, 2), (1, 1)) ax1.set_title("linear svm,cost:0.1") test_linear_kernel(ax1, cost=0.1) ax2.set_title("linear svm,cost:500") test_linear_kernel(ax2, cost=500) ax3.set_title("rbf kernel svm,cost:0.1") test_rbf_kernel(ax3, cost=0.1) ax4.set_title("rbf kernel svm,cost:500") test_rbf_kernel(ax4, cost=500) sys.stdout = sys.__stdout__ print("Plot done!!!") def test_linear_kernel(ax, cost): train_x, train_y = make_blobs( n_samples=500, centers=2, n_features=2, random_state=1 ) train_y[train_y == 0] = -1 scaler = StandardScaler() train_x_scaled = scaler.fit_transform(train_x, train_y) train_data = np.hstack((train_y.reshape(500, 1), train_x_scaled)) mykernel = Kernel(kernel="linear", degree=5, coef0=1, gamma=0.5) mysvm = SmoSVM( train=train_data, kernel_func=mykernel, cost=cost, tolerance=0.001, auto_norm=False, ) mysvm.fit() plot_partition_boundary(mysvm, train_data, ax=ax) def test_rbf_kernel(ax, cost): train_x, train_y = make_circles( n_samples=500, noise=0.1, factor=0.1, random_state=1 ) train_y[train_y == 0] = -1 scaler = StandardScaler() train_x_scaled = scaler.fit_transform(train_x, train_y) train_data = np.hstack((train_y.reshape(500, 1), train_x_scaled)) mykernel = Kernel(kernel="rbf", degree=5, coef0=1, gamma=0.5) mysvm = SmoSVM( train=train_data, kernel_func=mykernel, cost=cost, tolerance=0.001, auto_norm=False, ) mysvm.fit() plot_partition_boundary(mysvm, train_data, ax=ax) def plot_partition_boundary( model, train_data, ax, resolution=100, colors=("b", "k", "r") ): """ We can not get the optimum w of our kernel svm model which is different from linear svm. For this reason, we generate randomly distributed points with high desity and prediced values of these points are calculated by using our tained model. Then we could use this prediced values to draw contour map. And this contour map can represent svm's partition boundary. """ train_data_x = train_data[:, 1] train_data_y = train_data[:, 2] train_data_tags = train_data[:, 0] xrange = np.linspace(train_data_x.min(), train_data_x.max(), resolution) yrange = np.linspace(train_data_y.min(), train_data_y.max(), resolution) test_samples = np.array([(x, y) for x in xrange for y in yrange]).reshape( resolution * resolution, 2 ) test_tags = model.predict(test_samples, classify=False) grid = test_tags.reshape((len(xrange), len(yrange))) # Plot contour map which represents the partition boundary ax.contour( xrange, yrange, np.mat(grid).T, levels=(-1, 0, 1), linestyles=("--", "-", "--"), linewidths=(1, 1, 1), colors=colors, ) # Plot all train samples ax.scatter( train_data_x, train_data_y, c=train_data_tags, cmap=plt.cm.Dark2, lw=0, alpha=0.5, ) # Plot support vectors support = model.support ax.scatter( train_data_x[support], train_data_y[support], c=train_data_tags[support], cmap=plt.cm.Dark2, ) if __name__ == "__main__": test_cancel_data() test_demonstration() plt.show()
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Prize Strings Problem 191 A particular school offers cash rewards to children with good attendance and punctuality. If they are absent for three consecutive days or late on more than one occasion then they forfeit their prize. During an n-day period a trinary string is formed for each child consisting of L's (late), O's (on time), and A's (absent). Although there are eighty-one trinary strings for a 4-day period that can be formed, exactly forty-three strings would lead to a prize: OOOO OOOA OOOL OOAO OOAA OOAL OOLO OOLA OAOO OAOA OAOL OAAO OAAL OALO OALA OLOO OLOA OLAO OLAA AOOO AOOA AOOL AOAO AOAA AOAL AOLO AOLA AAOO AAOA AAOL AALO AALA ALOO ALOA ALAO ALAA LOOO LOOA LOAO LOAA LAOO LAOA LAAO How many "prize" strings exist over a 30-day period? References: - The original Project Euler project page: https://projecteuler.net/problem=191 """ cache: dict[tuple[int, int, int], int] = {} def _calculate(days: int, absent: int, late: int) -> int: """ A small helper function for the recursion, mainly to have a clean interface for the solution() function below. It should get called with the number of days (corresponding to the desired length of the 'prize strings'), and the initial values for the number of consecutive absent days and number of total late days. >>> _calculate(days=4, absent=0, late=0) 43 >>> _calculate(days=30, absent=2, late=0) 0 >>> _calculate(days=30, absent=1, late=0) 98950096 """ # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on key = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one state_late = _calculate(days - 1, absent, late + 1) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 state_absent = _calculate(days - 1, absent + 1, 0) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter state_ontime = _calculate(days - 1, absent, 0) prizestrings = state_late + state_absent + state_ontime cache[key] = prizestrings return prizestrings def solution(days: int = 30) -> int: """ Returns the number of possible prize strings for a particular number of days, using a simple recursive function with caching to speed it up. >>> solution() 1918080160 >>> solution(4) 43 """ return _calculate(days, absent=0, late=0) if __name__ == "__main__": print(solution())
""" Prize Strings Problem 191 A particular school offers cash rewards to children with good attendance and punctuality. If they are absent for three consecutive days or late on more than one occasion then they forfeit their prize. During an n-day period a trinary string is formed for each child consisting of L's (late), O's (on time), and A's (absent). Although there are eighty-one trinary strings for a 4-day period that can be formed, exactly forty-three strings would lead to a prize: OOOO OOOA OOOL OOAO OOAA OOAL OOLO OOLA OAOO OAOA OAOL OAAO OAAL OALO OALA OLOO OLOA OLAO OLAA AOOO AOOA AOOL AOAO AOAA AOAL AOLO AOLA AAOO AAOA AAOL AALO AALA ALOO ALOA ALAO ALAA LOOO LOOA LOAO LOAA LAOO LAOA LAAO How many "prize" strings exist over a 30-day period? References: - The original Project Euler project page: https://projecteuler.net/problem=191 """ cache: dict[tuple[int, int, int], int] = {} def _calculate(days: int, absent: int, late: int) -> int: """ A small helper function for the recursion, mainly to have a clean interface for the solution() function below. It should get called with the number of days (corresponding to the desired length of the 'prize strings'), and the initial values for the number of consecutive absent days and number of total late days. >>> _calculate(days=4, absent=0, late=0) 43 >>> _calculate(days=30, absent=2, late=0) 0 >>> _calculate(days=30, absent=1, late=0) 98950096 """ # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on key = (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one state_late = _calculate(days - 1, absent, late + 1) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 state_absent = _calculate(days - 1, absent + 1, 0) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter state_ontime = _calculate(days - 1, absent, 0) prizestrings = state_late + state_absent + state_ontime cache[key] = prizestrings return prizestrings def solution(days: int = 30) -> int: """ Returns the number of possible prize strings for a particular number of days, using a simple recursive function with caching to speed it up. >>> solution() 1918080160 >>> solution(4) 43 """ return _calculate(days, absent=0, late=0) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 """ Double hashing is a collision resolving technique in Open Addressed Hash tables. Double hashing uses the idea of applying a second hash function to key when a collision occurs. The advantage of Double hashing is that it is one of the best form of probing, producing a uniform distribution of records throughout a hash table. This technique does not yield any clusters. It is one of effective method for resolving collisions. Double hashing can be done using: (hash1(key) + i * hash2(key)) % TABLE_SIZE Where hash1() and hash2() are hash functions and TABLE_SIZE is size of hash table. Reference: https://en.wikipedia.org/wiki/Double_hashing """ from .hash_table import HashTable from .number_theory.prime_numbers import is_prime, next_prime class DoubleHash(HashTable): """ Hash Table example with open addressing and Double Hash """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __hash_function_2(self, value, data): next_prime_gt = ( next_prime(value % self.size_table) if not is_prime(value % self.size_table) else value % self.size_table ) # gt = bigger than return next_prime_gt - (data % next_prime_gt) def __hash_double_function(self, key, data, increment): return (increment * self.__hash_function_2(key, data)) % self.size_table def _collision_resolution(self, key, data=None): i = 1 new_key = self.hash_function(data) while self.values[new_key] is not None and self.values[new_key] != key: new_key = ( self.__hash_double_function(key, data, i) if self.balanced_factor() >= self.lim_charge else None ) if new_key is None: break else: i += 1 return new_key
#!/usr/bin/env python3 """ Double hashing is a collision resolving technique in Open Addressed Hash tables. Double hashing uses the idea of applying a second hash function to key when a collision occurs. The advantage of Double hashing is that it is one of the best form of probing, producing a uniform distribution of records throughout a hash table. This technique does not yield any clusters. It is one of effective method for resolving collisions. Double hashing can be done using: (hash1(key) + i * hash2(key)) % TABLE_SIZE Where hash1() and hash2() are hash functions and TABLE_SIZE is size of hash table. Reference: https://en.wikipedia.org/wiki/Double_hashing """ from .hash_table import HashTable from .number_theory.prime_numbers import is_prime, next_prime class DoubleHash(HashTable): """ Hash Table example with open addressing and Double Hash """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __hash_function_2(self, value, data): next_prime_gt = ( next_prime(value % self.size_table) if not is_prime(value % self.size_table) else value % self.size_table ) # gt = bigger than return next_prime_gt - (data % next_prime_gt) def __hash_double_function(self, key, data, increment): return (increment * self.__hash_function_2(key, data)) % self.size_table def _collision_resolution(self, key, data=None): i = 1 new_key = self.hash_function(data) while self.values[new_key] is not None and self.values[new_key] != key: new_key = ( self.__hash_double_function(key, data, i) if self.balanced_factor() >= self.lim_charge else None ) if new_key is None: break else: i += 1 return new_key
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# https://github.com/rupansh/QuantumComputing/blob/master/rippleadd.py # https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder # https://en.wikipedia.org/wiki/Controlled_NOT_gate import qiskit from qiskit.providers import Backend def store_two_classics(val1: int, val2: int) -> tuple[qiskit.QuantumCircuit, str, str]: """ Generates a Quantum Circuit which stores two classical integers Returns the circuit and binary representation of the integers """ x, y = bin(val1)[2:], bin(val2)[2:] # Remove leading '0b' # Ensure that both strings are of the same length if len(x) > len(y): y = y.zfill(len(x)) else: x = x.zfill(len(y)) # We need (3 * number of bits in the larger number)+1 qBits # The second parameter is the number of classical registers, to measure the result circuit = qiskit.QuantumCircuit((len(x) * 3) + 1, len(x) + 1) # We are essentially "not-ing" the bits that are 1 # Reversed because it's easier to perform ops on more significant bits for i in range(len(x)): if x[::-1][i] == "1": circuit.x(i) for j in range(len(y)): if y[::-1][j] == "1": circuit.x(len(x) + j) return circuit, x, y def full_adder( circuit: qiskit.QuantumCircuit, input1_loc: int, input2_loc: int, carry_in: int, carry_out: int, ): """ Quantum Equivalent of a Full Adder Circuit CX/CCX is like 2-way/3-way XOR """ circuit.ccx(input1_loc, input2_loc, carry_out) circuit.cx(input1_loc, input2_loc) circuit.ccx(input2_loc, carry_in, carry_out) circuit.cx(input2_loc, carry_in) circuit.cx(input1_loc, input2_loc) # The default value for **backend** is the result of a function call which is not # normally recommended and causes flake8-bugbear to raise a B008 error. However, # in this case, this is acceptable because `Aer.get_backend()` is called when the # function is defined and that same backend is then reused for all function calls. def ripple_adder( val1: int, val2: int, backend: Backend = qiskit.Aer.get_backend("aer_simulator"), # noqa: B008 ) -> int: """ Quantum Equivalent of a Ripple Adder Circuit Uses qasm_simulator backend by default Currently only adds 'emulated' Classical Bits but nothing prevents us from doing this with hadamard'd bits :) Only supports adding positive integers >>> ripple_adder(3, 4) 7 >>> ripple_adder(10, 4) 14 >>> ripple_adder(-1, 10) Traceback (most recent call last): ... ValueError: Both Integers must be positive! """ if val1 < 0 or val2 < 0: raise ValueError("Both Integers must be positive!") # Store the Integers circuit, x, y = store_two_classics(val1, val2) """ We are essentially using each bit of x & y respectively as full_adder's input the carry_input is used from the previous circuit (for circuit num > 1) the carry_out is just below carry_input because it will be essentially the carry_input for the next full_adder """ for i in range(len(x)): full_adder(circuit, i, len(x) + i, len(x) + len(y) + i, len(x) + len(y) + i + 1) circuit.barrier() # Optional, just for aesthetics # Measure the resultant qBits for i in range(len(x) + 1): circuit.measure([(len(x) * 2) + i], [i]) res = qiskit.execute(circuit, backend, shots=1).result() # The result is in binary. Convert it back to int return int(list(res.get_counts())[0], 2) if __name__ == "__main__": import doctest doctest.testmod()
# https://github.com/rupansh/QuantumComputing/blob/master/rippleadd.py # https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder # https://en.wikipedia.org/wiki/Controlled_NOT_gate import qiskit from qiskit.providers import Backend def store_two_classics(val1: int, val2: int) -> tuple[qiskit.QuantumCircuit, str, str]: """ Generates a Quantum Circuit which stores two classical integers Returns the circuit and binary representation of the integers """ x, y = bin(val1)[2:], bin(val2)[2:] # Remove leading '0b' # Ensure that both strings are of the same length if len(x) > len(y): y = y.zfill(len(x)) else: x = x.zfill(len(y)) # We need (3 * number of bits in the larger number)+1 qBits # The second parameter is the number of classical registers, to measure the result circuit = qiskit.QuantumCircuit((len(x) * 3) + 1, len(x) + 1) # We are essentially "not-ing" the bits that are 1 # Reversed because it's easier to perform ops on more significant bits for i in range(len(x)): if x[::-1][i] == "1": circuit.x(i) for j in range(len(y)): if y[::-1][j] == "1": circuit.x(len(x) + j) return circuit, x, y def full_adder( circuit: qiskit.QuantumCircuit, input1_loc: int, input2_loc: int, carry_in: int, carry_out: int, ): """ Quantum Equivalent of a Full Adder Circuit CX/CCX is like 2-way/3-way XOR """ circuit.ccx(input1_loc, input2_loc, carry_out) circuit.cx(input1_loc, input2_loc) circuit.ccx(input2_loc, carry_in, carry_out) circuit.cx(input2_loc, carry_in) circuit.cx(input1_loc, input2_loc) # The default value for **backend** is the result of a function call which is not # normally recommended and causes flake8-bugbear to raise a B008 error. However, # in this case, this is acceptable because `Aer.get_backend()` is called when the # function is defined and that same backend is then reused for all function calls. def ripple_adder( val1: int, val2: int, backend: Backend = qiskit.Aer.get_backend("aer_simulator"), # noqa: B008 ) -> int: """ Quantum Equivalent of a Ripple Adder Circuit Uses qasm_simulator backend by default Currently only adds 'emulated' Classical Bits but nothing prevents us from doing this with hadamard'd bits :) Only supports adding positive integers >>> ripple_adder(3, 4) 7 >>> ripple_adder(10, 4) 14 >>> ripple_adder(-1, 10) Traceback (most recent call last): ... ValueError: Both Integers must be positive! """ if val1 < 0 or val2 < 0: raise ValueError("Both Integers must be positive!") # Store the Integers circuit, x, y = store_two_classics(val1, val2) """ We are essentially using each bit of x & y respectively as full_adder's input the carry_input is used from the previous circuit (for circuit num > 1) the carry_out is just below carry_input because it will be essentially the carry_input for the next full_adder """ for i in range(len(x)): full_adder(circuit, i, len(x) + i, len(x) + len(y) + i, len(x) + len(y) + i + 1) circuit.barrier() # Optional, just for aesthetics # Measure the resultant qBits for i in range(len(x) + 1): circuit.measure([(len(x) * 2) + i], [i]) res = qiskit.execute(circuit, backend, shots=1).result() # The result is in binary. Convert it back to int return int(list(res.get_counts())[0], 2) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" In mathematics, the Lucas–Lehmer test (LLT) is a primality test for Mersenne numbers. https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test A Mersenne number is a number that is one less than a power of two. That is M_p = 2^p - 1 https://en.wikipedia.org/wiki/Mersenne_prime The Lucas–Lehmer test is the primality test used by the Great Internet Mersenne Prime Search (GIMPS) to locate large primes. """ # Primality test 2^p - 1 # Return true if 2^p - 1 is prime def lucas_lehmer_test(p: int) -> bool: """ >>> lucas_lehmer_test(p=7) True >>> lucas_lehmer_test(p=11) False # M_11 = 2^11 - 1 = 2047 = 23 * 89 """ if p < 2: raise ValueError("p should not be less than 2!") elif p == 2: return True s = 4 m = (1 << p) - 1 for _ in range(p - 2): s = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
""" In mathematics, the Lucas–Lehmer test (LLT) is a primality test for Mersenne numbers. https://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test A Mersenne number is a number that is one less than a power of two. That is M_p = 2^p - 1 https://en.wikipedia.org/wiki/Mersenne_prime The Lucas–Lehmer test is the primality test used by the Great Internet Mersenne Prime Search (GIMPS) to locate large primes. """ # Primality test 2^p - 1 # Return true if 2^p - 1 is prime def lucas_lehmer_test(p: int) -> bool: """ >>> lucas_lehmer_test(p=7) True >>> lucas_lehmer_test(p=11) False # M_11 = 2^11 - 1 = 2047 = 23 * 89 """ if p < 2: raise ValueError("p should not be less than 2!") elif p == 2: return True s = 4 m = (1 << p) - 1 for _ in range(p - 2): s = ((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(11))
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 16: https://projecteuler.net/problem=16 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ def solution(power: int = 1000) -> int: """Returns the sum of the digits of the number 2^power. >>> solution(1000) 1366 >>> solution(50) 76 >>> solution(20) 31 >>> solution(15) 26 """ n = 2**power r = 0 while n: r, n = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
""" Problem 16: https://projecteuler.net/problem=16 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ def solution(power: int = 1000) -> int: """Returns the sum of the digits of the number 2^power. >>> solution(1000) 1366 >>> solution(50) 76 >>> solution(20) 31 >>> solution(15) 26 """ n = 2**power r = 0 while n: r, n = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/python # Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries """ Implementing logistic regression for classification problem Helpful resources: Coursera ML course https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac """ import numpy as np from matplotlib import pyplot as plt from sklearn import datasets # get_ipython().run_line_magic('matplotlib', 'inline') # In[67]: # sigmoid function or logistic function is used as a hypothesis function in # classification problems def sigmoid_function(z): return 1 / (1 + np.exp(-z)) def cost_function(h, y): return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean() def log_likelihood(x, y, weights): scores = np.dot(x, weights) return np.sum(y * scores - np.log(1 + np.exp(scores))) # here alpha is the learning rate, X is the feature matrix,y is the target matrix def logistic_reg(alpha, x, y, max_iterations=70000): theta = np.zeros(x.shape[1]) for iterations in range(max_iterations): z = np.dot(x, theta) h = sigmoid_function(z) gradient = np.dot(x.T, h - y) / y.size theta = theta - alpha * gradient # updating the weights z = np.dot(x, theta) h = sigmoid_function(z) j = cost_function(h, y) if iterations % 100 == 0: print(f"loss: {j} \t") # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": iris = datasets.load_iris() x = iris.data[:, :2] y = (iris.target != 0) * 1 alpha = 0.1 theta = logistic_reg(alpha, x, y, max_iterations=70000) print("theta: ", theta) # printing the theta i.e our weights vector def predict_prob(x): return sigmoid_function( np.dot(x, theta) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 6)) plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color="b", label="0") plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color="r", label="1") (x1_min, x1_max) = (x[:, 0].min(), x[:, 0].max()) (x2_min, x2_max) = (x[:, 1].min(), x[:, 1].max()) (xx1, xx2) = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max)) grid = np.c_[xx1.ravel(), xx2.ravel()] probs = predict_prob(grid).reshape(xx1.shape) plt.contour(xx1, xx2, probs, [0.5], linewidths=1, colors="black") plt.legend() plt.show()
#!/usr/bin/python # Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries """ Implementing logistic regression for classification problem Helpful resources: Coursera ML course https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac """ import numpy as np from matplotlib import pyplot as plt from sklearn import datasets # get_ipython().run_line_magic('matplotlib', 'inline') # In[67]: # sigmoid function or logistic function is used as a hypothesis function in # classification problems def sigmoid_function(z): return 1 / (1 + np.exp(-z)) def cost_function(h, y): return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean() def log_likelihood(x, y, weights): scores = np.dot(x, weights) return np.sum(y * scores - np.log(1 + np.exp(scores))) # here alpha is the learning rate, X is the feature matrix,y is the target matrix def logistic_reg(alpha, x, y, max_iterations=70000): theta = np.zeros(x.shape[1]) for iterations in range(max_iterations): z = np.dot(x, theta) h = sigmoid_function(z) gradient = np.dot(x.T, h - y) / y.size theta = theta - alpha * gradient # updating the weights z = np.dot(x, theta) h = sigmoid_function(z) j = cost_function(h, y) if iterations % 100 == 0: print(f"loss: {j} \t") # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": iris = datasets.load_iris() x = iris.data[:, :2] y = (iris.target != 0) * 1 alpha = 0.1 theta = logistic_reg(alpha, x, y, max_iterations=70000) print("theta: ", theta) # printing the theta i.e our weights vector def predict_prob(x): return sigmoid_function( np.dot(x, theta) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 6)) plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color="b", label="0") plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color="r", label="1") (x1_min, x1_max) = (x[:, 0].min(), x[:, 0].max()) (x2_min, x2_max) = (x[:, 1].min(), x[:, 1].max()) (xx1, xx2) = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max)) grid = np.c_[xx1.ravel(), xx2.ravel()] probs = predict_prob(grid).reshape(xx1.shape) plt.contour(xx1, xx2, probs, [0.5], linewidths=1, colors="black") plt.legend() plt.show()
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from typing import Any def viterbi( observations_space: list, states_space: list, initial_probabilities: dict, transition_probabilities: dict, emission_probabilities: dict, ) -> list: """ Viterbi Algorithm, to find the most likely path of states from the start and the expected output. https://en.wikipedia.org/wiki/Viterbi_algorithm sdafads Wikipedia example >>> observations = ["normal", "cold", "dizzy"] >>> states = ["Healthy", "Fever"] >>> start_p = {"Healthy": 0.6, "Fever": 0.4} >>> trans_p = { ... "Healthy": {"Healthy": 0.7, "Fever": 0.3}, ... "Fever": {"Healthy": 0.4, "Fever": 0.6}, ... } >>> emit_p = { ... "Healthy": {"normal": 0.5, "cold": 0.4, "dizzy": 0.1}, ... "Fever": {"normal": 0.1, "cold": 0.3, "dizzy": 0.6}, ... } >>> viterbi(observations, states, start_p, trans_p, emit_p) ['Healthy', 'Healthy', 'Fever'] >>> viterbi((), states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, (), start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, states, {}, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, states, start_p, {}, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, states, start_p, trans_p, {}) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi("invalid", states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: observations_space must be a list >>> viterbi(["valid", 123], states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: observations_space must be a list of strings >>> viterbi(observations, "invalid", start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: states_space must be a list >>> viterbi(observations, ["valid", 123], start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: states_space must be a list of strings >>> viterbi(observations, states, "invalid", trans_p, emit_p) Traceback (most recent call last): ... ValueError: initial_probabilities must be a dict >>> viterbi(observations, states, {2:2}, trans_p, emit_p) Traceback (most recent call last): ... ValueError: initial_probabilities all keys must be strings >>> viterbi(observations, states, {"a":2}, trans_p, emit_p) Traceback (most recent call last): ... ValueError: initial_probabilities all values must be float >>> viterbi(observations, states, start_p, "invalid", emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities must be a dict >>> viterbi(observations, states, start_p, {"a":2}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities all values must be dict >>> viterbi(observations, states, start_p, {2:{2:2}}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities all keys must be strings >>> viterbi(observations, states, start_p, {"a":{2:2}}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities all keys must be strings >>> viterbi(observations, states, start_p, {"a":{"b":2}}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities nested dictionary all values must be float >>> viterbi(observations, states, start_p, trans_p, "invalid") Traceback (most recent call last): ... ValueError: emission_probabilities must be a dict >>> viterbi(observations, states, start_p, trans_p, None) Traceback (most recent call last): ... ValueError: There's an empty parameter """ _validation( observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ) # Creates data structures and fill initial step probabilities: dict = {} pointers: dict = {} for state in states_space: observation = observations_space[0] probabilities[(state, observation)] = ( initial_probabilities[state] * emission_probabilities[state][observation] ) pointers[(state, observation)] = None # Fills the data structure with the probabilities of # different transitions and pointers to previous states for o in range(1, len(observations_space)): observation = observations_space[o] prior_observation = observations_space[o - 1] for state in states_space: # Calculates the argmax for probability function arg_max = "" max_probability = -1 for k_state in states_space: probability = ( probabilities[(k_state, prior_observation)] * transition_probabilities[k_state][state] * emission_probabilities[state][observation] ) if probability > max_probability: max_probability = probability arg_max = k_state # Update probabilities and pointers dicts probabilities[(state, observation)] = ( probabilities[(arg_max, prior_observation)] * transition_probabilities[arg_max][state] * emission_probabilities[state][observation] ) pointers[(state, observation)] = arg_max # The final observation final_observation = observations_space[len(observations_space) - 1] # argmax for given final observation arg_max = "" max_probability = -1 for k_state in states_space: probability = probabilities[(k_state, final_observation)] if probability > max_probability: max_probability = probability arg_max = k_state last_state = arg_max # Process pointers backwards previous = last_state result = [] for o in range(len(observations_space) - 1, -1, -1): result.append(previous) previous = pointers[previous, observations_space[o]] result.reverse() return result def _validation( observations_space: Any, states_space: Any, initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: """ >>> observations = ["normal", "cold", "dizzy"] >>> states = ["Healthy", "Fever"] >>> start_p = {"Healthy": 0.6, "Fever": 0.4} >>> trans_p = { ... "Healthy": {"Healthy": 0.7, "Fever": 0.3}, ... "Fever": {"Healthy": 0.4, "Fever": 0.6}, ... } >>> emit_p = { ... "Healthy": {"normal": 0.5, "cold": 0.4, "dizzy": 0.1}, ... "Fever": {"normal": 0.1, "cold": 0.3, "dizzy": 0.6}, ... } >>> _validation(observations, states, start_p, trans_p, emit_p) >>> _validation([], states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter """ _validate_not_empty( observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ) _validate_lists(observations_space, states_space) _validate_dicts( initial_probabilities, transition_probabilities, emission_probabilities ) def _validate_not_empty( observations_space: Any, states_space: Any, initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: """ >>> _validate_not_empty(["a"], ["b"], {"c":0.5}, ... {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) >>> _validate_not_empty(["a"], ["b"], {"c":0.5}, {}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> _validate_not_empty(["a"], ["b"], None, {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: There's an empty parameter """ if not all( [ observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ] ): raise ValueError("There's an empty parameter") def _validate_lists(observations_space: Any, states_space: Any) -> None: """ >>> _validate_lists(["a"], ["b"]) >>> _validate_lists(1234, ["b"]) Traceback (most recent call last): ... ValueError: observations_space must be a list >>> _validate_lists(["a"], [3]) Traceback (most recent call last): ... ValueError: states_space must be a list of strings """ _validate_list(observations_space, "observations_space") _validate_list(states_space, "states_space") def _validate_list(_object: Any, var_name: str) -> None: """ >>> _validate_list(["a"], "mock_name") >>> _validate_list("a", "mock_name") Traceback (most recent call last): ... ValueError: mock_name must be a list >>> _validate_list([0.5], "mock_name") Traceback (most recent call last): ... ValueError: mock_name must be a list of strings """ if not isinstance(_object, list): raise ValueError(f"{var_name} must be a list") else: for x in _object: if not isinstance(x, str): raise ValueError(f"{var_name} must be a list of strings") def _validate_dicts( initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: """ >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) >>> _validate_dicts("invalid", {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: initial_probabilities must be a dict >>> _validate_dicts({"c":0.5}, {2: {"e": 0.6}}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: transition_probabilities all keys must be strings >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {2: 0.7}}) Traceback (most recent call last): ... ValueError: emission_probabilities all keys must be strings >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {"g": "h"}}) Traceback (most recent call last): ... ValueError: emission_probabilities nested dictionary all values must be float """ _validate_dict(initial_probabilities, "initial_probabilities", float) _validate_nested_dict(transition_probabilities, "transition_probabilities") _validate_nested_dict(emission_probabilities, "emission_probabilities") def _validate_nested_dict(_object: Any, var_name: str) -> None: """ >>> _validate_nested_dict({"a":{"b": 0.5}}, "mock_name") >>> _validate_nested_dict("invalid", "mock_name") Traceback (most recent call last): ... ValueError: mock_name must be a dict >>> _validate_nested_dict({"a": 8}, "mock_name") Traceback (most recent call last): ... ValueError: mock_name all values must be dict >>> _validate_nested_dict({"a":{2: 0.5}}, "mock_name") Traceback (most recent call last): ... ValueError: mock_name all keys must be strings >>> _validate_nested_dict({"a":{"b": 4}}, "mock_name") Traceback (most recent call last): ... ValueError: mock_name nested dictionary all values must be float """ _validate_dict(_object, var_name, dict) for x in _object.values(): _validate_dict(x, var_name, float, True) def _validate_dict( _object: Any, var_name: str, value_type: type, nested: bool = False ) -> None: """ >>> _validate_dict({"b": 0.5}, "mock_name", float) >>> _validate_dict("invalid", "mock_name", float) Traceback (most recent call last): ... ValueError: mock_name must be a dict >>> _validate_dict({"a": 8}, "mock_name", dict) Traceback (most recent call last): ... ValueError: mock_name all values must be dict >>> _validate_dict({2: 0.5}, "mock_name",float, True) Traceback (most recent call last): ... ValueError: mock_name all keys must be strings >>> _validate_dict({"b": 4}, "mock_name", float,True) Traceback (most recent call last): ... ValueError: mock_name nested dictionary all values must be float """ if not isinstance(_object, dict): raise ValueError(f"{var_name} must be a dict") if not all(isinstance(x, str) for x in _object): raise ValueError(f"{var_name} all keys must be strings") if not all(isinstance(x, value_type) for x in _object.values()): nested_text = "nested dictionary " if nested else "" raise ValueError( f"{var_name} {nested_text}all values must be {value_type.__name__}" ) if __name__ == "__main__": from doctest import testmod testmod()
from typing import Any def viterbi( observations_space: list, states_space: list, initial_probabilities: dict, transition_probabilities: dict, emission_probabilities: dict, ) -> list: """ Viterbi Algorithm, to find the most likely path of states from the start and the expected output. https://en.wikipedia.org/wiki/Viterbi_algorithm sdafads Wikipedia example >>> observations = ["normal", "cold", "dizzy"] >>> states = ["Healthy", "Fever"] >>> start_p = {"Healthy": 0.6, "Fever": 0.4} >>> trans_p = { ... "Healthy": {"Healthy": 0.7, "Fever": 0.3}, ... "Fever": {"Healthy": 0.4, "Fever": 0.6}, ... } >>> emit_p = { ... "Healthy": {"normal": 0.5, "cold": 0.4, "dizzy": 0.1}, ... "Fever": {"normal": 0.1, "cold": 0.3, "dizzy": 0.6}, ... } >>> viterbi(observations, states, start_p, trans_p, emit_p) ['Healthy', 'Healthy', 'Fever'] >>> viterbi((), states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, (), start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, states, {}, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, states, start_p, {}, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, states, start_p, trans_p, {}) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi("invalid", states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: observations_space must be a list >>> viterbi(["valid", 123], states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: observations_space must be a list of strings >>> viterbi(observations, "invalid", start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: states_space must be a list >>> viterbi(observations, ["valid", 123], start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: states_space must be a list of strings >>> viterbi(observations, states, "invalid", trans_p, emit_p) Traceback (most recent call last): ... ValueError: initial_probabilities must be a dict >>> viterbi(observations, states, {2:2}, trans_p, emit_p) Traceback (most recent call last): ... ValueError: initial_probabilities all keys must be strings >>> viterbi(observations, states, {"a":2}, trans_p, emit_p) Traceback (most recent call last): ... ValueError: initial_probabilities all values must be float >>> viterbi(observations, states, start_p, "invalid", emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities must be a dict >>> viterbi(observations, states, start_p, {"a":2}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities all values must be dict >>> viterbi(observations, states, start_p, {2:{2:2}}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities all keys must be strings >>> viterbi(observations, states, start_p, {"a":{2:2}}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities all keys must be strings >>> viterbi(observations, states, start_p, {"a":{"b":2}}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities nested dictionary all values must be float >>> viterbi(observations, states, start_p, trans_p, "invalid") Traceback (most recent call last): ... ValueError: emission_probabilities must be a dict >>> viterbi(observations, states, start_p, trans_p, None) Traceback (most recent call last): ... ValueError: There's an empty parameter """ _validation( observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ) # Creates data structures and fill initial step probabilities: dict = {} pointers: dict = {} for state in states_space: observation = observations_space[0] probabilities[(state, observation)] = ( initial_probabilities[state] * emission_probabilities[state][observation] ) pointers[(state, observation)] = None # Fills the data structure with the probabilities of # different transitions and pointers to previous states for o in range(1, len(observations_space)): observation = observations_space[o] prior_observation = observations_space[o - 1] for state in states_space: # Calculates the argmax for probability function arg_max = "" max_probability = -1 for k_state in states_space: probability = ( probabilities[(k_state, prior_observation)] * transition_probabilities[k_state][state] * emission_probabilities[state][observation] ) if probability > max_probability: max_probability = probability arg_max = k_state # Update probabilities and pointers dicts probabilities[(state, observation)] = ( probabilities[(arg_max, prior_observation)] * transition_probabilities[arg_max][state] * emission_probabilities[state][observation] ) pointers[(state, observation)] = arg_max # The final observation final_observation = observations_space[len(observations_space) - 1] # argmax for given final observation arg_max = "" max_probability = -1 for k_state in states_space: probability = probabilities[(k_state, final_observation)] if probability > max_probability: max_probability = probability arg_max = k_state last_state = arg_max # Process pointers backwards previous = last_state result = [] for o in range(len(observations_space) - 1, -1, -1): result.append(previous) previous = pointers[previous, observations_space[o]] result.reverse() return result def _validation( observations_space: Any, states_space: Any, initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: """ >>> observations = ["normal", "cold", "dizzy"] >>> states = ["Healthy", "Fever"] >>> start_p = {"Healthy": 0.6, "Fever": 0.4} >>> trans_p = { ... "Healthy": {"Healthy": 0.7, "Fever": 0.3}, ... "Fever": {"Healthy": 0.4, "Fever": 0.6}, ... } >>> emit_p = { ... "Healthy": {"normal": 0.5, "cold": 0.4, "dizzy": 0.1}, ... "Fever": {"normal": 0.1, "cold": 0.3, "dizzy": 0.6}, ... } >>> _validation(observations, states, start_p, trans_p, emit_p) >>> _validation([], states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter """ _validate_not_empty( observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ) _validate_lists(observations_space, states_space) _validate_dicts( initial_probabilities, transition_probabilities, emission_probabilities ) def _validate_not_empty( observations_space: Any, states_space: Any, initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: """ >>> _validate_not_empty(["a"], ["b"], {"c":0.5}, ... {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) >>> _validate_not_empty(["a"], ["b"], {"c":0.5}, {}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> _validate_not_empty(["a"], ["b"], None, {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: There's an empty parameter """ if not all( [ observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ] ): raise ValueError("There's an empty parameter") def _validate_lists(observations_space: Any, states_space: Any) -> None: """ >>> _validate_lists(["a"], ["b"]) >>> _validate_lists(1234, ["b"]) Traceback (most recent call last): ... ValueError: observations_space must be a list >>> _validate_lists(["a"], [3]) Traceback (most recent call last): ... ValueError: states_space must be a list of strings """ _validate_list(observations_space, "observations_space") _validate_list(states_space, "states_space") def _validate_list(_object: Any, var_name: str) -> None: """ >>> _validate_list(["a"], "mock_name") >>> _validate_list("a", "mock_name") Traceback (most recent call last): ... ValueError: mock_name must be a list >>> _validate_list([0.5], "mock_name") Traceback (most recent call last): ... ValueError: mock_name must be a list of strings """ if not isinstance(_object, list): raise ValueError(f"{var_name} must be a list") else: for x in _object: if not isinstance(x, str): raise ValueError(f"{var_name} must be a list of strings") def _validate_dicts( initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: """ >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) >>> _validate_dicts("invalid", {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: initial_probabilities must be a dict >>> _validate_dicts({"c":0.5}, {2: {"e": 0.6}}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: transition_probabilities all keys must be strings >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {2: 0.7}}) Traceback (most recent call last): ... ValueError: emission_probabilities all keys must be strings >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {"g": "h"}}) Traceback (most recent call last): ... ValueError: emission_probabilities nested dictionary all values must be float """ _validate_dict(initial_probabilities, "initial_probabilities", float) _validate_nested_dict(transition_probabilities, "transition_probabilities") _validate_nested_dict(emission_probabilities, "emission_probabilities") def _validate_nested_dict(_object: Any, var_name: str) -> None: """ >>> _validate_nested_dict({"a":{"b": 0.5}}, "mock_name") >>> _validate_nested_dict("invalid", "mock_name") Traceback (most recent call last): ... ValueError: mock_name must be a dict >>> _validate_nested_dict({"a": 8}, "mock_name") Traceback (most recent call last): ... ValueError: mock_name all values must be dict >>> _validate_nested_dict({"a":{2: 0.5}}, "mock_name") Traceback (most recent call last): ... ValueError: mock_name all keys must be strings >>> _validate_nested_dict({"a":{"b": 4}}, "mock_name") Traceback (most recent call last): ... ValueError: mock_name nested dictionary all values must be float """ _validate_dict(_object, var_name, dict) for x in _object.values(): _validate_dict(x, var_name, float, True) def _validate_dict( _object: Any, var_name: str, value_type: type, nested: bool = False ) -> None: """ >>> _validate_dict({"b": 0.5}, "mock_name", float) >>> _validate_dict("invalid", "mock_name", float) Traceback (most recent call last): ... ValueError: mock_name must be a dict >>> _validate_dict({"a": 8}, "mock_name", dict) Traceback (most recent call last): ... ValueError: mock_name all values must be dict >>> _validate_dict({2: 0.5}, "mock_name",float, True) Traceback (most recent call last): ... ValueError: mock_name all keys must be strings >>> _validate_dict({"b": 4}, "mock_name", float,True) Traceback (most recent call last): ... ValueError: mock_name nested dictionary all values must be float """ if not isinstance(_object, dict): raise ValueError(f"{var_name} must be a dict") if not all(isinstance(x, str) for x in _object): raise ValueError(f"{var_name} all keys must be strings") if not all(isinstance(x, value_type) for x in _object.values()): nested_text = "nested dictionary " if nested else "" raise ValueError( f"{var_name} {nested_text}all values must be {value_type.__name__}" ) if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def reverse_letters(input_str: str) -> str: """ Reverses letters in a given string without adjusting the position of the words >>> reverse_letters('The cat in the hat') 'ehT tac ni eht tah' >>> reverse_letters('The quick brown fox jumped over the lazy dog.') 'ehT kciuq nworb xof depmuj revo eht yzal .god' >>> reverse_letters('Is this true?') 'sI siht ?eurt' >>> reverse_letters("I love Python") 'I evol nohtyP' """ return " ".join([word[::-1] for word in input_str.split()]) if __name__ == "__main__": import doctest doctest.testmod()
def reverse_letters(input_str: str) -> str: """ Reverses letters in a given string without adjusting the position of the words >>> reverse_letters('The cat in the hat') 'ehT tac ni eht tah' >>> reverse_letters('The quick brown fox jumped over the lazy dog.') 'ehT kciuq nworb xof depmuj revo eht yzal .god' >>> reverse_letters('Is this true?') 'sI siht ?eurt' >>> reverse_letters("I love Python") 'I evol nohtyP' """ return " ".join([word[::-1] for word in input_str.split()]) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Implementation of Circular Queue using linked lists # https://en.wikipedia.org/wiki/Circular_buffer from __future__ import annotations from typing import Any class CircularQueueLinkedList: """ Circular FIFO list with the given capacity (default queue length : 6) >>> cq = CircularQueueLinkedList(2) >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.enqueue('c') Traceback (most recent call last): ... Exception: Full Queue """ def __init__(self, initial_capacity: int = 6) -> None: self.front: Node | None = None self.rear: Node | None = None self.create_linked_list(initial_capacity) def create_linked_list(self, initial_capacity: int) -> None: current_node = Node() self.front = current_node self.rear = current_node previous_node = current_node for _ in range(1, initial_capacity): current_node = Node() previous_node.next = current_node current_node.prev = previous_node previous_node = current_node previous_node.next = self.front self.front.prev = previous_node def is_empty(self) -> bool: """ Checks where the queue is empty or not >>> cq = CircularQueueLinkedList() >>> cq.is_empty() True >>> cq.enqueue('a') >>> cq.is_empty() False >>> cq.dequeue() 'a' >>> cq.is_empty() True """ return ( self.front == self.rear and self.front is not None and self.front.data is None ) def first(self) -> Any | None: """ Returns the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.first() 'a' >>> cq.dequeue() 'a' >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('b') >>> cq.enqueue('c') >>> cq.first() 'b' """ self.check_can_perform_operation() return self.front.data if self.front else None def enqueue(self, data: Any) -> None: """ Saves data at the end of the queue >>> cq = CircularQueueLinkedList() >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.dequeue() 'a' >>> cq.dequeue() 'b' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ if self.rear is None: return self.check_is_full() if not self.is_empty(): self.rear = self.rear.next if self.rear: self.rear.data = data def dequeue(self) -> Any: """ Removes and retrieves the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.dequeue() 'a' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ self.check_can_perform_operation() if self.rear is None or self.front is None: return if self.front == self.rear: data = self.front.data self.front.data = None return data old_front = self.front self.front = old_front.next data = old_front.data old_front.data = None return data def check_can_perform_operation(self) -> None: if self.is_empty(): raise Exception("Empty Queue") def check_is_full(self) -> None: if self.rear and self.rear.next == self.front: raise Exception("Full Queue") class Node: def __init__(self) -> None: self.data: Any | None = None self.next: Node | None = None self.prev: Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
# Implementation of Circular Queue using linked lists # https://en.wikipedia.org/wiki/Circular_buffer from __future__ import annotations from typing import Any class CircularQueueLinkedList: """ Circular FIFO list with the given capacity (default queue length : 6) >>> cq = CircularQueueLinkedList(2) >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.enqueue('c') Traceback (most recent call last): ... Exception: Full Queue """ def __init__(self, initial_capacity: int = 6) -> None: self.front: Node | None = None self.rear: Node | None = None self.create_linked_list(initial_capacity) def create_linked_list(self, initial_capacity: int) -> None: current_node = Node() self.front = current_node self.rear = current_node previous_node = current_node for _ in range(1, initial_capacity): current_node = Node() previous_node.next = current_node current_node.prev = previous_node previous_node = current_node previous_node.next = self.front self.front.prev = previous_node def is_empty(self) -> bool: """ Checks where the queue is empty or not >>> cq = CircularQueueLinkedList() >>> cq.is_empty() True >>> cq.enqueue('a') >>> cq.is_empty() False >>> cq.dequeue() 'a' >>> cq.is_empty() True """ return ( self.front == self.rear and self.front is not None and self.front.data is None ) def first(self) -> Any | None: """ Returns the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.first() 'a' >>> cq.dequeue() 'a' >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('b') >>> cq.enqueue('c') >>> cq.first() 'b' """ self.check_can_perform_operation() return self.front.data if self.front else None def enqueue(self, data: Any) -> None: """ Saves data at the end of the queue >>> cq = CircularQueueLinkedList() >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.dequeue() 'a' >>> cq.dequeue() 'b' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ if self.rear is None: return self.check_is_full() if not self.is_empty(): self.rear = self.rear.next if self.rear: self.rear.data = data def dequeue(self) -> Any: """ Removes and retrieves the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.dequeue() 'a' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ self.check_can_perform_operation() if self.rear is None or self.front is None: return if self.front == self.rear: data = self.front.data self.front.data = None return data old_front = self.front self.front = old_front.next data = old_front.data old_front.data = None return data def check_can_perform_operation(self) -> None: if self.is_empty(): raise Exception("Empty Queue") def check_is_full(self) -> None: if self.rear and self.rear.next == self.front: raise Exception("Full Queue") class Node: def __init__(self) -> None: self.data: Any | None = None self.next: Node | None = None self.prev: Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import math from numpy import inf from scipy.integrate import quad def gamma(num: float) -> float: """ https://en.wikipedia.org/wiki/Gamma_function In mathematics, the gamma function is one commonly used extension of the factorial function to complex numbers. The gamma function is defined for all complex numbers except the non-positive integers >>> gamma(-1) Traceback (most recent call last): ... ValueError: math domain error >>> gamma(0) Traceback (most recent call last): ... ValueError: math domain error >>> gamma(9) 40320.0 >>> from math import gamma as math_gamma >>> all(.99999999 < gamma(i) / math_gamma(i) <= 1.000000001 ... for i in range(1, 50)) True >>> from math import gamma as math_gamma >>> gamma(-1)/math_gamma(-1) <= 1.000000001 Traceback (most recent call last): ... ValueError: math domain error >>> from math import gamma as math_gamma >>> gamma(3.3) - math_gamma(3.3) <= 0.00000001 True """ if num <= 0: raise ValueError("math domain error") return quad(integrand, 0, inf, args=(num))[0] def integrand(x: float, z: float) -> float: return math.pow(x, z - 1) * math.exp(-x) if __name__ == "__main__": from doctest import testmod testmod()
import math from numpy import inf from scipy.integrate import quad def gamma(num: float) -> float: """ https://en.wikipedia.org/wiki/Gamma_function In mathematics, the gamma function is one commonly used extension of the factorial function to complex numbers. The gamma function is defined for all complex numbers except the non-positive integers >>> gamma(-1) Traceback (most recent call last): ... ValueError: math domain error >>> gamma(0) Traceback (most recent call last): ... ValueError: math domain error >>> gamma(9) 40320.0 >>> from math import gamma as math_gamma >>> all(.99999999 < gamma(i) / math_gamma(i) <= 1.000000001 ... for i in range(1, 50)) True >>> from math import gamma as math_gamma >>> gamma(-1)/math_gamma(-1) <= 1.000000001 Traceback (most recent call last): ... ValueError: math domain error >>> from math import gamma as math_gamma >>> gamma(3.3) - math_gamma(3.3) <= 0.00000001 True """ if num <= 0: raise ValueError("math domain error") return quad(integrand, 0, inf, args=(num))[0] def integrand(x: float, z: float) -> float: return math.pow(x, z - 1) * math.exp(-x) if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Atbash """ import string def atbash_slow(sequence: str) -> str: """ >>> atbash_slow("ABCDEFG") 'ZYXWVUT' >>> atbash_slow("aW;;123BX") 'zD;;123YC' """ output = "" for i in sequence: extract = ord(i) if 65 <= extract <= 90: output += chr(155 - extract) elif 97 <= extract <= 122: output += chr(219 - extract) else: output += i return output def atbash(sequence: str) -> str: """ >>> atbash("ABCDEFG") 'ZYXWVUT' >>> atbash("aW;;123BX") 'zD;;123YC' """ letters = string.ascii_letters letters_reversed = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(c)] if c in letters else c for c in sequence ) def benchmark() -> None: """Let's benchmark our functions side-by-side...""" from timeit import timeit print("Running performance benchmarks...") setup = "from string import printable ; from __main__ import atbash, atbash_slow" print(f"> atbash_slow(): {timeit('atbash_slow(printable)', setup=setup)} seconds") print(f"> atbash(): {timeit('atbash(printable)', setup=setup)} seconds") if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"{example} encrypted in atbash: {atbash(example)}") benchmark()
""" https://en.wikipedia.org/wiki/Atbash """ import string def atbash_slow(sequence: str) -> str: """ >>> atbash_slow("ABCDEFG") 'ZYXWVUT' >>> atbash_slow("aW;;123BX") 'zD;;123YC' """ output = "" for i in sequence: extract = ord(i) if 65 <= extract <= 90: output += chr(155 - extract) elif 97 <= extract <= 122: output += chr(219 - extract) else: output += i return output def atbash(sequence: str) -> str: """ >>> atbash("ABCDEFG") 'ZYXWVUT' >>> atbash("aW;;123BX") 'zD;;123YC' """ letters = string.ascii_letters letters_reversed = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(c)] if c in letters else c for c in sequence ) def benchmark() -> None: """Let's benchmark our functions side-by-side...""" from timeit import timeit print("Running performance benchmarks...") setup = "from string import printable ; from __main__ import atbash, atbash_slow" print(f"> atbash_slow(): {timeit('atbash_slow(printable)', setup=setup)} seconds") print(f"> atbash(): {timeit('atbash(printable)', setup=setup)} seconds") if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"{example} encrypted in atbash: {atbash(example)}") benchmark()
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Ford-Fulkerson Algorithm for Maximum Flow Problem """ Description: (1) Start with initial flow as 0; (2) Choose augmenting path from source to sink and add path to flow; """ def bfs(graph, s, t, parent): # Return True if there is node that has not iterated. visited = [False] * len(graph) queue = [] queue.append(s) visited[s] = True while queue: u = queue.pop(0) for ind in range(len(graph[u])): if visited[ind] is False and graph[u][ind] > 0: queue.append(ind) visited[ind] = True parent[ind] = u return True if visited[t] else False def ford_fulkerson(graph, source, sink): # This array is filled by BFS and to store path parent = [-1] * (len(graph)) max_flow = 0 while bfs(graph, source, sink, parent): path_flow = float("Inf") s = sink while s != source: # Find the minimum value in select path path_flow = min(path_flow, graph[parent[s]][s]) s = parent[s] max_flow += path_flow v = sink while v != source: u = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] return max_flow graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] source, sink = 0, 5 print(ford_fulkerson(graph, source, sink))
# Ford-Fulkerson Algorithm for Maximum Flow Problem """ Description: (1) Start with initial flow as 0; (2) Choose augmenting path from source to sink and add path to flow; """ def bfs(graph, s, t, parent): # Return True if there is node that has not iterated. visited = [False] * len(graph) queue = [] queue.append(s) visited[s] = True while queue: u = queue.pop(0) for ind in range(len(graph[u])): if visited[ind] is False and graph[u][ind] > 0: queue.append(ind) visited[ind] = True parent[ind] = u return True if visited[t] else False def ford_fulkerson(graph, source, sink): # This array is filled by BFS and to store path parent = [-1] * (len(graph)) max_flow = 0 while bfs(graph, source, sink, parent): path_flow = float("Inf") s = sink while s != source: # Find the minimum value in select path path_flow = min(path_flow, graph[parent[s]][s]) s = parent[s] max_flow += path_flow v = sink while v != source: u = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] return max_flow graph = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] source, sink = 0, 5 print(ford_fulkerson(graph, source, sink))
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Return an image of 16 generations of one-dimensional cellular automata based on a given ruleset number https://mathworld.wolfram.com/ElementaryCellularAutomaton.html """ from __future__ import annotations from PIL import Image # Define the first generation of cells # fmt: off CELLS = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # fmt: on def format_ruleset(ruleset: int) -> list[int]: """ >>> format_ruleset(11100) [0, 0, 0, 1, 1, 1, 0, 0] >>> format_ruleset(0) [0, 0, 0, 0, 0, 0, 0, 0] >>> format_ruleset(11111111) [1, 1, 1, 1, 1, 1, 1, 1] """ return [int(c) for c in f"{ruleset:08}"[:8]] def new_generation(cells: list[list[int]], rule: list[int], time: int) -> list[int]: population = len(cells[0]) # 31 next_generation = [] for i in range(population): # Get the neighbors of each cell # Handle neighbours outside bounds by using 0 as their value left_neighbor = 0 if i == 0 else cells[time][i - 1] right_neighbor = 0 if i == population - 1 else cells[time][i + 1] # Define a new cell and add it to the new generation situation = 7 - int(f"{left_neighbor}{cells[time][i]}{right_neighbor}", 2) next_generation.append(rule[situation]) return next_generation def generate_image(cells: list[list[int]]) -> Image.Image: """ Convert the cells into a greyscale PIL.Image.Image and return it to the caller. >>> from random import random >>> cells = [[random() for w in range(31)] for h in range(16)] >>> img = generate_image(cells) >>> isinstance(img, Image.Image) True >>> img.width, img.height (31, 16) """ # Create the output image img = Image.new("RGB", (len(cells[0]), len(cells))) pixels = img.load() # Generates image for w in range(img.width): for h in range(img.height): color = 255 - int(255 * cells[h][w]) pixels[w, h] = (color, color, color) return img if __name__ == "__main__": rule_num = bin(int(input("Rule:\n").strip()))[2:] rule = format_ruleset(int(rule_num)) for time in range(16): CELLS.append(new_generation(CELLS, rule, time)) img = generate_image(CELLS) # Uncomment to save the image # img.save(f"rule_{rule_num}.png") img.show()
""" Return an image of 16 generations of one-dimensional cellular automata based on a given ruleset number https://mathworld.wolfram.com/ElementaryCellularAutomaton.html """ from __future__ import annotations from PIL import Image # Define the first generation of cells # fmt: off CELLS = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] # fmt: on def format_ruleset(ruleset: int) -> list[int]: """ >>> format_ruleset(11100) [0, 0, 0, 1, 1, 1, 0, 0] >>> format_ruleset(0) [0, 0, 0, 0, 0, 0, 0, 0] >>> format_ruleset(11111111) [1, 1, 1, 1, 1, 1, 1, 1] """ return [int(c) for c in f"{ruleset:08}"[:8]] def new_generation(cells: list[list[int]], rule: list[int], time: int) -> list[int]: population = len(cells[0]) # 31 next_generation = [] for i in range(population): # Get the neighbors of each cell # Handle neighbours outside bounds by using 0 as their value left_neighbor = 0 if i == 0 else cells[time][i - 1] right_neighbor = 0 if i == population - 1 else cells[time][i + 1] # Define a new cell and add it to the new generation situation = 7 - int(f"{left_neighbor}{cells[time][i]}{right_neighbor}", 2) next_generation.append(rule[situation]) return next_generation def generate_image(cells: list[list[int]]) -> Image.Image: """ Convert the cells into a greyscale PIL.Image.Image and return it to the caller. >>> from random import random >>> cells = [[random() for w in range(31)] for h in range(16)] >>> img = generate_image(cells) >>> isinstance(img, Image.Image) True >>> img.width, img.height (31, 16) """ # Create the output image img = Image.new("RGB", (len(cells[0]), len(cells))) pixels = img.load() # Generates image for w in range(img.width): for h in range(img.height): color = 255 - int(255 * cells[h][w]) pixels[w, h] = (color, color, color) return img if __name__ == "__main__": rule_num = bin(int(input("Rule:\n").strip()))[2:] rule = format_ruleset(int(rule_num)) for time in range(16): CELLS.append(new_generation(CELLS, rule, time)) img = generate_image(CELLS) # Uncomment to save the image # img.save(f"rule_{rule_num}.png") img.show()
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Truncatable primes Problem 37: https://projecteuler.net/problem=37 The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ from __future__ import annotations import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def list_truncated_nums(n: int) -> list[int]: """ Returns a list of all left and right truncated numbers of n >>> list_truncated_nums(927628) [927628, 27628, 92762, 7628, 9276, 628, 927, 28, 92, 8, 9] >>> list_truncated_nums(467) [467, 67, 46, 7, 4] >>> list_truncated_nums(58) [58, 8, 5] """ str_num = str(n) list_nums = [n] for i in range(1, len(str_num)): list_nums.append(int(str_num[i:])) list_nums.append(int(str_num[:-i])) return list_nums def validate(n: int) -> bool: """ To optimize the approach, we will rule out the numbers above 1000, whose first or last three digits are not prime >>> validate(74679) False >>> validate(235693) False >>> validate(3797) True """ if len(str(n)) > 3: if not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])): return False return True def compute_truncated_primes(count: int = 11) -> list[int]: """ Returns the list of truncated primes >>> compute_truncated_primes(11) [23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397] """ list_truncated_primes: list[int] = [] num = 13 while len(list_truncated_primes) != count: if validate(num): list_nums = list_truncated_nums(num) if all(is_prime(i) for i in list_nums): list_truncated_primes.append(num) num += 2 return list_truncated_primes def solution() -> int: """ Returns the sum of truncated primes """ return sum(compute_truncated_primes(11)) if __name__ == "__main__": print(f"{sum(compute_truncated_primes(11)) = }")
""" Truncatable primes Problem 37: https://projecteuler.net/problem=37 The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ from __future__ import annotations import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def list_truncated_nums(n: int) -> list[int]: """ Returns a list of all left and right truncated numbers of n >>> list_truncated_nums(927628) [927628, 27628, 92762, 7628, 9276, 628, 927, 28, 92, 8, 9] >>> list_truncated_nums(467) [467, 67, 46, 7, 4] >>> list_truncated_nums(58) [58, 8, 5] """ str_num = str(n) list_nums = [n] for i in range(1, len(str_num)): list_nums.append(int(str_num[i:])) list_nums.append(int(str_num[:-i])) return list_nums def validate(n: int) -> bool: """ To optimize the approach, we will rule out the numbers above 1000, whose first or last three digits are not prime >>> validate(74679) False >>> validate(235693) False >>> validate(3797) True """ if len(str(n)) > 3: if not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])): return False return True def compute_truncated_primes(count: int = 11) -> list[int]: """ Returns the list of truncated primes >>> compute_truncated_primes(11) [23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397] """ list_truncated_primes: list[int] = [] num = 13 while len(list_truncated_primes) != count: if validate(num): list_nums = list_truncated_nums(num) if all(is_prime(i) for i in list_nums): list_truncated_primes.append(num) num += 2 return list_truncated_primes def solution() -> int: """ Returns the sum of truncated primes """ return sum(compute_truncated_primes(11)) if __name__ == "__main__": print(f"{sum(compute_truncated_primes(11)) = }")
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital. HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. """ import itertools def is_combination_valid(combination): """ Checks if a combination (a tuple of 9 digits) is a valid product equation. >>> is_combination_valid(('3', '9', '1', '8', '6', '7', '2', '5', '4')) True >>> is_combination_valid(('1', '2', '3', '4', '5', '6', '7', '8', '9')) False """ return ( int("".join(combination[0:2])) * int("".join(combination[2:5])) == int("".join(combination[5:9])) ) or ( int("".join(combination[0])) * int("".join(combination[1:5])) == int("".join(combination[5:9])) ) def solution(): """ Finds the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital >>> solution() 45228 """ return sum( { int("".join(pandigital[5:9])) for pandigital in itertools.permutations("123456789") if is_combination_valid(pandigital) } ) if __name__ == "__main__": print(solution())
""" We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital. HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. """ import itertools def is_combination_valid(combination): """ Checks if a combination (a tuple of 9 digits) is a valid product equation. >>> is_combination_valid(('3', '9', '1', '8', '6', '7', '2', '5', '4')) True >>> is_combination_valid(('1', '2', '3', '4', '5', '6', '7', '8', '9')) False """ return ( int("".join(combination[0:2])) * int("".join(combination[2:5])) == int("".join(combination[5:9])) ) or ( int("".join(combination[0])) * int("".join(combination[1:5])) == int("".join(combination[5:9])) ) def solution(): """ Finds the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital >>> solution() 45228 """ return sum( { int("".join(pandigital[5:9])) for pandigital in itertools.permutations("123456789") if is_combination_valid(pandigital) } ) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The algorithm finds distance between closest pair of points in the given n points. Approach used -> Divide and conquer The points are sorted based on Xco-ords and then based on Yco-ords separately. And by applying divide and conquer approach, minimum distance is obtained recursively. >> Closest points can lie on different sides of partition. This case handled by forming a strip of points whose Xco-ords distance is less than closest_pair_dis from mid-point's Xco-ords. Points sorted based on Yco-ords are used in this step to reduce sorting time. Closest pair distance is found in the strip of points. (closest_in_strip) min(closest_pair_dis, closest_in_strip) would be the final answer. Time complexity: O(n * log n) """ def euclidean_distance_sqr(point1, point2): """ >>> euclidean_distance_sqr([1,2],[2,4]) 5 """ return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2 def column_based_sort(array, column=0): """ >>> column_based_sort([(5, 1), (4, 2), (3, 0)], 1) [(3, 0), (5, 1), (4, 2)] """ return sorted(array, key=lambda x: x[column]) def dis_between_closest_pair(points, points_counts, min_dis=float("inf")): """ brute force approach to find distance between closest pair points Parameters : points, points_count, min_dis (list(tuple(int, int)), int, int) Returns : min_dis (float): distance between closest pair of points >>> dis_between_closest_pair([[1,2],[2,4],[5,7],[8,9],[11,0]],5) 5 """ for i in range(points_counts - 1): for j in range(i + 1, points_counts): current_dis = euclidean_distance_sqr(points[i], points[j]) if current_dis < min_dis: min_dis = current_dis return min_dis def dis_between_closest_in_strip(points, points_counts, min_dis=float("inf")): """ closest pair of points in strip Parameters : points, points_count, min_dis (list(tuple(int, int)), int, int) Returns : min_dis (float): distance btw closest pair of points in the strip (< min_dis) >>> dis_between_closest_in_strip([[1,2],[2,4],[5,7],[8,9],[11,0]],5) 85 """ for i in range(min(6, points_counts - 1), points_counts): for j in range(max(0, i - 6), i): current_dis = euclidean_distance_sqr(points[i], points[j]) if current_dis < min_dis: min_dis = current_dis return min_dis def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts): """divide and conquer approach Parameters : points, points_count (list(tuple(int, int)), int) Returns : (float): distance btw closest pair of points >>> closest_pair_of_points_sqr([(1, 2), (3, 4)], [(5, 6), (7, 8)], 2) 8 """ # base case if points_counts <= 3: return dis_between_closest_pair(points_sorted_on_x, points_counts) # recursion mid = points_counts // 2 closest_in_left = closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y[:mid], mid ) closest_in_right = closest_pair_of_points_sqr( points_sorted_on_y, points_sorted_on_y[mid:], points_counts - mid ) closest_pair_dis = min(closest_in_left, closest_in_right) """ cross_strip contains the points, whose Xcoords are at a distance(< closest_pair_dis) from mid's Xcoord """ cross_strip = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0]) < closest_pair_dis: cross_strip.append(point) closest_in_strip = dis_between_closest_in_strip( cross_strip, len(cross_strip), closest_pair_dis ) return min(closest_pair_dis, closest_in_strip) def closest_pair_of_points(points, points_counts): """ >>> closest_pair_of_points([(2, 3), (12, 30)], len([(2, 3), (12, 30)])) 28.792360097775937 """ points_sorted_on_x = column_based_sort(points, column=0) points_sorted_on_y = column_based_sort(points, column=1) return ( closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y, points_counts ) ) ** 0.5 if __name__ == "__main__": points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] print("Distance:", closest_pair_of_points(points, len(points)))
""" The algorithm finds distance between closest pair of points in the given n points. Approach used -> Divide and conquer The points are sorted based on Xco-ords and then based on Yco-ords separately. And by applying divide and conquer approach, minimum distance is obtained recursively. >> Closest points can lie on different sides of partition. This case handled by forming a strip of points whose Xco-ords distance is less than closest_pair_dis from mid-point's Xco-ords. Points sorted based on Yco-ords are used in this step to reduce sorting time. Closest pair distance is found in the strip of points. (closest_in_strip) min(closest_pair_dis, closest_in_strip) would be the final answer. Time complexity: O(n * log n) """ def euclidean_distance_sqr(point1, point2): """ >>> euclidean_distance_sqr([1,2],[2,4]) 5 """ return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2 def column_based_sort(array, column=0): """ >>> column_based_sort([(5, 1), (4, 2), (3, 0)], 1) [(3, 0), (5, 1), (4, 2)] """ return sorted(array, key=lambda x: x[column]) def dis_between_closest_pair(points, points_counts, min_dis=float("inf")): """ brute force approach to find distance between closest pair points Parameters : points, points_count, min_dis (list(tuple(int, int)), int, int) Returns : min_dis (float): distance between closest pair of points >>> dis_between_closest_pair([[1,2],[2,4],[5,7],[8,9],[11,0]],5) 5 """ for i in range(points_counts - 1): for j in range(i + 1, points_counts): current_dis = euclidean_distance_sqr(points[i], points[j]) if current_dis < min_dis: min_dis = current_dis return min_dis def dis_between_closest_in_strip(points, points_counts, min_dis=float("inf")): """ closest pair of points in strip Parameters : points, points_count, min_dis (list(tuple(int, int)), int, int) Returns : min_dis (float): distance btw closest pair of points in the strip (< min_dis) >>> dis_between_closest_in_strip([[1,2],[2,4],[5,7],[8,9],[11,0]],5) 85 """ for i in range(min(6, points_counts - 1), points_counts): for j in range(max(0, i - 6), i): current_dis = euclidean_distance_sqr(points[i], points[j]) if current_dis < min_dis: min_dis = current_dis return min_dis def closest_pair_of_points_sqr(points_sorted_on_x, points_sorted_on_y, points_counts): """divide and conquer approach Parameters : points, points_count (list(tuple(int, int)), int) Returns : (float): distance btw closest pair of points >>> closest_pair_of_points_sqr([(1, 2), (3, 4)], [(5, 6), (7, 8)], 2) 8 """ # base case if points_counts <= 3: return dis_between_closest_pair(points_sorted_on_x, points_counts) # recursion mid = points_counts // 2 closest_in_left = closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y[:mid], mid ) closest_in_right = closest_pair_of_points_sqr( points_sorted_on_y, points_sorted_on_y[mid:], points_counts - mid ) closest_pair_dis = min(closest_in_left, closest_in_right) """ cross_strip contains the points, whose Xcoords are at a distance(< closest_pair_dis) from mid's Xcoord """ cross_strip = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0]) < closest_pair_dis: cross_strip.append(point) closest_in_strip = dis_between_closest_in_strip( cross_strip, len(cross_strip), closest_pair_dis ) return min(closest_pair_dis, closest_in_strip) def closest_pair_of_points(points, points_counts): """ >>> closest_pair_of_points([(2, 3), (12, 30)], len([(2, 3), (12, 30)])) 28.792360097775937 """ points_sorted_on_x = column_based_sort(points, column=0) points_sorted_on_y = column_based_sort(points, column=1) return ( closest_pair_of_points_sqr( points_sorted_on_x, points_sorted_on_y, points_counts ) ) ** 0.5 if __name__ == "__main__": points = [(2, 3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)] print("Distance:", closest_pair_of_points(points, len(points)))
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 20: https://projecteuler.net/problem=20 n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ def factorial(num: int) -> int: """Find the factorial of a given number n""" fact = 1 for i in range(1, num + 1): fact *= i return fact def split_and_add(number: int) -> int: """Split number digits and add them.""" sum_of_digits = 0 while number > 0: last_digit = number % 10 sum_of_digits += last_digit number = number // 10 # Removing the last_digit from the given number return sum_of_digits def solution(num: int = 100) -> int: """Returns the sum of the digits in the factorial of num >>> solution(100) 648 >>> solution(50) 216 >>> solution(10) 27 >>> solution(5) 3 >>> solution(3) 6 >>> solution(2) 2 >>> solution(1) 1 """ nfact = factorial(num) result = split_and_add(nfact) return result if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
""" Problem 20: https://projecteuler.net/problem=20 n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! """ def factorial(num: int) -> int: """Find the factorial of a given number n""" fact = 1 for i in range(1, num + 1): fact *= i return fact def split_and_add(number: int) -> int: """Split number digits and add them.""" sum_of_digits = 0 while number > 0: last_digit = number % 10 sum_of_digits += last_digit number = number // 10 # Removing the last_digit from the given number return sum_of_digits def solution(num: int = 100) -> int: """Returns the sum of the digits in the factorial of num >>> solution(100) 648 >>> solution(50) 216 >>> solution(10) 27 >>> solution(5) 3 >>> solution(3) 6 >>> solution(2) 2 >>> solution(1) 1 """ nfact = factorial(num) result = split_and_add(nfact) return result if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
-1
TheAlgorithms/Python
7,984
fix: no implicit optional
https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
dhruvmanila
"2022-11-15T03:45:16Z"
"2022-11-15T13:55:14Z"
316e71b03448b6adb8a32d96cb4d6488ee7b7787
3bf86b91e7d438eb2b9ecbab68060c007d270332
fix: no implicit optional. https://mypy-lang.blogspot.com/2022/11/mypy-0990-released.html ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""README, Author - Anurag Kumar(mailto:[email protected]) Requirements: - sklearn - numpy - matplotlib Python: - 3.5 Inputs: - X , a 2D numpy array of features. - k , number of clusters to create. - initial_centroids , initial centroid values generated by utility function(mentioned in usage). - maxiter , maximum number of iterations to process. - heterogeneity , empty list that will be filled with hetrogeneity values if passed to kmeans func. Usage: 1. define 'k' value, 'X' features array and 'hetrogeneity' empty list 2. create initial_centroids, initial_centroids = get_initial_centroids( X, k, seed=0 # seed value for initial centroid generation, # None for randomness(default=None) ) 3. find centroids and clusters using kmeans function. centroids, cluster_assignment = kmeans( X, k, initial_centroids, maxiter=400, record_heterogeneity=heterogeneity, verbose=True # whether to print logs in console or not.(default=False) ) 4. Plot the loss function, hetrogeneity values for every iteration saved in hetrogeneity list. plot_heterogeneity( heterogeneity, k ) 5. Transfers Dataframe into excel format it must have feature called 'Clust' with k means clustering numbers in it. """ import warnings import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.metrics import pairwise_distances warnings.filterwarnings("ignore") TAG = "K-MEANS-CLUST/ " def get_initial_centroids(data, k, seed=None): """Randomly choose k data points as initial centroids""" if seed is not None: # useful for obtaining consistent results np.random.seed(seed) n = data.shape[0] # number of data points # Pick K indices from range [0, N). rand_indices = np.random.randint(0, n, k) # Keep centroids as dense format, as many entries will be nonzero due to averaging. # As long as at least one document in a cluster contains a word, # it will carry a nonzero weight in the TF-IDF vector of the centroid. centroids = data[rand_indices, :] return centroids def centroid_pairwise_dist(x, centroids): return pairwise_distances(x, centroids, metric="euclidean") def assign_clusters(data, centroids): # Compute distances between each data point and the set of centroids: # Fill in the blank (RHS only) distances_from_centroids = centroid_pairwise_dist(data, centroids) # Compute cluster assignments for each data point: # Fill in the blank (RHS only) cluster_assignment = np.argmin(distances_from_centroids, axis=1) return cluster_assignment def revise_centroids(data, k, cluster_assignment): new_centroids = [] for i in range(k): # Select all data points that belong to cluster i. Fill in the blank (RHS only) member_data_points = data[cluster_assignment == i] # Compute the mean of the data points. Fill in the blank (RHS only) centroid = member_data_points.mean(axis=0) new_centroids.append(centroid) new_centroids = np.array(new_centroids) return new_centroids def compute_heterogeneity(data, k, centroids, cluster_assignment): heterogeneity = 0.0 for i in range(k): # Select all data points that belong to cluster i. Fill in the blank (RHS only) member_data_points = data[cluster_assignment == i, :] if member_data_points.shape[0] > 0: # check if i-th cluster is non-empty # Compute distances from centroid to data points (RHS only) distances = pairwise_distances( member_data_points, [centroids[i]], metric="euclidean" ) squared_distances = distances**2 heterogeneity += np.sum(squared_distances) return heterogeneity def plot_heterogeneity(heterogeneity, k): plt.figure(figsize=(7, 4)) plt.plot(heterogeneity, linewidth=4) plt.xlabel("# Iterations") plt.ylabel("Heterogeneity") plt.title(f"Heterogeneity of clustering over time, K={k:d}") plt.rcParams.update({"font.size": 16}) plt.show() def kmeans( data, k, initial_centroids, maxiter=500, record_heterogeneity=None, verbose=False ): """This function runs k-means on given data and initial set of centroids. maxiter: maximum number of iterations to run.(default=500) record_heterogeneity: (optional) a list, to store the history of heterogeneity as function of iterations if None, do not store the history. verbose: if True, print how many data points changed their cluster labels in each iteration""" centroids = initial_centroids[:] prev_cluster_assignment = None for itr in range(maxiter): if verbose: print(itr, end="") # 1. Make cluster assignments using nearest centroids cluster_assignment = assign_clusters(data, centroids) # 2. Compute a new centroid for each of the k clusters, averaging all data # points assigned to that cluster. centroids = revise_centroids(data, k, cluster_assignment) # Check for convergence: if none of the assignments changed, stop if ( prev_cluster_assignment is not None and (prev_cluster_assignment == cluster_assignment).all() ): break # Print number of new assignments if prev_cluster_assignment is not None: num_changed = np.sum(prev_cluster_assignment != cluster_assignment) if verbose: print( f" {num_changed:5d} elements changed their cluster assignment." ) # Record heterogeneity convergence metric if record_heterogeneity is not None: # YOUR CODE HERE score = compute_heterogeneity(data, k, centroids, cluster_assignment) record_heterogeneity.append(score) prev_cluster_assignment = cluster_assignment[:] return centroids, cluster_assignment # Mock test below if False: # change to true to run this test case. from sklearn import datasets as ds dataset = ds.load_iris() k = 3 heterogeneity = [] initial_centroids = get_initial_centroids(dataset["data"], k, seed=0) centroids, cluster_assignment = kmeans( dataset["data"], k, initial_centroids, maxiter=400, record_heterogeneity=heterogeneity, verbose=True, ) plot_heterogeneity(heterogeneity, k) def report_generator( df: pd.DataFrame, clustering_variables: np.ndarray, fill_missing_report=None ) -> pd.DataFrame: """ Function generates easy-erading clustering report. It takes 2 arguments as an input: DataFrame - dataframe with predicted cluester column; FillMissingReport - dictionary of rules how we are going to fill missing values of for final report generate (not included in modeling); in order to run the function following libraries must be imported: import pandas as pd import numpy as np >>> data = pd.DataFrame() >>> data['numbers'] = [1, 2, 3] >>> data['col1'] = [0.5, 2.5, 4.5] >>> data['col2'] = [100, 200, 300] >>> data['col3'] = [10, 20, 30] >>> data['Cluster'] = [1, 1, 2] >>> report_generator(data, ['col1', 'col2'], 0) Features Type Mark 1 2 0 # of Customers ClusterSize False 2.000000 1.000000 1 % of Customers ClusterProportion False 0.666667 0.333333 2 col1 mean_with_zeros True 1.500000 4.500000 3 col2 mean_with_zeros True 150.000000 300.000000 4 numbers mean_with_zeros False 1.500000 3.000000 .. ... ... ... ... ... 99 dummy 5% False 1.000000 1.000000 100 dummy 95% False 1.000000 1.000000 101 dummy stdev False 0.000000 NaN 102 dummy mode False 1.000000 1.000000 103 dummy median False 1.000000 1.000000 <BLANKLINE> [104 rows x 5 columns] """ # Fill missing values with given rules if fill_missing_report: df.fillna(value=fill_missing_report, inplace=True) df["dummy"] = 1 numeric_cols = df.select_dtypes(np.number).columns report = ( df.groupby(["Cluster"])[ # construct report dataframe numeric_cols ] # group by cluster number .agg( [ ("sum", np.sum), ("mean_with_zeros", lambda x: np.mean(np.nan_to_num(x))), ("mean_without_zeros", lambda x: x.replace(0, np.NaN).mean()), ( "mean_25-75", lambda x: np.mean( np.nan_to_num( sorted(x)[ round(len(x) * 25 / 100) : round(len(x) * 75 / 100) ] ) ), ), ("mean_with_na", np.mean), ("min", lambda x: x.min()), ("5%", lambda x: x.quantile(0.05)), ("25%", lambda x: x.quantile(0.25)), ("50%", lambda x: x.quantile(0.50)), ("75%", lambda x: x.quantile(0.75)), ("95%", lambda x: x.quantile(0.95)), ("max", lambda x: x.max()), ("count", lambda x: x.count()), ("stdev", lambda x: x.std()), ("mode", lambda x: x.mode()[0]), ("median", lambda x: x.median()), ("# > 0", lambda x: (x > 0).sum()), ] ) .T.reset_index() .rename(index=str, columns={"level_0": "Features", "level_1": "Type"}) ) # rename columns # calculate the size of cluster(count of clientID's) clustersize = report[ (report["Features"] == "dummy") & (report["Type"] == "count") ].copy() # avoid SettingWithCopyWarning clustersize.Type = ( "ClusterSize" # rename created cluster df to match report column names ) clustersize.Features = "# of Customers" clusterproportion = pd.DataFrame( clustersize.iloc[:, 2:].values / clustersize.iloc[:, 2:].values.sum() # calculating the proportion of cluster ) clusterproportion[ "Type" ] = "% of Customers" # rename created cluster df to match report column names clusterproportion["Features"] = "ClusterProportion" cols = clusterproportion.columns.tolist() cols = cols[-2:] + cols[:-2] clusterproportion = clusterproportion[cols] # rearrange columns to match report clusterproportion.columns = report.columns a = pd.DataFrame( abs( report[report["Type"] == "count"].iloc[:, 2:].values - clustersize.iloc[:, 2:].values ) ) # generating df with count of nan values a["Features"] = 0 a["Type"] = "# of nan" a.Features = report[ report["Type"] == "count" ].Features.tolist() # filling values in order to match report cols = a.columns.tolist() cols = cols[-2:] + cols[:-2] a = a[cols] # rearrange columns to match report a.columns = report.columns # rename columns to match report report = report.drop( report[report.Type == "count"].index ) # drop count values except cluster size report = pd.concat( [report, a, clustersize, clusterproportion], axis=0 ) # concat report with clustert size and nan values report["Mark"] = report["Features"].isin(clustering_variables) cols = report.columns.tolist() cols = cols[0:2] + cols[-1:] + cols[2:-1] report = report[cols] sorter1 = { "ClusterSize": 9, "ClusterProportion": 8, "mean_with_zeros": 7, "mean_with_na": 6, "max": 5, "50%": 4, "min": 3, "25%": 2, "75%": 1, "# of nan": 0, "# > 0": -1, "sum_with_na": -2, } report = ( report.assign( Sorter1=lambda x: x.Type.map(sorter1), Sorter2=lambda x: list(reversed(range(len(x)))), ) .sort_values(["Sorter1", "Mark", "Sorter2"], ascending=False) .drop(["Sorter1", "Sorter2"], axis=1) ) report.columns.name = "" report = report.reset_index() report.drop(columns=["index"], inplace=True) return report if __name__ == "__main__": import doctest doctest.testmod()
"""README, Author - Anurag Kumar(mailto:[email protected]) Requirements: - sklearn - numpy - matplotlib Python: - 3.5 Inputs: - X , a 2D numpy array of features. - k , number of clusters to create. - initial_centroids , initial centroid values generated by utility function(mentioned in usage). - maxiter , maximum number of iterations to process. - heterogeneity , empty list that will be filled with hetrogeneity values if passed to kmeans func. Usage: 1. define 'k' value, 'X' features array and 'hetrogeneity' empty list 2. create initial_centroids, initial_centroids = get_initial_centroids( X, k, seed=0 # seed value for initial centroid generation, # None for randomness(default=None) ) 3. find centroids and clusters using kmeans function. centroids, cluster_assignment = kmeans( X, k, initial_centroids, maxiter=400, record_heterogeneity=heterogeneity, verbose=True # whether to print logs in console or not.(default=False) ) 4. Plot the loss function, hetrogeneity values for every iteration saved in hetrogeneity list. plot_heterogeneity( heterogeneity, k ) 5. Transfers Dataframe into excel format it must have feature called 'Clust' with k means clustering numbers in it. """ import warnings import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.metrics import pairwise_distances warnings.filterwarnings("ignore") TAG = "K-MEANS-CLUST/ " def get_initial_centroids(data, k, seed=None): """Randomly choose k data points as initial centroids""" if seed is not None: # useful for obtaining consistent results np.random.seed(seed) n = data.shape[0] # number of data points # Pick K indices from range [0, N). rand_indices = np.random.randint(0, n, k) # Keep centroids as dense format, as many entries will be nonzero due to averaging. # As long as at least one document in a cluster contains a word, # it will carry a nonzero weight in the TF-IDF vector of the centroid. centroids = data[rand_indices, :] return centroids def centroid_pairwise_dist(x, centroids): return pairwise_distances(x, centroids, metric="euclidean") def assign_clusters(data, centroids): # Compute distances between each data point and the set of centroids: # Fill in the blank (RHS only) distances_from_centroids = centroid_pairwise_dist(data, centroids) # Compute cluster assignments for each data point: # Fill in the blank (RHS only) cluster_assignment = np.argmin(distances_from_centroids, axis=1) return cluster_assignment def revise_centroids(data, k, cluster_assignment): new_centroids = [] for i in range(k): # Select all data points that belong to cluster i. Fill in the blank (RHS only) member_data_points = data[cluster_assignment == i] # Compute the mean of the data points. Fill in the blank (RHS only) centroid = member_data_points.mean(axis=0) new_centroids.append(centroid) new_centroids = np.array(new_centroids) return new_centroids def compute_heterogeneity(data, k, centroids, cluster_assignment): heterogeneity = 0.0 for i in range(k): # Select all data points that belong to cluster i. Fill in the blank (RHS only) member_data_points = data[cluster_assignment == i, :] if member_data_points.shape[0] > 0: # check if i-th cluster is non-empty # Compute distances from centroid to data points (RHS only) distances = pairwise_distances( member_data_points, [centroids[i]], metric="euclidean" ) squared_distances = distances**2 heterogeneity += np.sum(squared_distances) return heterogeneity def plot_heterogeneity(heterogeneity, k): plt.figure(figsize=(7, 4)) plt.plot(heterogeneity, linewidth=4) plt.xlabel("# Iterations") plt.ylabel("Heterogeneity") plt.title(f"Heterogeneity of clustering over time, K={k:d}") plt.rcParams.update({"font.size": 16}) plt.show() def kmeans( data, k, initial_centroids, maxiter=500, record_heterogeneity=None, verbose=False ): """This function runs k-means on given data and initial set of centroids. maxiter: maximum number of iterations to run.(default=500) record_heterogeneity: (optional) a list, to store the history of heterogeneity as function of iterations if None, do not store the history. verbose: if True, print how many data points changed their cluster labels in each iteration""" centroids = initial_centroids[:] prev_cluster_assignment = None for itr in range(maxiter): if verbose: print(itr, end="") # 1. Make cluster assignments using nearest centroids cluster_assignment = assign_clusters(data, centroids) # 2. Compute a new centroid for each of the k clusters, averaging all data # points assigned to that cluster. centroids = revise_centroids(data, k, cluster_assignment) # Check for convergence: if none of the assignments changed, stop if ( prev_cluster_assignment is not None and (prev_cluster_assignment == cluster_assignment).all() ): break # Print number of new assignments if prev_cluster_assignment is not None: num_changed = np.sum(prev_cluster_assignment != cluster_assignment) if verbose: print( f" {num_changed:5d} elements changed their cluster assignment." ) # Record heterogeneity convergence metric if record_heterogeneity is not None: # YOUR CODE HERE score = compute_heterogeneity(data, k, centroids, cluster_assignment) record_heterogeneity.append(score) prev_cluster_assignment = cluster_assignment[:] return centroids, cluster_assignment # Mock test below if False: # change to true to run this test case. from sklearn import datasets as ds dataset = ds.load_iris() k = 3 heterogeneity = [] initial_centroids = get_initial_centroids(dataset["data"], k, seed=0) centroids, cluster_assignment = kmeans( dataset["data"], k, initial_centroids, maxiter=400, record_heterogeneity=heterogeneity, verbose=True, ) plot_heterogeneity(heterogeneity, k) def report_generator( df: pd.DataFrame, clustering_variables: np.ndarray, fill_missing_report=None ) -> pd.DataFrame: """ Function generates easy-erading clustering report. It takes 2 arguments as an input: DataFrame - dataframe with predicted cluester column; FillMissingReport - dictionary of rules how we are going to fill missing values of for final report generate (not included in modeling); in order to run the function following libraries must be imported: import pandas as pd import numpy as np >>> data = pd.DataFrame() >>> data['numbers'] = [1, 2, 3] >>> data['col1'] = [0.5, 2.5, 4.5] >>> data['col2'] = [100, 200, 300] >>> data['col3'] = [10, 20, 30] >>> data['Cluster'] = [1, 1, 2] >>> report_generator(data, ['col1', 'col2'], 0) Features Type Mark 1 2 0 # of Customers ClusterSize False 2.000000 1.000000 1 % of Customers ClusterProportion False 0.666667 0.333333 2 col1 mean_with_zeros True 1.500000 4.500000 3 col2 mean_with_zeros True 150.000000 300.000000 4 numbers mean_with_zeros False 1.500000 3.000000 .. ... ... ... ... ... 99 dummy 5% False 1.000000 1.000000 100 dummy 95% False 1.000000 1.000000 101 dummy stdev False 0.000000 NaN 102 dummy mode False 1.000000 1.000000 103 dummy median False 1.000000 1.000000 <BLANKLINE> [104 rows x 5 columns] """ # Fill missing values with given rules if fill_missing_report: df.fillna(value=fill_missing_report, inplace=True) df["dummy"] = 1 numeric_cols = df.select_dtypes(np.number).columns report = ( df.groupby(["Cluster"])[ # construct report dataframe numeric_cols ] # group by cluster number .agg( [ ("sum", np.sum), ("mean_with_zeros", lambda x: np.mean(np.nan_to_num(x))), ("mean_without_zeros", lambda x: x.replace(0, np.NaN).mean()), ( "mean_25-75", lambda x: np.mean( np.nan_to_num( sorted(x)[ round(len(x) * 25 / 100) : round(len(x) * 75 / 100) ] ) ), ), ("mean_with_na", np.mean), ("min", lambda x: x.min()), ("5%", lambda x: x.quantile(0.05)), ("25%", lambda x: x.quantile(0.25)), ("50%", lambda x: x.quantile(0.50)), ("75%", lambda x: x.quantile(0.75)), ("95%", lambda x: x.quantile(0.95)), ("max", lambda x: x.max()), ("count", lambda x: x.count()), ("stdev", lambda x: x.std()), ("mode", lambda x: x.mode()[0]), ("median", lambda x: x.median()), ("# > 0", lambda x: (x > 0).sum()), ] ) .T.reset_index() .rename(index=str, columns={"level_0": "Features", "level_1": "Type"}) ) # rename columns # calculate the size of cluster(count of clientID's) clustersize = report[ (report["Features"] == "dummy") & (report["Type"] == "count") ].copy() # avoid SettingWithCopyWarning clustersize.Type = ( "ClusterSize" # rename created cluster df to match report column names ) clustersize.Features = "# of Customers" clusterproportion = pd.DataFrame( clustersize.iloc[:, 2:].values / clustersize.iloc[:, 2:].values.sum() # calculating the proportion of cluster ) clusterproportion[ "Type" ] = "% of Customers" # rename created cluster df to match report column names clusterproportion["Features"] = "ClusterProportion" cols = clusterproportion.columns.tolist() cols = cols[-2:] + cols[:-2] clusterproportion = clusterproportion[cols] # rearrange columns to match report clusterproportion.columns = report.columns a = pd.DataFrame( abs( report[report["Type"] == "count"].iloc[:, 2:].values - clustersize.iloc[:, 2:].values ) ) # generating df with count of nan values a["Features"] = 0 a["Type"] = "# of nan" a.Features = report[ report["Type"] == "count" ].Features.tolist() # filling values in order to match report cols = a.columns.tolist() cols = cols[-2:] + cols[:-2] a = a[cols] # rearrange columns to match report a.columns = report.columns # rename columns to match report report = report.drop( report[report.Type == "count"].index ) # drop count values except cluster size report = pd.concat( [report, a, clustersize, clusterproportion], axis=0 ) # concat report with clustert size and nan values report["Mark"] = report["Features"].isin(clustering_variables) cols = report.columns.tolist() cols = cols[0:2] + cols[-1:] + cols[2:-1] report = report[cols] sorter1 = { "ClusterSize": 9, "ClusterProportion": 8, "mean_with_zeros": 7, "mean_with_na": 6, "max": 5, "50%": 4, "min": 3, "25%": 2, "75%": 1, "# of nan": 0, "# > 0": -1, "sum_with_na": -2, } report = ( report.assign( Sorter1=lambda x: x.Type.map(sorter1), Sorter2=lambda x: list(reversed(range(len(x)))), ) .sort_values(["Sorter1", "Mark", "Sorter2"], ascending=False) .drop(["Sorter1", "Sorter2"], axis=1) ) report.columns.name = "" report = report.reset_index() report.drop(columns=["index"], inplace=True) return report if __name__ == "__main__": import doctest doctest.testmod()
-1