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
7,821
Format docs
### Describe your change: Fix some warnings that would be raised by adding adding `flake8-docstrings` to the pre-commit hooks. This PR is just to show the features of that tool. There are two groups of checks. #### Documentation This looks like a good match with the repo guidelines. For classes and functions, there is an easy trick to use the leading underscore for names, then classes/functions won't be public, so you could document only what you need. - D100 Missing docstring in public module - D101 Missing docstring in public class - D104 Missing docstring in public package #### Docstring formating It might be a bit confusing for people since the summary does not have a lot of sense in the context of this repo. It will have the same words as in the file and function names and algorithm description is in the module docstring. Ignoring that line is not an option since there is a lot of code with doctests. - D205 1 blank line required between summary line and description - D400 First line should end with a period - D401 First line should be in imperative mood; try rephrasing - D403 First word of the first line should be properly capitalized * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] 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}`.
Cjkjvfnby
"2022-10-28T21:48:39Z"
"2022-10-29T06:26:20Z"
762afc086f065f1d8fe1afcde8c8ad3fa46898a7
cf08d9f5e7afdcfb9406032abcad328aa79c566a
Format docs. ### Describe your change: Fix some warnings that would be raised by adding adding `flake8-docstrings` to the pre-commit hooks. This PR is just to show the features of that tool. There are two groups of checks. #### Documentation This looks like a good match with the repo guidelines. For classes and functions, there is an easy trick to use the leading underscore for names, then classes/functions won't be public, so you could document only what you need. - D100 Missing docstring in public module - D101 Missing docstring in public class - D104 Missing docstring in public package #### Docstring formating It might be a bit confusing for people since the summary does not have a lot of sense in the context of this repo. It will have the same words as in the file and function names and algorithm description is in the module docstring. Ignoring that line is not an option since there is a lot of code with doctests. - D205 1 blank line required between summary line and description - D400 First line should end with a period - D401 First line should be in imperative mood; try rephrasing - D403 First word of the first line should be properly capitalized * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] 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}`.
""" A Trie/Prefix Tree is a kind of search tree used to provide quick lookup of words/patterns in a set of words. A basic Trie however has O(n^2) space complexity making it impractical in practice. It however provides O(max(search_string, length of longest word)) lookup time making it an optimal approach when space is not an issue. """ class TrieNode: def __init__(self) -> None: self.nodes: dict[str, TrieNode] = {} # Mapping from char to TrieNode self.is_leaf = False def insert_many(self, words: list[str]) -> None: """ Inserts a list of words into the Trie :param words: list of string words :return: None """ for word in words: self.insert(word) def insert(self, word: str) -> None: """ Inserts a word into the Trie :param word: word to be inserted :return: None """ curr = self for char in word: if char not in curr.nodes: curr.nodes[char] = TrieNode() curr = curr.nodes[char] curr.is_leaf = True def find(self, word: str) -> bool: """ Tries to find word in a Trie :param word: word to look for :return: Returns True if word is found, False otherwise """ curr = self for char in word: if char not in curr.nodes: return False curr = curr.nodes[char] return curr.is_leaf def delete(self, word: str) -> None: """ Deletes a word in a Trie :param word: word to delete :return: None """ def _delete(curr: TrieNode, word: str, index: int) -> bool: if index == len(word): # If word does not exist if not curr.is_leaf: return False curr.is_leaf = False return len(curr.nodes) == 0 char = word[index] char_node = curr.nodes.get(char) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted delete_curr = _delete(char_node, word, index + 1) if delete_curr: del curr.nodes[char] return len(curr.nodes) == 0 return delete_curr _delete(self, word, 0) def print_words(node: TrieNode, word: str) -> None: """ Prints all the words in a Trie :param node: root node of Trie :param word: Word variable should be empty at start :return: None """ if node.is_leaf: print(word, end=" ") for key, value in node.nodes.items(): print_words(value, word + key) def test_trie() -> bool: words = "banana bananas bandana band apple all beast".split() root = TrieNode() root.insert_many(words) # print_words(root, "") assert all(root.find(word) for word in words) assert root.find("banana") assert not root.find("bandanas") assert not root.find("apps") assert root.find("apple") assert root.find("all") root.delete("all") assert not root.find("all") root.delete("banana") assert not root.find("banana") assert root.find("bananas") return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_trie() def main() -> None: """ >>> pytests() """ print_results("Testing trie functionality", test_trie()) if __name__ == "__main__": main()
""" A Trie/Prefix Tree is a kind of search tree used to provide quick lookup of words/patterns in a set of words. A basic Trie however has O(n^2) space complexity making it impractical in practice. It however provides O(max(search_string, length of longest word)) lookup time making it an optimal approach when space is not an issue. """ class TrieNode: def __init__(self) -> None: self.nodes: dict[str, TrieNode] = {} # Mapping from char to TrieNode self.is_leaf = False def insert_many(self, words: list[str]) -> None: """ Inserts a list of words into the Trie :param words: list of string words :return: None """ for word in words: self.insert(word) def insert(self, word: str) -> None: """ Inserts a word into the Trie :param word: word to be inserted :return: None """ curr = self for char in word: if char not in curr.nodes: curr.nodes[char] = TrieNode() curr = curr.nodes[char] curr.is_leaf = True def find(self, word: str) -> bool: """ Tries to find word in a Trie :param word: word to look for :return: Returns True if word is found, False otherwise """ curr = self for char in word: if char not in curr.nodes: return False curr = curr.nodes[char] return curr.is_leaf def delete(self, word: str) -> None: """ Deletes a word in a Trie :param word: word to delete :return: None """ def _delete(curr: TrieNode, word: str, index: int) -> bool: if index == len(word): # If word does not exist if not curr.is_leaf: return False curr.is_leaf = False return len(curr.nodes) == 0 char = word[index] char_node = curr.nodes.get(char) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted delete_curr = _delete(char_node, word, index + 1) if delete_curr: del curr.nodes[char] return len(curr.nodes) == 0 return delete_curr _delete(self, word, 0) def print_words(node: TrieNode, word: str) -> None: """ Prints all the words in a Trie :param node: root node of Trie :param word: Word variable should be empty at start :return: None """ if node.is_leaf: print(word, end=" ") for key, value in node.nodes.items(): print_words(value, word + key) def test_trie() -> bool: words = "banana bananas bandana band apple all beast".split() root = TrieNode() root.insert_many(words) # print_words(root, "") assert all(root.find(word) for word in words) assert root.find("banana") assert not root.find("bandanas") assert not root.find("apps") assert root.find("apple") assert root.find("all") root.delete("all") assert not root.find("all") root.delete("banana") assert not root.find("banana") assert root.find("bananas") return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_trie() def main() -> None: """ >>> pytests() """ print_results("Testing trie functionality", test_trie()) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,821
Format docs
### Describe your change: Fix some warnings that would be raised by adding adding `flake8-docstrings` to the pre-commit hooks. This PR is just to show the features of that tool. There are two groups of checks. #### Documentation This looks like a good match with the repo guidelines. For classes and functions, there is an easy trick to use the leading underscore for names, then classes/functions won't be public, so you could document only what you need. - D100 Missing docstring in public module - D101 Missing docstring in public class - D104 Missing docstring in public package #### Docstring formating It might be a bit confusing for people since the summary does not have a lot of sense in the context of this repo. It will have the same words as in the file and function names and algorithm description is in the module docstring. Ignoring that line is not an option since there is a lot of code with doctests. - D205 1 blank line required between summary line and description - D400 First line should end with a period - D401 First line should be in imperative mood; try rephrasing - D403 First word of the first line should be properly capitalized * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] 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}`.
Cjkjvfnby
"2022-10-28T21:48:39Z"
"2022-10-29T06:26:20Z"
762afc086f065f1d8fe1afcde8c8ad3fa46898a7
cf08d9f5e7afdcfb9406032abcad328aa79c566a
Format docs. ### Describe your change: Fix some warnings that would be raised by adding adding `flake8-docstrings` to the pre-commit hooks. This PR is just to show the features of that tool. There are two groups of checks. #### Documentation This looks like a good match with the repo guidelines. For classes and functions, there is an easy trick to use the leading underscore for names, then classes/functions won't be public, so you could document only what you need. - D100 Missing docstring in public module - D101 Missing docstring in public class - D104 Missing docstring in public package #### Docstring formating It might be a bit confusing for people since the summary does not have a lot of sense in the context of this repo. It will have the same words as in the file and function names and algorithm description is in the module docstring. Ignoring that line is not an option since there is a lot of code with doctests. - D205 1 blank line required between summary line and description - D400 First line should end with a period - D401 First line should be in imperative mood; try rephrasing - D403 First word of the first line should be properly capitalized * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] 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 double_linear_search(array: list[int], search_item: int) -> int: """ Iterate through the array from both sides to find the index of search_item. :param array: the array to be searched :param search_item: the item to be searched :return the index of search_item, if search_item is in array, else -1 Examples: >>> double_linear_search([1, 5, 5, 10], 1) 0 >>> double_linear_search([1, 5, 5, 10], 5) 1 >>> double_linear_search([1, 5, 5, 10], 100) -1 >>> double_linear_search([1, 5, 5, 10], 10) 3 """ # define the start and end index of the given array start_ind, end_ind = 0, len(array) - 1 while start_ind <= end_ind: if array[start_ind] == search_item: return start_ind elif array[end_ind] == search_item: return end_ind else: start_ind += 1 end_ind -= 1 # returns -1 if search_item is not found in array return -1 if __name__ == "__main__": print(double_linear_search(list(range(100)), 40))
from __future__ import annotations def double_linear_search(array: list[int], search_item: int) -> int: """ Iterate through the array from both sides to find the index of search_item. :param array: the array to be searched :param search_item: the item to be searched :return the index of search_item, if search_item is in array, else -1 Examples: >>> double_linear_search([1, 5, 5, 10], 1) 0 >>> double_linear_search([1, 5, 5, 10], 5) 1 >>> double_linear_search([1, 5, 5, 10], 100) -1 >>> double_linear_search([1, 5, 5, 10], 10) 3 """ # define the start and end index of the given array start_ind, end_ind = 0, len(array) - 1 while start_ind <= end_ind: if array[start_ind] == search_item: return start_ind elif array[end_ind] == search_item: return end_ind else: start_ind += 1 end_ind -= 1 # returns -1 if search_item is not found in array return -1 if __name__ == "__main__": print(double_linear_search(list(range(100)), 40))
-1
TheAlgorithms/Python
7,821
Format docs
### Describe your change: Fix some warnings that would be raised by adding adding `flake8-docstrings` to the pre-commit hooks. This PR is just to show the features of that tool. There are two groups of checks. #### Documentation This looks like a good match with the repo guidelines. For classes and functions, there is an easy trick to use the leading underscore for names, then classes/functions won't be public, so you could document only what you need. - D100 Missing docstring in public module - D101 Missing docstring in public class - D104 Missing docstring in public package #### Docstring formating It might be a bit confusing for people since the summary does not have a lot of sense in the context of this repo. It will have the same words as in the file and function names and algorithm description is in the module docstring. Ignoring that line is not an option since there is a lot of code with doctests. - D205 1 blank line required between summary line and description - D400 First line should end with a period - D401 First line should be in imperative mood; try rephrasing - D403 First word of the first line should be properly capitalized * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] 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}`.
Cjkjvfnby
"2022-10-28T21:48:39Z"
"2022-10-29T06:26:20Z"
762afc086f065f1d8fe1afcde8c8ad3fa46898a7
cf08d9f5e7afdcfb9406032abcad328aa79c566a
Format docs. ### Describe your change: Fix some warnings that would be raised by adding adding `flake8-docstrings` to the pre-commit hooks. This PR is just to show the features of that tool. There are two groups of checks. #### Documentation This looks like a good match with the repo guidelines. For classes and functions, there is an easy trick to use the leading underscore for names, then classes/functions won't be public, so you could document only what you need. - D100 Missing docstring in public module - D101 Missing docstring in public class - D104 Missing docstring in public package #### Docstring formating It might be a bit confusing for people since the summary does not have a lot of sense in the context of this repo. It will have the same words as in the file and function names and algorithm description is in the module docstring. Ignoring that line is not an option since there is a lot of code with doctests. - D205 1 blank line required between summary line and description - D400 First line should end with a period - D401 First line should be in imperative mood; try rephrasing - D403 First word of the first line should be properly capitalized * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] 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}`.
class Things: def __init__(self, name, value, weight): self.name = name self.value = value self.weight = weight def __repr__(self): return f"{self.__class__.__name__}({self.name}, {self.value}, {self.weight})" def get_value(self): return self.value def get_name(self): return self.name def get_weight(self): return self.weight def value_weight(self): return self.value / self.weight def build_menu(name, value, weight): menu = [] for i in range(len(value)): menu.append(Things(name[i], value[i], weight[i])) return menu def greedy(item, max_cost, key_func): items_copy = sorted(item, key=key_func, reverse=True) result = [] total_value, total_cost = 0.0, 0.0 for i in range(len(items_copy)): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i]) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def test_greedy(): """ >>> food = ["Burger", "Pizza", "Coca Cola", "Rice", ... "Sambhar", "Chicken", "Fries", "Milk"] >>> value = [80, 100, 60, 70, 50, 110, 90, 60] >>> weight = [40, 60, 40, 70, 100, 85, 55, 70] >>> foods = build_menu(food, value, weight) >>> foods # doctest: +NORMALIZE_WHITESPACE [Things(Burger, 80, 40), Things(Pizza, 100, 60), Things(Coca Cola, 60, 40), Things(Rice, 70, 70), Things(Sambhar, 50, 100), Things(Chicken, 110, 85), Things(Fries, 90, 55), Things(Milk, 60, 70)] >>> greedy(foods, 500, Things.get_value) # doctest: +NORMALIZE_WHITESPACE ([Things(Chicken, 110, 85), Things(Pizza, 100, 60), Things(Fries, 90, 55), Things(Burger, 80, 40), Things(Rice, 70, 70), Things(Coca Cola, 60, 40), Things(Milk, 60, 70)], 570.0) """ if __name__ == "__main__": import doctest doctest.testmod()
class Things: def __init__(self, name, value, weight): self.name = name self.value = value self.weight = weight def __repr__(self): return f"{self.__class__.__name__}({self.name}, {self.value}, {self.weight})" def get_value(self): return self.value def get_name(self): return self.name def get_weight(self): return self.weight def value_weight(self): return self.value / self.weight def build_menu(name, value, weight): menu = [] for i in range(len(value)): menu.append(Things(name[i], value[i], weight[i])) return menu def greedy(item, max_cost, key_func): items_copy = sorted(item, key=key_func, reverse=True) result = [] total_value, total_cost = 0.0, 0.0 for i in range(len(items_copy)): if (total_cost + items_copy[i].get_weight()) <= max_cost: result.append(items_copy[i]) total_cost += items_copy[i].get_weight() total_value += items_copy[i].get_value() return (result, total_value) def test_greedy(): """ >>> food = ["Burger", "Pizza", "Coca Cola", "Rice", ... "Sambhar", "Chicken", "Fries", "Milk"] >>> value = [80, 100, 60, 70, 50, 110, 90, 60] >>> weight = [40, 60, 40, 70, 100, 85, 55, 70] >>> foods = build_menu(food, value, weight) >>> foods # doctest: +NORMALIZE_WHITESPACE [Things(Burger, 80, 40), Things(Pizza, 100, 60), Things(Coca Cola, 60, 40), Things(Rice, 70, 70), Things(Sambhar, 50, 100), Things(Chicken, 110, 85), Things(Fries, 90, 55), Things(Milk, 60, 70)] >>> greedy(foods, 500, Things.get_value) # doctest: +NORMALIZE_WHITESPACE ([Things(Chicken, 110, 85), Things(Pizza, 100, 60), Things(Fries, 90, 55), Things(Burger, 80, 40), Things(Rice, 70, 70), Things(Coca Cola, 60, 40), Things(Milk, 60, 70)], 570.0) """ if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,821
Format docs
### Describe your change: Fix some warnings that would be raised by adding adding `flake8-docstrings` to the pre-commit hooks. This PR is just to show the features of that tool. There are two groups of checks. #### Documentation This looks like a good match with the repo guidelines. For classes and functions, there is an easy trick to use the leading underscore for names, then classes/functions won't be public, so you could document only what you need. - D100 Missing docstring in public module - D101 Missing docstring in public class - D104 Missing docstring in public package #### Docstring formating It might be a bit confusing for people since the summary does not have a lot of sense in the context of this repo. It will have the same words as in the file and function names and algorithm description is in the module docstring. Ignoring that line is not an option since there is a lot of code with doctests. - D205 1 blank line required between summary line and description - D400 First line should end with a period - D401 First line should be in imperative mood; try rephrasing - D403 First word of the first line should be properly capitalized * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] 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}`.
Cjkjvfnby
"2022-10-28T21:48:39Z"
"2022-10-29T06:26:20Z"
762afc086f065f1d8fe1afcde8c8ad3fa46898a7
cf08d9f5e7afdcfb9406032abcad328aa79c566a
Format docs. ### Describe your change: Fix some warnings that would be raised by adding adding `flake8-docstrings` to the pre-commit hooks. This PR is just to show the features of that tool. There are two groups of checks. #### Documentation This looks like a good match with the repo guidelines. For classes and functions, there is an easy trick to use the leading underscore for names, then classes/functions won't be public, so you could document only what you need. - D100 Missing docstring in public module - D101 Missing docstring in public class - D104 Missing docstring in public package #### Docstring formating It might be a bit confusing for people since the summary does not have a lot of sense in the context of this repo. It will have the same words as in the file and function names and algorithm description is in the module docstring. Ignoring that line is not an option since there is a lot of code with doctests. - D205 1 blank line required between summary line and description - D400 First line should end with a period - D401 First line should be in imperative mood; try rephrasing - D403 First word of the first line should be properly capitalized * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] 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 iterative merge sort in Python Author: Aman Gupta For doctests run following command: python3 -m doctest -v iterative_merge_sort.py For manual testing run: python3 iterative_merge_sort.py """ from __future__ import annotations def merge(input_list: list, low: int, mid: int, high: int) -> list: """ sorting left-half and right-half individually then merging them into result """ result = [] left, right = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0)) input_list[low : high + 1] = result + left + right return input_list # iteration over the unsorted list def iter_merge_sort(input_list: list) -> list: """ Return a sorted copy of the input list >>> iter_merge_sort([5, 9, 8, 7, 1, 2, 7]) [1, 2, 5, 7, 7, 8, 9] >>> iter_merge_sort([1]) [1] >>> iter_merge_sort([2, 1]) [1, 2] >>> iter_merge_sort([2, 1, 3]) [1, 2, 3] >>> iter_merge_sort([4, 3, 2, 1]) [1, 2, 3, 4] >>> iter_merge_sort([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> iter_merge_sort(['c', 'b', 'a']) ['a', 'b', 'c'] >>> iter_merge_sort([0.3, 0.2, 0.1]) [0.1, 0.2, 0.3] >>> iter_merge_sort(['dep', 'dang', 'trai']) ['dang', 'dep', 'trai'] >>> iter_merge_sort([6]) [6] >>> iter_merge_sort([]) [] >>> iter_merge_sort([-2, -9, -1, -4]) [-9, -4, -2, -1] >>> iter_merge_sort([1.1, 1, 0.0, -1, -1.1]) [-1.1, -1, 0.0, 1, 1.1] >>> iter_merge_sort(['c', 'b', 'a']) ['a', 'b', 'c'] >>> iter_merge_sort('cba') ['a', 'b', 'c'] """ if len(input_list) <= 1: return input_list input_list = list(input_list) # iteration for two-way merging p = 2 while p <= len(input_list): # getting low, high and middle value for merge-sort of single list for i in range(0, len(input_list), p): low = i high = i + p - 1 mid = (low + high + 1) // 2 input_list = merge(input_list, low, mid, high) # final merge of last two parts if p * 2 >= len(input_list): mid = i input_list = merge(input_list, 0, mid, len(input_list) - 1) break p *= 2 return input_list if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() if user_input == "": unsorted = [] else: unsorted = [int(item.strip()) for item in user_input.split(",")] print(iter_merge_sort(unsorted))
""" Implementation of iterative merge sort in Python Author: Aman Gupta For doctests run following command: python3 -m doctest -v iterative_merge_sort.py For manual testing run: python3 iterative_merge_sort.py """ from __future__ import annotations def merge(input_list: list, low: int, mid: int, high: int) -> list: """ sorting left-half and right-half individually then merging them into result """ result = [] left, right = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0)) input_list[low : high + 1] = result + left + right return input_list # iteration over the unsorted list def iter_merge_sort(input_list: list) -> list: """ Return a sorted copy of the input list >>> iter_merge_sort([5, 9, 8, 7, 1, 2, 7]) [1, 2, 5, 7, 7, 8, 9] >>> iter_merge_sort([1]) [1] >>> iter_merge_sort([2, 1]) [1, 2] >>> iter_merge_sort([2, 1, 3]) [1, 2, 3] >>> iter_merge_sort([4, 3, 2, 1]) [1, 2, 3, 4] >>> iter_merge_sort([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> iter_merge_sort(['c', 'b', 'a']) ['a', 'b', 'c'] >>> iter_merge_sort([0.3, 0.2, 0.1]) [0.1, 0.2, 0.3] >>> iter_merge_sort(['dep', 'dang', 'trai']) ['dang', 'dep', 'trai'] >>> iter_merge_sort([6]) [6] >>> iter_merge_sort([]) [] >>> iter_merge_sort([-2, -9, -1, -4]) [-9, -4, -2, -1] >>> iter_merge_sort([1.1, 1, 0.0, -1, -1.1]) [-1.1, -1, 0.0, 1, 1.1] >>> iter_merge_sort(['c', 'b', 'a']) ['a', 'b', 'c'] >>> iter_merge_sort('cba') ['a', 'b', 'c'] """ if len(input_list) <= 1: return input_list input_list = list(input_list) # iteration for two-way merging p = 2 while p <= len(input_list): # getting low, high and middle value for merge-sort of single list for i in range(0, len(input_list), p): low = i high = i + p - 1 mid = (low + high + 1) // 2 input_list = merge(input_list, low, mid, high) # final merge of last two parts if p * 2 >= len(input_list): mid = i input_list = merge(input_list, 0, mid, len(input_list) - 1) break p *= 2 return input_list if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() if user_input == "": unsorted = [] else: unsorted = [int(item.strip()) for item in user_input.split(",")] print(iter_merge_sort(unsorted))
-1
TheAlgorithms/Python
7,821
Format docs
### Describe your change: Fix some warnings that would be raised by adding adding `flake8-docstrings` to the pre-commit hooks. This PR is just to show the features of that tool. There are two groups of checks. #### Documentation This looks like a good match with the repo guidelines. For classes and functions, there is an easy trick to use the leading underscore for names, then classes/functions won't be public, so you could document only what you need. - D100 Missing docstring in public module - D101 Missing docstring in public class - D104 Missing docstring in public package #### Docstring formating It might be a bit confusing for people since the summary does not have a lot of sense in the context of this repo. It will have the same words as in the file and function names and algorithm description is in the module docstring. Ignoring that line is not an option since there is a lot of code with doctests. - D205 1 blank line required between summary line and description - D400 First line should end with a period - D401 First line should be in imperative mood; try rephrasing - D403 First word of the first line should be properly capitalized * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] 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}`.
Cjkjvfnby
"2022-10-28T21:48:39Z"
"2022-10-29T06:26:20Z"
762afc086f065f1d8fe1afcde8c8ad3fa46898a7
cf08d9f5e7afdcfb9406032abcad328aa79c566a
Format docs. ### Describe your change: Fix some warnings that would be raised by adding adding `flake8-docstrings` to the pre-commit hooks. This PR is just to show the features of that tool. There are two groups of checks. #### Documentation This looks like a good match with the repo guidelines. For classes and functions, there is an easy trick to use the leading underscore for names, then classes/functions won't be public, so you could document only what you need. - D100 Missing docstring in public module - D101 Missing docstring in public class - D104 Missing docstring in public package #### Docstring formating It might be a bit confusing for people since the summary does not have a lot of sense in the context of this repo. It will have the same words as in the file and function names and algorithm description is in the module docstring. Ignoring that line is not an option since there is a lot of code with doctests. - D205 1 blank line required between summary line and description - D400 First line should end with a period - D401 First line should be in imperative mood; try rephrasing - D403 First word of the first line should be properly capitalized * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] 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}`.
""" Convert Base 10 (Decimal) Values to Hexadecimal Representations """ # set decimal value for each hexadecimal digit values = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", } def decimal_to_hexadecimal(decimal: float) -> str: """ take integer decimal value, return hexadecimal representation as str beginning with 0x >>> decimal_to_hexadecimal(5) '0x5' >>> decimal_to_hexadecimal(15) '0xf' >>> decimal_to_hexadecimal(37) '0x25' >>> decimal_to_hexadecimal(255) '0xff' >>> decimal_to_hexadecimal(4096) '0x1000' >>> decimal_to_hexadecimal(999098) '0xf3eba' >>> # negatives work too >>> decimal_to_hexadecimal(-256) '-0x100' >>> # floats are acceptable if equivalent to an int >>> decimal_to_hexadecimal(17.0) '0x11' >>> # other floats will error >>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # strings will error as well >>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # results are the same when compared to Python's default hex function >>> decimal_to_hexadecimal(-256) == hex(-256) True """ assert type(decimal) in (int, float) and decimal == int(decimal) decimal = int(decimal) hexadecimal = "" negative = False if decimal < 0: negative = True decimal *= -1 while decimal > 0: decimal, remainder = divmod(decimal, 16) hexadecimal = values[remainder] + hexadecimal hexadecimal = "0x" + hexadecimal if negative: hexadecimal = "-" + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
""" Convert Base 10 (Decimal) Values to Hexadecimal Representations """ # set decimal value for each hexadecimal digit values = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "a", 11: "b", 12: "c", 13: "d", 14: "e", 15: "f", } def decimal_to_hexadecimal(decimal: float) -> str: """ take integer decimal value, return hexadecimal representation as str beginning with 0x >>> decimal_to_hexadecimal(5) '0x5' >>> decimal_to_hexadecimal(15) '0xf' >>> decimal_to_hexadecimal(37) '0x25' >>> decimal_to_hexadecimal(255) '0xff' >>> decimal_to_hexadecimal(4096) '0x1000' >>> decimal_to_hexadecimal(999098) '0xf3eba' >>> # negatives work too >>> decimal_to_hexadecimal(-256) '-0x100' >>> # floats are acceptable if equivalent to an int >>> decimal_to_hexadecimal(17.0) '0x11' >>> # other floats will error >>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # strings will error as well >>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError >>> # results are the same when compared to Python's default hex function >>> decimal_to_hexadecimal(-256) == hex(-256) True """ assert type(decimal) in (int, float) and decimal == int(decimal) decimal = int(decimal) hexadecimal = "" negative = False if decimal < 0: negative = True decimal *= -1 while decimal > 0: decimal, remainder = divmod(decimal, 16) hexadecimal = values[remainder] + hexadecimal hexadecimal = "0x" + hexadecimal if negative: hexadecimal = "-" + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.3.0 hooks: - id: check-executables-have-shebangs - id: check-yaml - id: end-of-file-fixer types: [python] - id: trailing-whitespace exclude: | (?x)^( data_structures/heap/binomial_heap.py )$ - id: requirements-txt-fixer - repo: https://github.com/psf/black rev: 22.10.0 hooks: - id: black - repo: https://github.com/PyCQA/isort rev: 5.10.1 hooks: - id: isort args: - --profile=black - repo: https://github.com/asottile/pyupgrade rev: v3.1.0 hooks: - id: pyupgrade args: - --py310-plus - repo: https://github.com/PyCQA/flake8 rev: 5.0.4 hooks: - id: flake8 # See .flake8 for args additional_dependencies: - flake8-bugbear - flake8-builtins - flake8-broken-line - flake8-comprehensions - pep8-naming - yesqa - repo: https://github.com/pre-commit/mirrors-mypy rev: v0.982 hooks: - id: mypy args: - --ignore-missing-imports - --install-types # See mirrors-mypy README.md - --non-interactive additional_dependencies: [types-requests] - repo: https://github.com/codespell-project/codespell rev: v2.2.2 hooks: - id: codespell args: - --ignore-words-list=ans,crate,damon,fo,followings,hist,iff,mater,secant,som,sur,tim,zar exclude: | (?x)^( ciphers/prehistoric_men.txt | strings/dictionary.txt | strings/words.txt | project_euler/problem_022/p022_names.txt )$ - repo: local hooks: - id: validate-filenames name: Validate filenames entry: ./scripts/validate_filenames.py language: script pass_filenames: false
repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.3.0 hooks: - id: check-executables-have-shebangs - id: check-yaml - id: end-of-file-fixer types: [python] - id: trailing-whitespace exclude: | (?x)^( data_structures/heap/binomial_heap.py )$ - id: requirements-txt-fixer - repo: https://github.com/MarcoGorelli/auto-walrus rev: v0.2.1 hooks: - id: auto-walrus - repo: https://github.com/psf/black rev: 22.10.0 hooks: - id: black - repo: https://github.com/PyCQA/isort rev: 5.10.1 hooks: - id: isort args: - --profile=black - repo: https://github.com/asottile/pyupgrade rev: v3.1.0 hooks: - id: pyupgrade args: - --py310-plus - repo: https://github.com/PyCQA/flake8 rev: 5.0.4 hooks: - id: flake8 # See .flake8 for args additional_dependencies: - flake8-bugbear - flake8-builtins - flake8-broken-line - flake8-comprehensions - pep8-naming - yesqa - repo: https://github.com/pre-commit/mirrors-mypy rev: v0.982 hooks: - id: mypy args: - --ignore-missing-imports - --install-types # See mirrors-mypy README.md - --non-interactive additional_dependencies: [types-requests] - repo: https://github.com/codespell-project/codespell rev: v2.2.2 hooks: - id: codespell args: - --ignore-words-list=ans,crate,damon,fo,followings,hist,iff,mater,secant,som,sur,tim,zar exclude: | (?x)^( ciphers/prehistoric_men.txt | strings/dictionary.txt | strings/words.txt | project_euler/problem_022/p022_names.txt )$ - repo: local hooks: - id: validate-filenames name: Validate filenames entry: ./scripts/validate_filenames.py language: script pass_filenames: false
1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
## Arithmetic Analysis * [Bisection](arithmetic_analysis/bisection.py) * [Gaussian Elimination](arithmetic_analysis/gaussian_elimination.py) * [In Static Equilibrium](arithmetic_analysis/in_static_equilibrium.py) * [Intersection](arithmetic_analysis/intersection.py) * [Jacobi Iteration Method](arithmetic_analysis/jacobi_iteration_method.py) * [Lu Decomposition](arithmetic_analysis/lu_decomposition.py) * [Newton Forward Interpolation](arithmetic_analysis/newton_forward_interpolation.py) * [Newton Method](arithmetic_analysis/newton_method.py) * [Newton Raphson](arithmetic_analysis/newton_raphson.py) * [Newton Raphson New](arithmetic_analysis/newton_raphson_new.py) * [Secant Method](arithmetic_analysis/secant_method.py) ## Audio Filters * [Butterworth Filter](audio_filters/butterworth_filter.py) * [Equal Loudness Filter](audio_filters/equal_loudness_filter.py) * [Iir Filter](audio_filters/iir_filter.py) * [Show Response](audio_filters/show_response.py) ## Backtracking * [All Combinations](backtracking/all_combinations.py) * [All Permutations](backtracking/all_permutations.py) * [All Subsequences](backtracking/all_subsequences.py) * [Coloring](backtracking/coloring.py) * [Combination Sum](backtracking/combination_sum.py) * [Hamiltonian Cycle](backtracking/hamiltonian_cycle.py) * [Knight Tour](backtracking/knight_tour.py) * [Minimax](backtracking/minimax.py) * [Minmax](backtracking/minmax.py) * [N Queens](backtracking/n_queens.py) * [N Queens Math](backtracking/n_queens_math.py) * [Rat In Maze](backtracking/rat_in_maze.py) * [Sudoku](backtracking/sudoku.py) * [Sum Of Subsets](backtracking/sum_of_subsets.py) ## Bit Manipulation * [Binary And Operator](bit_manipulation/binary_and_operator.py) * [Binary Count Setbits](bit_manipulation/binary_count_setbits.py) * [Binary Count Trailing Zeros](bit_manipulation/binary_count_trailing_zeros.py) * [Binary Or Operator](bit_manipulation/binary_or_operator.py) * [Binary Shifts](bit_manipulation/binary_shifts.py) * [Binary Twos Complement](bit_manipulation/binary_twos_complement.py) * [Binary Xor Operator](bit_manipulation/binary_xor_operator.py) * [Count 1S Brian Kernighan Method](bit_manipulation/count_1s_brian_kernighan_method.py) * [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py) * [Gray Code Sequence](bit_manipulation/gray_code_sequence.py) * [Is Even](bit_manipulation/is_even.py) * [Reverse Bits](bit_manipulation/reverse_bits.py) * [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py) ## Blockchain * [Chinese Remainder Theorem](blockchain/chinese_remainder_theorem.py) * [Diophantine Equation](blockchain/diophantine_equation.py) * [Modular Division](blockchain/modular_division.py) ## Boolean Algebra * [And Gate](boolean_algebra/and_gate.py) * [Nand Gate](boolean_algebra/nand_gate.py) * [Norgate](boolean_algebra/norgate.py) * [Not Gate](boolean_algebra/not_gate.py) * [Or Gate](boolean_algebra/or_gate.py) * [Quine Mc Cluskey](boolean_algebra/quine_mc_cluskey.py) * [Xnor Gate](boolean_algebra/xnor_gate.py) * [Xor Gate](boolean_algebra/xor_gate.py) ## Cellular Automata * [Conways Game Of Life](cellular_automata/conways_game_of_life.py) * [Game Of Life](cellular_automata/game_of_life.py) * [Nagel Schrekenberg](cellular_automata/nagel_schrekenberg.py) * [One Dimensional](cellular_automata/one_dimensional.py) ## Ciphers * [A1Z26](ciphers/a1z26.py) * [Affine Cipher](ciphers/affine_cipher.py) * [Atbash](ciphers/atbash.py) * [Baconian Cipher](ciphers/baconian_cipher.py) * [Base16](ciphers/base16.py) * [Base32](ciphers/base32.py) * [Base64](ciphers/base64.py) * [Base85](ciphers/base85.py) * [Beaufort Cipher](ciphers/beaufort_cipher.py) * [Bifid](ciphers/bifid.py) * [Brute Force Caesar Cipher](ciphers/brute_force_caesar_cipher.py) * [Caesar Cipher](ciphers/caesar_cipher.py) * [Cryptomath Module](ciphers/cryptomath_module.py) * [Decrypt Caesar With Chi Squared](ciphers/decrypt_caesar_with_chi_squared.py) * [Deterministic Miller Rabin](ciphers/deterministic_miller_rabin.py) * [Diffie](ciphers/diffie.py) * [Diffie Hellman](ciphers/diffie_hellman.py) * [Elgamal Key Generator](ciphers/elgamal_key_generator.py) * [Enigma Machine2](ciphers/enigma_machine2.py) * [Hill Cipher](ciphers/hill_cipher.py) * [Mixed Keyword Cypher](ciphers/mixed_keyword_cypher.py) * [Mono Alphabetic Ciphers](ciphers/mono_alphabetic_ciphers.py) * [Morse Code](ciphers/morse_code.py) * [Onepad Cipher](ciphers/onepad_cipher.py) * [Playfair Cipher](ciphers/playfair_cipher.py) * [Polybius](ciphers/polybius.py) * [Porta Cipher](ciphers/porta_cipher.py) * [Rabin Miller](ciphers/rabin_miller.py) * [Rail Fence Cipher](ciphers/rail_fence_cipher.py) * [Rot13](ciphers/rot13.py) * [Rsa Cipher](ciphers/rsa_cipher.py) * [Rsa Factorization](ciphers/rsa_factorization.py) * [Rsa Key Generator](ciphers/rsa_key_generator.py) * [Shuffled Shift Cipher](ciphers/shuffled_shift_cipher.py) * [Simple Keyword Cypher](ciphers/simple_keyword_cypher.py) * [Simple Substitution Cipher](ciphers/simple_substitution_cipher.py) * [Trafid Cipher](ciphers/trafid_cipher.py) * [Transposition Cipher](ciphers/transposition_cipher.py) * [Transposition Cipher Encrypt Decrypt File](ciphers/transposition_cipher_encrypt_decrypt_file.py) * [Vigenere Cipher](ciphers/vigenere_cipher.py) * [Xor Cipher](ciphers/xor_cipher.py) ## Compression * [Burrows Wheeler](compression/burrows_wheeler.py) * [Huffman](compression/huffman.py) * [Lempel Ziv](compression/lempel_ziv.py) * [Lempel Ziv Decompress](compression/lempel_ziv_decompress.py) * [Peak Signal To Noise Ratio](compression/peak_signal_to_noise_ratio.py) * [Run Length Encoding](compression/run_length_encoding.py) ## Computer Vision * [Cnn Classification](computer_vision/cnn_classification.py) * [Flip Augmentation](computer_vision/flip_augmentation.py) * [Harris Corner](computer_vision/harris_corner.py) * [Horn Schunck](computer_vision/horn_schunck.py) * [Mean Threshold](computer_vision/mean_threshold.py) * [Mosaic Augmentation](computer_vision/mosaic_augmentation.py) * [Pooling Functions](computer_vision/pooling_functions.py) ## Conversions * [Astronomical Length Scale Conversion](conversions/astronomical_length_scale_conversion.py) * [Binary To Decimal](conversions/binary_to_decimal.py) * [Binary To Hexadecimal](conversions/binary_to_hexadecimal.py) * [Binary To Octal](conversions/binary_to_octal.py) * [Decimal To Any](conversions/decimal_to_any.py) * [Decimal To Binary](conversions/decimal_to_binary.py) * [Decimal To Binary Recursion](conversions/decimal_to_binary_recursion.py) * [Decimal To Hexadecimal](conversions/decimal_to_hexadecimal.py) * [Decimal To Octal](conversions/decimal_to_octal.py) * [Excel Title To Column](conversions/excel_title_to_column.py) * [Hex To Bin](conversions/hex_to_bin.py) * [Hexadecimal To Decimal](conversions/hexadecimal_to_decimal.py) * [Length Conversion](conversions/length_conversion.py) * [Molecular Chemistry](conversions/molecular_chemistry.py) * [Octal To Decimal](conversions/octal_to_decimal.py) * [Prefix Conversions](conversions/prefix_conversions.py) * [Prefix Conversions String](conversions/prefix_conversions_string.py) * [Pressure Conversions](conversions/pressure_conversions.py) * [Rgb Hsv Conversion](conversions/rgb_hsv_conversion.py) * [Roman Numerals](conversions/roman_numerals.py) * [Speed Conversions](conversions/speed_conversions.py) * [Temperature Conversions](conversions/temperature_conversions.py) * [Volume Conversions](conversions/volume_conversions.py) * [Weight Conversion](conversions/weight_conversion.py) ## Data Structures * Binary Tree * [Avl Tree](data_structures/binary_tree/avl_tree.py) * [Basic Binary Tree](data_structures/binary_tree/basic_binary_tree.py) * [Binary Search Tree](data_structures/binary_tree/binary_search_tree.py) * [Binary Search Tree Recursive](data_structures/binary_tree/binary_search_tree_recursive.py) * [Binary Tree Mirror](data_structures/binary_tree/binary_tree_mirror.py) * [Binary Tree Node Sum](data_structures/binary_tree/binary_tree_node_sum.py) * [Binary Tree Traversals](data_structures/binary_tree/binary_tree_traversals.py) * [Diff Views Of Binary Tree](data_structures/binary_tree/diff_views_of_binary_tree.py) * [Fenwick Tree](data_structures/binary_tree/fenwick_tree.py) * [Inorder Tree Traversal 2022](data_structures/binary_tree/inorder_tree_traversal_2022.py) * [Lazy Segment Tree](data_structures/binary_tree/lazy_segment_tree.py) * [Lowest Common Ancestor](data_structures/binary_tree/lowest_common_ancestor.py) * [Maximum Fenwick Tree](data_structures/binary_tree/maximum_fenwick_tree.py) * [Merge Two Binary Trees](data_structures/binary_tree/merge_two_binary_trees.py) * [Non Recursive Segment Tree](data_structures/binary_tree/non_recursive_segment_tree.py) * [Number Of Possible Binary Trees](data_structures/binary_tree/number_of_possible_binary_trees.py) * [Red Black Tree](data_structures/binary_tree/red_black_tree.py) * [Segment Tree](data_structures/binary_tree/segment_tree.py) * [Segment Tree Other](data_structures/binary_tree/segment_tree_other.py) * [Treap](data_structures/binary_tree/treap.py) * [Wavelet Tree](data_structures/binary_tree/wavelet_tree.py) * Disjoint Set * [Alternate Disjoint Set](data_structures/disjoint_set/alternate_disjoint_set.py) * [Disjoint Set](data_structures/disjoint_set/disjoint_set.py) * Hashing * [Double Hash](data_structures/hashing/double_hash.py) * [Hash Table](data_structures/hashing/hash_table.py) * [Hash Table With Linked List](data_structures/hashing/hash_table_with_linked_list.py) * Number Theory * [Prime Numbers](data_structures/hashing/number_theory/prime_numbers.py) * [Quadratic Probing](data_structures/hashing/quadratic_probing.py) * Heap * [Binomial Heap](data_structures/heap/binomial_heap.py) * [Heap](data_structures/heap/heap.py) * [Heap Generic](data_structures/heap/heap_generic.py) * [Max Heap](data_structures/heap/max_heap.py) * [Min Heap](data_structures/heap/min_heap.py) * [Randomized Heap](data_structures/heap/randomized_heap.py) * [Skew Heap](data_structures/heap/skew_heap.py) * Linked List * [Circular Linked List](data_structures/linked_list/circular_linked_list.py) * [Deque Doubly](data_structures/linked_list/deque_doubly.py) * [Doubly Linked List](data_structures/linked_list/doubly_linked_list.py) * [Doubly Linked List Two](data_structures/linked_list/doubly_linked_list_two.py) * [From Sequence](data_structures/linked_list/from_sequence.py) * [Has Loop](data_structures/linked_list/has_loop.py) * [Is Palindrome](data_structures/linked_list/is_palindrome.py) * [Merge Two Lists](data_structures/linked_list/merge_two_lists.py) * [Middle Element Of Linked List](data_structures/linked_list/middle_element_of_linked_list.py) * [Print Reverse](data_structures/linked_list/print_reverse.py) * [Singly Linked List](data_structures/linked_list/singly_linked_list.py) * [Skip List](data_structures/linked_list/skip_list.py) * [Swap Nodes](data_structures/linked_list/swap_nodes.py) * Queue * [Circular Queue](data_structures/queue/circular_queue.py) * [Circular Queue Linked List](data_structures/queue/circular_queue_linked_list.py) * [Double Ended Queue](data_structures/queue/double_ended_queue.py) * [Linked Queue](data_structures/queue/linked_queue.py) * [Priority Queue Using List](data_structures/queue/priority_queue_using_list.py) * [Queue On List](data_structures/queue/queue_on_list.py) * [Queue On Pseudo Stack](data_structures/queue/queue_on_pseudo_stack.py) * Stacks * [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py) * [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py) * [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py) * [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py) * [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py) * [Next Greater Element](data_structures/stacks/next_greater_element.py) * [Postfix Evaluation](data_structures/stacks/postfix_evaluation.py) * [Prefix Evaluation](data_structures/stacks/prefix_evaluation.py) * [Stack](data_structures/stacks/stack.py) * [Stack With Doubly Linked List](data_structures/stacks/stack_with_doubly_linked_list.py) * [Stack With Singly Linked List](data_structures/stacks/stack_with_singly_linked_list.py) * [Stock Span Problem](data_structures/stacks/stock_span_problem.py) * Trie * [Trie](data_structures/trie/trie.py) ## Digital Image Processing * [Change Brightness](digital_image_processing/change_brightness.py) * [Change Contrast](digital_image_processing/change_contrast.py) * [Convert To Negative](digital_image_processing/convert_to_negative.py) * Dithering * [Burkes](digital_image_processing/dithering/burkes.py) * Edge Detection * [Canny](digital_image_processing/edge_detection/canny.py) * Filters * [Bilateral Filter](digital_image_processing/filters/bilateral_filter.py) * [Convolve](digital_image_processing/filters/convolve.py) * [Gabor Filter](digital_image_processing/filters/gabor_filter.py) * [Gaussian Filter](digital_image_processing/filters/gaussian_filter.py) * [Local Binary Pattern](digital_image_processing/filters/local_binary_pattern.py) * [Median Filter](digital_image_processing/filters/median_filter.py) * [Sobel Filter](digital_image_processing/filters/sobel_filter.py) * Histogram Equalization * [Histogram Stretch](digital_image_processing/histogram_equalization/histogram_stretch.py) * [Index Calculation](digital_image_processing/index_calculation.py) * Morphological Operations * [Dilation Operation](digital_image_processing/morphological_operations/dilation_operation.py) * [Erosion Operation](digital_image_processing/morphological_operations/erosion_operation.py) * Resize * [Resize](digital_image_processing/resize/resize.py) * Rotation * [Rotation](digital_image_processing/rotation/rotation.py) * [Sepia](digital_image_processing/sepia.py) * [Test Digital Image Processing](digital_image_processing/test_digital_image_processing.py) ## Divide And Conquer * [Closest Pair Of Points](divide_and_conquer/closest_pair_of_points.py) * [Convex Hull](divide_and_conquer/convex_hull.py) * [Heaps Algorithm](divide_and_conquer/heaps_algorithm.py) * [Heaps Algorithm Iterative](divide_and_conquer/heaps_algorithm_iterative.py) * [Inversions](divide_and_conquer/inversions.py) * [Kth Order Statistic](divide_and_conquer/kth_order_statistic.py) * [Max Difference Pair](divide_and_conquer/max_difference_pair.py) * [Max Subarray Sum](divide_and_conquer/max_subarray_sum.py) * [Mergesort](divide_and_conquer/mergesort.py) * [Peak](divide_and_conquer/peak.py) * [Power](divide_and_conquer/power.py) * [Strassen Matrix Multiplication](divide_and_conquer/strassen_matrix_multiplication.py) ## Dynamic Programming * [Abbreviation](dynamic_programming/abbreviation.py) * [All Construct](dynamic_programming/all_construct.py) * [Bitmask](dynamic_programming/bitmask.py) * [Catalan Numbers](dynamic_programming/catalan_numbers.py) * [Climbing Stairs](dynamic_programming/climbing_stairs.py) * [Edit Distance](dynamic_programming/edit_distance.py) * [Factorial](dynamic_programming/factorial.py) * [Fast Fibonacci](dynamic_programming/fast_fibonacci.py) * [Fibonacci](dynamic_programming/fibonacci.py) * [Floyd Warshall](dynamic_programming/floyd_warshall.py) * [Integer Partition](dynamic_programming/integer_partition.py) * [Iterating Through Submasks](dynamic_programming/iterating_through_submasks.py) * [Knapsack](dynamic_programming/knapsack.py) * [Longest Common Subsequence](dynamic_programming/longest_common_subsequence.py) * [Longest Common Substring](dynamic_programming/longest_common_substring.py) * [Longest Increasing Subsequence](dynamic_programming/longest_increasing_subsequence.py) * [Longest Increasing Subsequence O(Nlogn)](dynamic_programming/longest_increasing_subsequence_o(nlogn).py) * [Longest Sub Array](dynamic_programming/longest_sub_array.py) * [Matrix Chain Order](dynamic_programming/matrix_chain_order.py) * [Max Non Adjacent Sum](dynamic_programming/max_non_adjacent_sum.py) * [Max Sub Array](dynamic_programming/max_sub_array.py) * [Max Sum Contiguous Subsequence](dynamic_programming/max_sum_contiguous_subsequence.py) * [Minimum Coin Change](dynamic_programming/minimum_coin_change.py) * [Minimum Cost Path](dynamic_programming/minimum_cost_path.py) * [Minimum Partition](dynamic_programming/minimum_partition.py) * [Minimum Squares To Represent A Number](dynamic_programming/minimum_squares_to_represent_a_number.py) * [Minimum Steps To One](dynamic_programming/minimum_steps_to_one.py) * [Optimal Binary Search Tree](dynamic_programming/optimal_binary_search_tree.py) * [Rod Cutting](dynamic_programming/rod_cutting.py) * [Subset Generation](dynamic_programming/subset_generation.py) * [Sum Of Subset](dynamic_programming/sum_of_subset.py) ## Electronics * [Carrier Concentration](electronics/carrier_concentration.py) * [Coulombs Law](electronics/coulombs_law.py) * [Electric Power](electronics/electric_power.py) * [Ohms Law](electronics/ohms_law.py) ## File Transfer * [Receive File](file_transfer/receive_file.py) * [Send File](file_transfer/send_file.py) * Tests * [Test Send File](file_transfer/tests/test_send_file.py) ## Financial * [Equated Monthly Installments](financial/equated_monthly_installments.py) * [Interest](financial/interest.py) ## Fractals * [Julia Sets](fractals/julia_sets.py) * [Koch Snowflake](fractals/koch_snowflake.py) * [Mandelbrot](fractals/mandelbrot.py) * [Sierpinski Triangle](fractals/sierpinski_triangle.py) ## Fuzzy Logic * [Fuzzy Operations](fuzzy_logic/fuzzy_operations.py) ## Genetic Algorithm * [Basic String](genetic_algorithm/basic_string.py) ## Geodesy * [Haversine Distance](geodesy/haversine_distance.py) * [Lamberts Ellipsoidal Distance](geodesy/lamberts_ellipsoidal_distance.py) ## Graphics * [Bezier Curve](graphics/bezier_curve.py) * [Vector3 For 2D Rendering](graphics/vector3_for_2d_rendering.py) ## Graphs * [A Star](graphs/a_star.py) * [Articulation Points](graphs/articulation_points.py) * [Basic Graphs](graphs/basic_graphs.py) * [Bellman Ford](graphs/bellman_ford.py) * [Bfs Shortest Path](graphs/bfs_shortest_path.py) * [Bfs Zero One Shortest Path](graphs/bfs_zero_one_shortest_path.py) * [Bidirectional A Star](graphs/bidirectional_a_star.py) * [Bidirectional Breadth First Search](graphs/bidirectional_breadth_first_search.py) * [Boruvka](graphs/boruvka.py) * [Breadth First Search](graphs/breadth_first_search.py) * [Breadth First Search 2](graphs/breadth_first_search_2.py) * [Breadth First Search Shortest Path](graphs/breadth_first_search_shortest_path.py) * [Check Bipartite Graph Bfs](graphs/check_bipartite_graph_bfs.py) * [Check Bipartite Graph Dfs](graphs/check_bipartite_graph_dfs.py) * [Check Cycle](graphs/check_cycle.py) * [Connected Components](graphs/connected_components.py) * [Depth First Search](graphs/depth_first_search.py) * [Depth First Search 2](graphs/depth_first_search_2.py) * [Dijkstra](graphs/dijkstra.py) * [Dijkstra 2](graphs/dijkstra_2.py) * [Dijkstra Algorithm](graphs/dijkstra_algorithm.py) * [Dijkstra Alternate](graphs/dijkstra_alternate.py) * [Dinic](graphs/dinic.py) * [Directed And Undirected (Weighted) Graph](graphs/directed_and_undirected_(weighted)_graph.py) * [Edmonds Karp Multiple Source And Sink](graphs/edmonds_karp_multiple_source_and_sink.py) * [Eulerian Path And Circuit For Undirected Graph](graphs/eulerian_path_and_circuit_for_undirected_graph.py) * [Even Tree](graphs/even_tree.py) * [Finding Bridges](graphs/finding_bridges.py) * [Frequent Pattern Graph Miner](graphs/frequent_pattern_graph_miner.py) * [G Topological Sort](graphs/g_topological_sort.py) * [Gale Shapley Bigraph](graphs/gale_shapley_bigraph.py) * [Graph List](graphs/graph_list.py) * [Graph Matrix](graphs/graph_matrix.py) * [Graphs Floyd Warshall](graphs/graphs_floyd_warshall.py) * [Greedy Best First](graphs/greedy_best_first.py) * [Greedy Min Vertex Cover](graphs/greedy_min_vertex_cover.py) * [Kahns Algorithm Long](graphs/kahns_algorithm_long.py) * [Kahns Algorithm Topo](graphs/kahns_algorithm_topo.py) * [Karger](graphs/karger.py) * [Markov Chain](graphs/markov_chain.py) * [Matching Min Vertex Cover](graphs/matching_min_vertex_cover.py) * [Minimum Path Sum](graphs/minimum_path_sum.py) * [Minimum Spanning Tree Boruvka](graphs/minimum_spanning_tree_boruvka.py) * [Minimum Spanning Tree Kruskal](graphs/minimum_spanning_tree_kruskal.py) * [Minimum Spanning Tree Kruskal2](graphs/minimum_spanning_tree_kruskal2.py) * [Minimum Spanning Tree Prims](graphs/minimum_spanning_tree_prims.py) * [Minimum Spanning Tree Prims2](graphs/minimum_spanning_tree_prims2.py) * [Multi Heuristic Astar](graphs/multi_heuristic_astar.py) * [Page Rank](graphs/page_rank.py) * [Prim](graphs/prim.py) * [Random Graph Generator](graphs/random_graph_generator.py) * [Scc Kosaraju](graphs/scc_kosaraju.py) * [Strongly Connected Components](graphs/strongly_connected_components.py) * [Tarjans Scc](graphs/tarjans_scc.py) * Tests * [Test Min Spanning Tree Kruskal](graphs/tests/test_min_spanning_tree_kruskal.py) * [Test Min Spanning Tree Prim](graphs/tests/test_min_spanning_tree_prim.py) ## Greedy Methods * [Fractional Knapsack](greedy_methods/fractional_knapsack.py) * [Fractional Knapsack 2](greedy_methods/fractional_knapsack_2.py) * [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py) ## Hashes * [Adler32](hashes/adler32.py) * [Chaos Machine](hashes/chaos_machine.py) * [Djb2](hashes/djb2.py) * [Enigma Machine](hashes/enigma_machine.py) * [Hamming Code](hashes/hamming_code.py) * [Luhn](hashes/luhn.py) * [Md5](hashes/md5.py) * [Sdbm](hashes/sdbm.py) * [Sha1](hashes/sha1.py) * [Sha256](hashes/sha256.py) ## Knapsack * [Greedy Knapsack](knapsack/greedy_knapsack.py) * [Knapsack](knapsack/knapsack.py) * Tests * [Test Greedy Knapsack](knapsack/tests/test_greedy_knapsack.py) * [Test Knapsack](knapsack/tests/test_knapsack.py) ## Linear Algebra * Src * [Conjugate Gradient](linear_algebra/src/conjugate_gradient.py) * [Lib](linear_algebra/src/lib.py) * [Polynom For Points](linear_algebra/src/polynom_for_points.py) * [Power Iteration](linear_algebra/src/power_iteration.py) * [Rayleigh Quotient](linear_algebra/src/rayleigh_quotient.py) * [Schur Complement](linear_algebra/src/schur_complement.py) * [Test Linear Algebra](linear_algebra/src/test_linear_algebra.py) * [Transformations 2D](linear_algebra/src/transformations_2d.py) ## Machine Learning * [Astar](machine_learning/astar.py) * [Data Transformations](machine_learning/data_transformations.py) * [Decision Tree](machine_learning/decision_tree.py) * Forecasting * [Run](machine_learning/forecasting/run.py) * [Gaussian Naive Bayes](machine_learning/gaussian_naive_bayes.py) * [Gradient Boosting Regressor](machine_learning/gradient_boosting_regressor.py) * [Gradient Descent](machine_learning/gradient_descent.py) * [K Means Clust](machine_learning/k_means_clust.py) * [K Nearest Neighbours](machine_learning/k_nearest_neighbours.py) * [Knn Sklearn](machine_learning/knn_sklearn.py) * [Linear Discriminant Analysis](machine_learning/linear_discriminant_analysis.py) * [Linear Regression](machine_learning/linear_regression.py) * Local Weighted Learning * [Local Weighted Learning](machine_learning/local_weighted_learning/local_weighted_learning.py) * [Logistic Regression](machine_learning/logistic_regression.py) * Lstm * [Lstm Prediction](machine_learning/lstm/lstm_prediction.py) * [Multilayer Perceptron Classifier](machine_learning/multilayer_perceptron_classifier.py) * [Polymonial Regression](machine_learning/polymonial_regression.py) * [Random Forest Classifier](machine_learning/random_forest_classifier.py) * [Random Forest Regressor](machine_learning/random_forest_regressor.py) * [Scoring Functions](machine_learning/scoring_functions.py) * [Self Organizing Map](machine_learning/self_organizing_map.py) * [Sequential Minimum Optimization](machine_learning/sequential_minimum_optimization.py) * [Similarity Search](machine_learning/similarity_search.py) * [Support Vector Machines](machine_learning/support_vector_machines.py) * [Word Frequency Functions](machine_learning/word_frequency_functions.py) * [Xgboost Classifier](machine_learning/xgboost_classifier.py) * [Xgboost Regressor](machine_learning/xgboost_regressor.py) ## Maths * [3N Plus 1](maths/3n_plus_1.py) * [Abs](maths/abs.py) * [Abs Max](maths/abs_max.py) * [Abs Min](maths/abs_min.py) * [Add](maths/add.py) * [Aliquot Sum](maths/aliquot_sum.py) * [Allocation Number](maths/allocation_number.py) * [Arc Length](maths/arc_length.py) * [Area](maths/area.py) * [Area Under Curve](maths/area_under_curve.py) * [Armstrong Numbers](maths/armstrong_numbers.py) * [Average Absolute Deviation](maths/average_absolute_deviation.py) * [Average Mean](maths/average_mean.py) * [Average Median](maths/average_median.py) * [Average Mode](maths/average_mode.py) * [Bailey Borwein Plouffe](maths/bailey_borwein_plouffe.py) * [Basic Maths](maths/basic_maths.py) * [Binary Exp Mod](maths/binary_exp_mod.py) * [Binary Exponentiation](maths/binary_exponentiation.py) * [Binary Exponentiation 2](maths/binary_exponentiation_2.py) * [Binary Exponentiation 3](maths/binary_exponentiation_3.py) * [Binomial Coefficient](maths/binomial_coefficient.py) * [Binomial Distribution](maths/binomial_distribution.py) * [Bisection](maths/bisection.py) * [Carmichael Number](maths/carmichael_number.py) * [Catalan Number](maths/catalan_number.py) * [Ceil](maths/ceil.py) * [Check Polygon](maths/check_polygon.py) * [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py) * [Collatz Sequence](maths/collatz_sequence.py) * [Combinations](maths/combinations.py) * [Decimal Isolate](maths/decimal_isolate.py) * [Double Factorial Iterative](maths/double_factorial_iterative.py) * [Double Factorial Recursive](maths/double_factorial_recursive.py) * [Entropy](maths/entropy.py) * [Euclidean Distance](maths/euclidean_distance.py) * [Euclidean Gcd](maths/euclidean_gcd.py) * [Euler Method](maths/euler_method.py) * [Euler Modified](maths/euler_modified.py) * [Eulers Totient](maths/eulers_totient.py) * [Extended Euclidean Algorithm](maths/extended_euclidean_algorithm.py) * [Factorial Iterative](maths/factorial_iterative.py) * [Factorial Recursive](maths/factorial_recursive.py) * [Factors](maths/factors.py) * [Fermat Little Theorem](maths/fermat_little_theorem.py) * [Fibonacci](maths/fibonacci.py) * [Find Max](maths/find_max.py) * [Find Max Recursion](maths/find_max_recursion.py) * [Find Min](maths/find_min.py) * [Find Min Recursion](maths/find_min_recursion.py) * [Floor](maths/floor.py) * [Gamma](maths/gamma.py) * [Gamma Recursive](maths/gamma_recursive.py) * [Gaussian](maths/gaussian.py) * [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py) * [Greatest Common Divisor](maths/greatest_common_divisor.py) * [Greedy Coin Change](maths/greedy_coin_change.py) * [Hamming Numbers](maths/hamming_numbers.py) * [Hardy Ramanujanalgo](maths/hardy_ramanujanalgo.py) * [Integration By Simpson Approx](maths/integration_by_simpson_approx.py) * [Is Ip V4 Address Valid](maths/is_ip_v4_address_valid.py) * [Is Square Free](maths/is_square_free.py) * [Jaccard Similarity](maths/jaccard_similarity.py) * [Kadanes](maths/kadanes.py) * [Karatsuba](maths/karatsuba.py) * [Krishnamurthy Number](maths/krishnamurthy_number.py) * [Kth Lexicographic Permutation](maths/kth_lexicographic_permutation.py) * [Largest Of Very Large Numbers](maths/largest_of_very_large_numbers.py) * [Largest Subarray Sum](maths/largest_subarray_sum.py) * [Least Common Multiple](maths/least_common_multiple.py) * [Line Length](maths/line_length.py) * [Lucas Lehmer Primality Test](maths/lucas_lehmer_primality_test.py) * [Lucas Series](maths/lucas_series.py) * [Maclaurin Series](maths/maclaurin_series.py) * [Matrix Exponentiation](maths/matrix_exponentiation.py) * [Max Sum Sliding Window](maths/max_sum_sliding_window.py) * [Median Of Two Arrays](maths/median_of_two_arrays.py) * [Miller Rabin](maths/miller_rabin.py) * [Mobius Function](maths/mobius_function.py) * [Modular Exponential](maths/modular_exponential.py) * [Monte Carlo](maths/monte_carlo.py) * [Monte Carlo Dice](maths/monte_carlo_dice.py) * [Nevilles Method](maths/nevilles_method.py) * [Newton Raphson](maths/newton_raphson.py) * [Number Of Digits](maths/number_of_digits.py) * [Numerical Integration](maths/numerical_integration.py) * [Perfect Cube](maths/perfect_cube.py) * [Perfect Number](maths/perfect_number.py) * [Perfect Square](maths/perfect_square.py) * [Persistence](maths/persistence.py) * [Pi Monte Carlo Estimation](maths/pi_monte_carlo_estimation.py) * [Points Are Collinear 3D](maths/points_are_collinear_3d.py) * [Pollard Rho](maths/pollard_rho.py) * [Polynomial Evaluation](maths/polynomial_evaluation.py) * [Power Using Recursion](maths/power_using_recursion.py) * [Prime Check](maths/prime_check.py) * [Prime Factors](maths/prime_factors.py) * [Prime Numbers](maths/prime_numbers.py) * [Prime Sieve Eratosthenes](maths/prime_sieve_eratosthenes.py) * [Primelib](maths/primelib.py) * [Proth Number](maths/proth_number.py) * [Pythagoras](maths/pythagoras.py) * [Qr Decomposition](maths/qr_decomposition.py) * [Quadratic Equations Complex Numbers](maths/quadratic_equations_complex_numbers.py) * [Radians](maths/radians.py) * [Radix2 Fft](maths/radix2_fft.py) * [Relu](maths/relu.py) * [Runge Kutta](maths/runge_kutta.py) * [Segmented Sieve](maths/segmented_sieve.py) * Series * [Arithmetic](maths/series/arithmetic.py) * [Geometric](maths/series/geometric.py) * [Geometric Series](maths/series/geometric_series.py) * [Harmonic](maths/series/harmonic.py) * [Harmonic Series](maths/series/harmonic_series.py) * [Hexagonal Numbers](maths/series/hexagonal_numbers.py) * [P Series](maths/series/p_series.py) * [Sieve Of Eratosthenes](maths/sieve_of_eratosthenes.py) * [Sigmoid](maths/sigmoid.py) * [Signum](maths/signum.py) * [Simpson Rule](maths/simpson_rule.py) * [Sin](maths/sin.py) * [Sock Merchant](maths/sock_merchant.py) * [Softmax](maths/softmax.py) * [Square Root](maths/square_root.py) * [Sum Of Arithmetic Series](maths/sum_of_arithmetic_series.py) * [Sum Of Digits](maths/sum_of_digits.py) * [Sum Of Geometric Progression](maths/sum_of_geometric_progression.py) * [Sum Of Harmonic Series](maths/sum_of_harmonic_series.py) * [Sylvester Sequence](maths/sylvester_sequence.py) * [Test Prime Check](maths/test_prime_check.py) * [Trapezoidal Rule](maths/trapezoidal_rule.py) * [Triplet Sum](maths/triplet_sum.py) * [Two Pointer](maths/two_pointer.py) * [Two Sum](maths/two_sum.py) * [Ugly Numbers](maths/ugly_numbers.py) * [Volume](maths/volume.py) * [Weird Number](maths/weird_number.py) * [Zellers Congruence](maths/zellers_congruence.py) ## Matrix * [Binary Search Matrix](matrix/binary_search_matrix.py) * [Count Islands In Matrix](matrix/count_islands_in_matrix.py) * [Cramers Rule 2X2](matrix/cramers_rule_2x2.py) * [Inverse Of Matrix](matrix/inverse_of_matrix.py) * [Largest Square Area In Matrix](matrix/largest_square_area_in_matrix.py) * [Matrix Class](matrix/matrix_class.py) * [Matrix Operation](matrix/matrix_operation.py) * [Max Area Of Island](matrix/max_area_of_island.py) * [Nth Fibonacci Using Matrix Exponentiation](matrix/nth_fibonacci_using_matrix_exponentiation.py) * [Rotate Matrix](matrix/rotate_matrix.py) * [Searching In Sorted Matrix](matrix/searching_in_sorted_matrix.py) * [Sherman Morrison](matrix/sherman_morrison.py) * [Spiral Print](matrix/spiral_print.py) * Tests * [Test Matrix Operation](matrix/tests/test_matrix_operation.py) ## Networking Flow * [Ford Fulkerson](networking_flow/ford_fulkerson.py) * [Minimum Cut](networking_flow/minimum_cut.py) ## Neural Network * [2 Hidden Layers Neural Network](neural_network/2_hidden_layers_neural_network.py) * [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py) * [Convolution Neural Network](neural_network/convolution_neural_network.py) * [Perceptron](neural_network/perceptron.py) ## Other * [Activity Selection](other/activity_selection.py) * [Alternative List Arrange](other/alternative_list_arrange.py) * [Check Strong Password](other/check_strong_password.py) * [Davisb Putnamb Logemannb Loveland](other/davisb_putnamb_logemannb_loveland.py) * [Dijkstra Bankers Algorithm](other/dijkstra_bankers_algorithm.py) * [Doomsday](other/doomsday.py) * [Fischer Yates Shuffle](other/fischer_yates_shuffle.py) * [Gauss Easter](other/gauss_easter.py) * [Graham Scan](other/graham_scan.py) * [Greedy](other/greedy.py) * [Least Recently Used](other/least_recently_used.py) * [Lfu Cache](other/lfu_cache.py) * [Linear Congruential Generator](other/linear_congruential_generator.py) * [Lru Cache](other/lru_cache.py) * [Magicdiamondpattern](other/magicdiamondpattern.py) * [Maximum Subarray](other/maximum_subarray.py) * [Nested Brackets](other/nested_brackets.py) * [Password Generator](other/password_generator.py) * [Scoring Algorithm](other/scoring_algorithm.py) * [Sdes](other/sdes.py) * [Tower Of Hanoi](other/tower_of_hanoi.py) ## Physics * [Casimir Effect](physics/casimir_effect.py) * [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py) * [Kinetic Energy](physics/kinetic_energy.py) * [Lorentz Transformation Four Vector](physics/lorentz_transformation_four_vector.py) * [N Body Simulation](physics/n_body_simulation.py) * [Newtons Law Of Gravitation](physics/newtons_law_of_gravitation.py) * [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py) ## Project Euler * Problem 001 * [Sol1](project_euler/problem_001/sol1.py) * [Sol2](project_euler/problem_001/sol2.py) * [Sol3](project_euler/problem_001/sol3.py) * [Sol4](project_euler/problem_001/sol4.py) * [Sol5](project_euler/problem_001/sol5.py) * [Sol6](project_euler/problem_001/sol6.py) * [Sol7](project_euler/problem_001/sol7.py) * Problem 002 * [Sol1](project_euler/problem_002/sol1.py) * [Sol2](project_euler/problem_002/sol2.py) * [Sol3](project_euler/problem_002/sol3.py) * [Sol4](project_euler/problem_002/sol4.py) * [Sol5](project_euler/problem_002/sol5.py) * Problem 003 * [Sol1](project_euler/problem_003/sol1.py) * [Sol2](project_euler/problem_003/sol2.py) * [Sol3](project_euler/problem_003/sol3.py) * Problem 004 * [Sol1](project_euler/problem_004/sol1.py) * [Sol2](project_euler/problem_004/sol2.py) * Problem 005 * [Sol1](project_euler/problem_005/sol1.py) * [Sol2](project_euler/problem_005/sol2.py) * Problem 006 * [Sol1](project_euler/problem_006/sol1.py) * [Sol2](project_euler/problem_006/sol2.py) * [Sol3](project_euler/problem_006/sol3.py) * [Sol4](project_euler/problem_006/sol4.py) * Problem 007 * [Sol1](project_euler/problem_007/sol1.py) * [Sol2](project_euler/problem_007/sol2.py) * [Sol3](project_euler/problem_007/sol3.py) * Problem 008 * [Sol1](project_euler/problem_008/sol1.py) * [Sol2](project_euler/problem_008/sol2.py) * [Sol3](project_euler/problem_008/sol3.py) * Problem 009 * [Sol1](project_euler/problem_009/sol1.py) * [Sol2](project_euler/problem_009/sol2.py) * [Sol3](project_euler/problem_009/sol3.py) * Problem 010 * [Sol1](project_euler/problem_010/sol1.py) * [Sol2](project_euler/problem_010/sol2.py) * [Sol3](project_euler/problem_010/sol3.py) * Problem 011 * [Sol1](project_euler/problem_011/sol1.py) * [Sol2](project_euler/problem_011/sol2.py) * Problem 012 * [Sol1](project_euler/problem_012/sol1.py) * [Sol2](project_euler/problem_012/sol2.py) * Problem 013 * [Sol1](project_euler/problem_013/sol1.py) * Problem 014 * [Sol1](project_euler/problem_014/sol1.py) * [Sol2](project_euler/problem_014/sol2.py) * Problem 015 * [Sol1](project_euler/problem_015/sol1.py) * Problem 016 * [Sol1](project_euler/problem_016/sol1.py) * [Sol2](project_euler/problem_016/sol2.py) * Problem 017 * [Sol1](project_euler/problem_017/sol1.py) * Problem 018 * [Solution](project_euler/problem_018/solution.py) * Problem 019 * [Sol1](project_euler/problem_019/sol1.py) * Problem 020 * [Sol1](project_euler/problem_020/sol1.py) * [Sol2](project_euler/problem_020/sol2.py) * [Sol3](project_euler/problem_020/sol3.py) * [Sol4](project_euler/problem_020/sol4.py) * Problem 021 * [Sol1](project_euler/problem_021/sol1.py) * Problem 022 * [Sol1](project_euler/problem_022/sol1.py) * [Sol2](project_euler/problem_022/sol2.py) * Problem 023 * [Sol1](project_euler/problem_023/sol1.py) * Problem 024 * [Sol1](project_euler/problem_024/sol1.py) * Problem 025 * [Sol1](project_euler/problem_025/sol1.py) * [Sol2](project_euler/problem_025/sol2.py) * [Sol3](project_euler/problem_025/sol3.py) * Problem 026 * [Sol1](project_euler/problem_026/sol1.py) * Problem 027 * [Sol1](project_euler/problem_027/sol1.py) * Problem 028 * [Sol1](project_euler/problem_028/sol1.py) * Problem 029 * [Sol1](project_euler/problem_029/sol1.py) * Problem 030 * [Sol1](project_euler/problem_030/sol1.py) * Problem 031 * [Sol1](project_euler/problem_031/sol1.py) * [Sol2](project_euler/problem_031/sol2.py) * Problem 032 * [Sol32](project_euler/problem_032/sol32.py) * Problem 033 * [Sol1](project_euler/problem_033/sol1.py) * Problem 034 * [Sol1](project_euler/problem_034/sol1.py) * Problem 035 * [Sol1](project_euler/problem_035/sol1.py) * Problem 036 * [Sol1](project_euler/problem_036/sol1.py) * Problem 037 * [Sol1](project_euler/problem_037/sol1.py) * Problem 038 * [Sol1](project_euler/problem_038/sol1.py) * Problem 039 * [Sol1](project_euler/problem_039/sol1.py) * Problem 040 * [Sol1](project_euler/problem_040/sol1.py) * Problem 041 * [Sol1](project_euler/problem_041/sol1.py) * Problem 042 * [Solution42](project_euler/problem_042/solution42.py) * Problem 043 * [Sol1](project_euler/problem_043/sol1.py) * Problem 044 * [Sol1](project_euler/problem_044/sol1.py) * Problem 045 * [Sol1](project_euler/problem_045/sol1.py) * Problem 046 * [Sol1](project_euler/problem_046/sol1.py) * Problem 047 * [Sol1](project_euler/problem_047/sol1.py) * Problem 048 * [Sol1](project_euler/problem_048/sol1.py) * Problem 049 * [Sol1](project_euler/problem_049/sol1.py) * Problem 050 * [Sol1](project_euler/problem_050/sol1.py) * Problem 051 * [Sol1](project_euler/problem_051/sol1.py) * Problem 052 * [Sol1](project_euler/problem_052/sol1.py) * Problem 053 * [Sol1](project_euler/problem_053/sol1.py) * Problem 054 * [Sol1](project_euler/problem_054/sol1.py) * [Test Poker Hand](project_euler/problem_054/test_poker_hand.py) * Problem 055 * [Sol1](project_euler/problem_055/sol1.py) * Problem 056 * [Sol1](project_euler/problem_056/sol1.py) * Problem 057 * [Sol1](project_euler/problem_057/sol1.py) * Problem 058 * [Sol1](project_euler/problem_058/sol1.py) * Problem 059 * [Sol1](project_euler/problem_059/sol1.py) * Problem 062 * [Sol1](project_euler/problem_062/sol1.py) * Problem 063 * [Sol1](project_euler/problem_063/sol1.py) * Problem 064 * [Sol1](project_euler/problem_064/sol1.py) * Problem 065 * [Sol1](project_euler/problem_065/sol1.py) * Problem 067 * [Sol1](project_euler/problem_067/sol1.py) * [Sol2](project_euler/problem_067/sol2.py) * Problem 068 * [Sol1](project_euler/problem_068/sol1.py) * Problem 069 * [Sol1](project_euler/problem_069/sol1.py) * Problem 070 * [Sol1](project_euler/problem_070/sol1.py) * Problem 071 * [Sol1](project_euler/problem_071/sol1.py) * Problem 072 * [Sol1](project_euler/problem_072/sol1.py) * [Sol2](project_euler/problem_072/sol2.py) * Problem 073 * [Sol1](project_euler/problem_073/sol1.py) * Problem 074 * [Sol1](project_euler/problem_074/sol1.py) * [Sol2](project_euler/problem_074/sol2.py) * Problem 075 * [Sol1](project_euler/problem_075/sol1.py) * Problem 076 * [Sol1](project_euler/problem_076/sol1.py) * Problem 077 * [Sol1](project_euler/problem_077/sol1.py) * Problem 078 * [Sol1](project_euler/problem_078/sol1.py) * Problem 080 * [Sol1](project_euler/problem_080/sol1.py) * Problem 081 * [Sol1](project_euler/problem_081/sol1.py) * Problem 085 * [Sol1](project_euler/problem_085/sol1.py) * Problem 086 * [Sol1](project_euler/problem_086/sol1.py) * Problem 087 * [Sol1](project_euler/problem_087/sol1.py) * Problem 089 * [Sol1](project_euler/problem_089/sol1.py) * Problem 091 * [Sol1](project_euler/problem_091/sol1.py) * Problem 092 * [Sol1](project_euler/problem_092/sol1.py) * Problem 097 * [Sol1](project_euler/problem_097/sol1.py) * Problem 099 * [Sol1](project_euler/problem_099/sol1.py) * Problem 101 * [Sol1](project_euler/problem_101/sol1.py) * Problem 102 * [Sol1](project_euler/problem_102/sol1.py) * Problem 104 * [Sol1](project_euler/problem_104/sol1.py) * Problem 107 * [Sol1](project_euler/problem_107/sol1.py) * Problem 109 * [Sol1](project_euler/problem_109/sol1.py) * Problem 112 * [Sol1](project_euler/problem_112/sol1.py) * Problem 113 * [Sol1](project_euler/problem_113/sol1.py) * Problem 114 * [Sol1](project_euler/problem_114/sol1.py) * Problem 115 * [Sol1](project_euler/problem_115/sol1.py) * Problem 116 * [Sol1](project_euler/problem_116/sol1.py) * Problem 119 * [Sol1](project_euler/problem_119/sol1.py) * Problem 120 * [Sol1](project_euler/problem_120/sol1.py) * Problem 121 * [Sol1](project_euler/problem_121/sol1.py) * Problem 123 * [Sol1](project_euler/problem_123/sol1.py) * Problem 125 * [Sol1](project_euler/problem_125/sol1.py) * Problem 129 * [Sol1](project_euler/problem_129/sol1.py) * Problem 135 * [Sol1](project_euler/problem_135/sol1.py) * Problem 144 * [Sol1](project_euler/problem_144/sol1.py) * Problem 145 * [Sol1](project_euler/problem_145/sol1.py) * Problem 173 * [Sol1](project_euler/problem_173/sol1.py) * Problem 174 * [Sol1](project_euler/problem_174/sol1.py) * Problem 180 * [Sol1](project_euler/problem_180/sol1.py) * Problem 188 * [Sol1](project_euler/problem_188/sol1.py) * Problem 191 * [Sol1](project_euler/problem_191/sol1.py) * Problem 203 * [Sol1](project_euler/problem_203/sol1.py) * Problem 205 * [Sol1](project_euler/problem_205/sol1.py) * Problem 206 * [Sol1](project_euler/problem_206/sol1.py) * Problem 207 * [Sol1](project_euler/problem_207/sol1.py) * Problem 234 * [Sol1](project_euler/problem_234/sol1.py) * Problem 301 * [Sol1](project_euler/problem_301/sol1.py) * Problem 493 * [Sol1](project_euler/problem_493/sol1.py) * Problem 551 * [Sol1](project_euler/problem_551/sol1.py) * Problem 587 * [Sol1](project_euler/problem_587/sol1.py) * Problem 686 * [Sol1](project_euler/problem_686/sol1.py) ## Quantum * [Deutsch Jozsa](quantum/deutsch_jozsa.py) * [Half Adder](quantum/half_adder.py) * [Not Gate](quantum/not_gate.py) * [Q Full Adder](quantum/q_full_adder.py) * [Quantum Entanglement](quantum/quantum_entanglement.py) * [Ripple Adder Classic](quantum/ripple_adder_classic.py) * [Single Qubit Measure](quantum/single_qubit_measure.py) * [Superdense Coding](quantum/superdense_coding.py) ## Scheduling * [First Come First Served](scheduling/first_come_first_served.py) * [Highest Response Ratio Next](scheduling/highest_response_ratio_next.py) * [Job Sequencing With Deadline](scheduling/job_sequencing_with_deadline.py) * [Multi Level Feedback Queue](scheduling/multi_level_feedback_queue.py) * [Non Preemptive Shortest Job First](scheduling/non_preemptive_shortest_job_first.py) * [Round Robin](scheduling/round_robin.py) * [Shortest Job First](scheduling/shortest_job_first.py) ## Searches * [Binary Search](searches/binary_search.py) * [Binary Tree Traversal](searches/binary_tree_traversal.py) * [Double Linear Search](searches/double_linear_search.py) * [Double Linear Search Recursion](searches/double_linear_search_recursion.py) * [Fibonacci Search](searches/fibonacci_search.py) * [Hill Climbing](searches/hill_climbing.py) * [Interpolation Search](searches/interpolation_search.py) * [Jump Search](searches/jump_search.py) * [Linear Search](searches/linear_search.py) * [Quick Select](searches/quick_select.py) * [Sentinel Linear Search](searches/sentinel_linear_search.py) * [Simple Binary Search](searches/simple_binary_search.py) * [Simulated Annealing](searches/simulated_annealing.py) * [Tabu Search](searches/tabu_search.py) * [Ternary Search](searches/ternary_search.py) ## Sorts * [Bead Sort](sorts/bead_sort.py) * [Bitonic Sort](sorts/bitonic_sort.py) * [Bogo Sort](sorts/bogo_sort.py) * [Bubble Sort](sorts/bubble_sort.py) * [Bucket Sort](sorts/bucket_sort.py) * [Circle Sort](sorts/circle_sort.py) * [Cocktail Shaker Sort](sorts/cocktail_shaker_sort.py) * [Comb Sort](sorts/comb_sort.py) * [Counting Sort](sorts/counting_sort.py) * [Cycle Sort](sorts/cycle_sort.py) * [Double Sort](sorts/double_sort.py) * [Dutch National Flag Sort](sorts/dutch_national_flag_sort.py) * [Exchange Sort](sorts/exchange_sort.py) * [External Sort](sorts/external_sort.py) * [Gnome Sort](sorts/gnome_sort.py) * [Heap Sort](sorts/heap_sort.py) * [Insertion Sort](sorts/insertion_sort.py) * [Intro Sort](sorts/intro_sort.py) * [Iterative Merge Sort](sorts/iterative_merge_sort.py) * [Merge Insertion Sort](sorts/merge_insertion_sort.py) * [Merge Sort](sorts/merge_sort.py) * [Msd Radix Sort](sorts/msd_radix_sort.py) * [Natural Sort](sorts/natural_sort.py) * [Odd Even Sort](sorts/odd_even_sort.py) * [Odd Even Transposition Parallel](sorts/odd_even_transposition_parallel.py) * [Odd Even Transposition Single Threaded](sorts/odd_even_transposition_single_threaded.py) * [Pancake Sort](sorts/pancake_sort.py) * [Patience Sort](sorts/patience_sort.py) * [Pigeon Sort](sorts/pigeon_sort.py) * [Pigeonhole Sort](sorts/pigeonhole_sort.py) * [Quick Sort](sorts/quick_sort.py) * [Quick Sort 3 Partition](sorts/quick_sort_3_partition.py) * [Radix Sort](sorts/radix_sort.py) * [Random Normal Distribution Quicksort](sorts/random_normal_distribution_quicksort.py) * [Random Pivot Quick Sort](sorts/random_pivot_quick_sort.py) * [Recursive Bubble Sort](sorts/recursive_bubble_sort.py) * [Recursive Insertion Sort](sorts/recursive_insertion_sort.py) * [Recursive Mergesort Array](sorts/recursive_mergesort_array.py) * [Recursive Quick Sort](sorts/recursive_quick_sort.py) * [Selection Sort](sorts/selection_sort.py) * [Shell Sort](sorts/shell_sort.py) * [Shrink Shell Sort](sorts/shrink_shell_sort.py) * [Slowsort](sorts/slowsort.py) * [Stooge Sort](sorts/stooge_sort.py) * [Strand Sort](sorts/strand_sort.py) * [Tim Sort](sorts/tim_sort.py) * [Topological Sort](sorts/topological_sort.py) * [Tree Sort](sorts/tree_sort.py) * [Unknown Sort](sorts/unknown_sort.py) * [Wiggle Sort](sorts/wiggle_sort.py) ## Strings * [Aho Corasick](strings/aho_corasick.py) * [Alternative String Arrange](strings/alternative_string_arrange.py) * [Anagrams](strings/anagrams.py) * [Autocomplete Using Trie](strings/autocomplete_using_trie.py) * [Barcode Validator](strings/barcode_validator.py) * [Boyer Moore Search](strings/boyer_moore_search.py) * [Can String Be Rearranged As Palindrome](strings/can_string_be_rearranged_as_palindrome.py) * [Capitalize](strings/capitalize.py) * [Check Anagrams](strings/check_anagrams.py) * [Credit Card Validator](strings/credit_card_validator.py) * [Detecting English Programmatically](strings/detecting_english_programmatically.py) * [Dna](strings/dna.py) * [Frequency Finder](strings/frequency_finder.py) * [Hamming Distance](strings/hamming_distance.py) * [Indian Phone Validator](strings/indian_phone_validator.py) * [Is Contains Unique Chars](strings/is_contains_unique_chars.py) * [Is Isogram](strings/is_isogram.py) * [Is Palindrome](strings/is_palindrome.py) * [Is Pangram](strings/is_pangram.py) * [Is Spain National Id](strings/is_spain_national_id.py) * [Jaro Winkler](strings/jaro_winkler.py) * [Join](strings/join.py) * [Knuth Morris Pratt](strings/knuth_morris_pratt.py) * [Levenshtein Distance](strings/levenshtein_distance.py) * [Lower](strings/lower.py) * [Manacher](strings/manacher.py) * [Min Cost String Conversion](strings/min_cost_string_conversion.py) * [Naive String Search](strings/naive_string_search.py) * [Ngram](strings/ngram.py) * [Palindrome](strings/palindrome.py) * [Prefix Function](strings/prefix_function.py) * [Rabin Karp](strings/rabin_karp.py) * [Remove Duplicate](strings/remove_duplicate.py) * [Reverse Letters](strings/reverse_letters.py) * [Reverse Long Words](strings/reverse_long_words.py) * [Reverse Words](strings/reverse_words.py) * [Snake Case To Camel Pascal Case](strings/snake_case_to_camel_pascal_case.py) * [Split](strings/split.py) * [Upper](strings/upper.py) * [Wave](strings/wave.py) * [Wildcard Pattern Matching](strings/wildcard_pattern_matching.py) * [Word Occurrence](strings/word_occurrence.py) * [Word Patterns](strings/word_patterns.py) * [Z Function](strings/z_function.py) ## Web Programming * [Co2 Emission](web_programming/co2_emission.py) * [Covid Stats Via Xpath](web_programming/covid_stats_via_xpath.py) * [Crawl Google Results](web_programming/crawl_google_results.py) * [Crawl Google Scholar Citation](web_programming/crawl_google_scholar_citation.py) * [Currency Converter](web_programming/currency_converter.py) * [Current Stock Price](web_programming/current_stock_price.py) * [Current Weather](web_programming/current_weather.py) * [Daily Horoscope](web_programming/daily_horoscope.py) * [Download Images From Google Query](web_programming/download_images_from_google_query.py) * [Emails From Url](web_programming/emails_from_url.py) * [Fetch Anime And Play](web_programming/fetch_anime_and_play.py) * [Fetch Bbc News](web_programming/fetch_bbc_news.py) * [Fetch Github Info](web_programming/fetch_github_info.py) * [Fetch Jobs](web_programming/fetch_jobs.py) * [Fetch Quotes](web_programming/fetch_quotes.py) * [Fetch Well Rx Price](web_programming/fetch_well_rx_price.py) * [Get Imdb Top 250 Movies Csv](web_programming/get_imdb_top_250_movies_csv.py) * [Get Imdbtop](web_programming/get_imdbtop.py) * [Get Top Billioners](web_programming/get_top_billioners.py) * [Get Top Hn Posts](web_programming/get_top_hn_posts.py) * [Get User Tweets](web_programming/get_user_tweets.py) * [Giphy](web_programming/giphy.py) * [Instagram Crawler](web_programming/instagram_crawler.py) * [Instagram Pic](web_programming/instagram_pic.py) * [Instagram Video](web_programming/instagram_video.py) * [Nasa Data](web_programming/nasa_data.py) * [Open Google Results](web_programming/open_google_results.py) * [Random Anime Character](web_programming/random_anime_character.py) * [Recaptcha Verification](web_programming/recaptcha_verification.py) * [Reddit](web_programming/reddit.py) * [Search Books By Isbn](web_programming/search_books_by_isbn.py) * [Slack Message](web_programming/slack_message.py) * [Test Fetch Github Info](web_programming/test_fetch_github_info.py) * [World Covid19 Stats](web_programming/world_covid19_stats.py)
## Arithmetic Analysis * [Bisection](arithmetic_analysis/bisection.py) * [Gaussian Elimination](arithmetic_analysis/gaussian_elimination.py) * [In Static Equilibrium](arithmetic_analysis/in_static_equilibrium.py) * [Intersection](arithmetic_analysis/intersection.py) * [Jacobi Iteration Method](arithmetic_analysis/jacobi_iteration_method.py) * [Lu Decomposition](arithmetic_analysis/lu_decomposition.py) * [Newton Forward Interpolation](arithmetic_analysis/newton_forward_interpolation.py) * [Newton Method](arithmetic_analysis/newton_method.py) * [Newton Raphson](arithmetic_analysis/newton_raphson.py) * [Newton Raphson New](arithmetic_analysis/newton_raphson_new.py) * [Secant Method](arithmetic_analysis/secant_method.py) ## Audio Filters * [Butterworth Filter](audio_filters/butterworth_filter.py) * [Equal Loudness Filter](audio_filters/equal_loudness_filter.py) * [Iir Filter](audio_filters/iir_filter.py) * [Show Response](audio_filters/show_response.py) ## Backtracking * [All Combinations](backtracking/all_combinations.py) * [All Permutations](backtracking/all_permutations.py) * [All Subsequences](backtracking/all_subsequences.py) * [Coloring](backtracking/coloring.py) * [Combination Sum](backtracking/combination_sum.py) * [Hamiltonian Cycle](backtracking/hamiltonian_cycle.py) * [Knight Tour](backtracking/knight_tour.py) * [Minimax](backtracking/minimax.py) * [Minmax](backtracking/minmax.py) * [N Queens](backtracking/n_queens.py) * [N Queens Math](backtracking/n_queens_math.py) * [Rat In Maze](backtracking/rat_in_maze.py) * [Sudoku](backtracking/sudoku.py) * [Sum Of Subsets](backtracking/sum_of_subsets.py) ## Bit Manipulation * [Binary And Operator](bit_manipulation/binary_and_operator.py) * [Binary Count Setbits](bit_manipulation/binary_count_setbits.py) * [Binary Count Trailing Zeros](bit_manipulation/binary_count_trailing_zeros.py) * [Binary Or Operator](bit_manipulation/binary_or_operator.py) * [Binary Shifts](bit_manipulation/binary_shifts.py) * [Binary Twos Complement](bit_manipulation/binary_twos_complement.py) * [Binary Xor Operator](bit_manipulation/binary_xor_operator.py) * [Count 1S Brian Kernighan Method](bit_manipulation/count_1s_brian_kernighan_method.py) * [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py) * [Gray Code Sequence](bit_manipulation/gray_code_sequence.py) * [Highest Set Bit](bit_manipulation/highest_set_bit.py) * [Is Even](bit_manipulation/is_even.py) * [Reverse Bits](bit_manipulation/reverse_bits.py) * [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py) ## Blockchain * [Chinese Remainder Theorem](blockchain/chinese_remainder_theorem.py) * [Diophantine Equation](blockchain/diophantine_equation.py) * [Modular Division](blockchain/modular_division.py) ## Boolean Algebra * [And Gate](boolean_algebra/and_gate.py) * [Nand Gate](boolean_algebra/nand_gate.py) * [Norgate](boolean_algebra/norgate.py) * [Not Gate](boolean_algebra/not_gate.py) * [Or Gate](boolean_algebra/or_gate.py) * [Quine Mc Cluskey](boolean_algebra/quine_mc_cluskey.py) * [Xnor Gate](boolean_algebra/xnor_gate.py) * [Xor Gate](boolean_algebra/xor_gate.py) ## Cellular Automata * [Conways Game Of Life](cellular_automata/conways_game_of_life.py) * [Game Of Life](cellular_automata/game_of_life.py) * [Nagel Schrekenberg](cellular_automata/nagel_schrekenberg.py) * [One Dimensional](cellular_automata/one_dimensional.py) ## Ciphers * [A1Z26](ciphers/a1z26.py) * [Affine Cipher](ciphers/affine_cipher.py) * [Atbash](ciphers/atbash.py) * [Baconian Cipher](ciphers/baconian_cipher.py) * [Base16](ciphers/base16.py) * [Base32](ciphers/base32.py) * [Base64](ciphers/base64.py) * [Base85](ciphers/base85.py) * [Beaufort Cipher](ciphers/beaufort_cipher.py) * [Bifid](ciphers/bifid.py) * [Brute Force Caesar Cipher](ciphers/brute_force_caesar_cipher.py) * [Caesar Cipher](ciphers/caesar_cipher.py) * [Cryptomath Module](ciphers/cryptomath_module.py) * [Decrypt Caesar With Chi Squared](ciphers/decrypt_caesar_with_chi_squared.py) * [Deterministic Miller Rabin](ciphers/deterministic_miller_rabin.py) * [Diffie](ciphers/diffie.py) * [Diffie Hellman](ciphers/diffie_hellman.py) * [Elgamal Key Generator](ciphers/elgamal_key_generator.py) * [Enigma Machine2](ciphers/enigma_machine2.py) * [Hill Cipher](ciphers/hill_cipher.py) * [Mixed Keyword Cypher](ciphers/mixed_keyword_cypher.py) * [Mono Alphabetic Ciphers](ciphers/mono_alphabetic_ciphers.py) * [Morse Code](ciphers/morse_code.py) * [Onepad Cipher](ciphers/onepad_cipher.py) * [Playfair Cipher](ciphers/playfair_cipher.py) * [Polybius](ciphers/polybius.py) * [Porta Cipher](ciphers/porta_cipher.py) * [Rabin Miller](ciphers/rabin_miller.py) * [Rail Fence Cipher](ciphers/rail_fence_cipher.py) * [Rot13](ciphers/rot13.py) * [Rsa Cipher](ciphers/rsa_cipher.py) * [Rsa Factorization](ciphers/rsa_factorization.py) * [Rsa Key Generator](ciphers/rsa_key_generator.py) * [Shuffled Shift Cipher](ciphers/shuffled_shift_cipher.py) * [Simple Keyword Cypher](ciphers/simple_keyword_cypher.py) * [Simple Substitution Cipher](ciphers/simple_substitution_cipher.py) * [Trafid Cipher](ciphers/trafid_cipher.py) * [Transposition Cipher](ciphers/transposition_cipher.py) * [Transposition Cipher Encrypt Decrypt File](ciphers/transposition_cipher_encrypt_decrypt_file.py) * [Vigenere Cipher](ciphers/vigenere_cipher.py) * [Xor Cipher](ciphers/xor_cipher.py) ## Compression * [Burrows Wheeler](compression/burrows_wheeler.py) * [Huffman](compression/huffman.py) * [Lempel Ziv](compression/lempel_ziv.py) * [Lempel Ziv Decompress](compression/lempel_ziv_decompress.py) * [Peak Signal To Noise Ratio](compression/peak_signal_to_noise_ratio.py) * [Run Length Encoding](compression/run_length_encoding.py) ## Computer Vision * [Cnn Classification](computer_vision/cnn_classification.py) * [Flip Augmentation](computer_vision/flip_augmentation.py) * [Harris Corner](computer_vision/harris_corner.py) * [Horn Schunck](computer_vision/horn_schunck.py) * [Mean Threshold](computer_vision/mean_threshold.py) * [Mosaic Augmentation](computer_vision/mosaic_augmentation.py) * [Pooling Functions](computer_vision/pooling_functions.py) ## Conversions * [Astronomical Length Scale Conversion](conversions/astronomical_length_scale_conversion.py) * [Binary To Decimal](conversions/binary_to_decimal.py) * [Binary To Hexadecimal](conversions/binary_to_hexadecimal.py) * [Binary To Octal](conversions/binary_to_octal.py) * [Decimal To Any](conversions/decimal_to_any.py) * [Decimal To Binary](conversions/decimal_to_binary.py) * [Decimal To Binary Recursion](conversions/decimal_to_binary_recursion.py) * [Decimal To Hexadecimal](conversions/decimal_to_hexadecimal.py) * [Decimal To Octal](conversions/decimal_to_octal.py) * [Excel Title To Column](conversions/excel_title_to_column.py) * [Hex To Bin](conversions/hex_to_bin.py) * [Hexadecimal To Decimal](conversions/hexadecimal_to_decimal.py) * [Length Conversion](conversions/length_conversion.py) * [Molecular Chemistry](conversions/molecular_chemistry.py) * [Octal To Decimal](conversions/octal_to_decimal.py) * [Prefix Conversions](conversions/prefix_conversions.py) * [Prefix Conversions String](conversions/prefix_conversions_string.py) * [Pressure Conversions](conversions/pressure_conversions.py) * [Rgb Hsv Conversion](conversions/rgb_hsv_conversion.py) * [Roman Numerals](conversions/roman_numerals.py) * [Speed Conversions](conversions/speed_conversions.py) * [Temperature Conversions](conversions/temperature_conversions.py) * [Volume Conversions](conversions/volume_conversions.py) * [Weight Conversion](conversions/weight_conversion.py) ## Data Structures * Binary Tree * [Avl Tree](data_structures/binary_tree/avl_tree.py) * [Basic Binary Tree](data_structures/binary_tree/basic_binary_tree.py) * [Binary Search Tree](data_structures/binary_tree/binary_search_tree.py) * [Binary Search Tree Recursive](data_structures/binary_tree/binary_search_tree_recursive.py) * [Binary Tree Mirror](data_structures/binary_tree/binary_tree_mirror.py) * [Binary Tree Node Sum](data_structures/binary_tree/binary_tree_node_sum.py) * [Binary Tree Traversals](data_structures/binary_tree/binary_tree_traversals.py) * [Diff Views Of Binary Tree](data_structures/binary_tree/diff_views_of_binary_tree.py) * [Fenwick Tree](data_structures/binary_tree/fenwick_tree.py) * [Inorder Tree Traversal 2022](data_structures/binary_tree/inorder_tree_traversal_2022.py) * [Lazy Segment Tree](data_structures/binary_tree/lazy_segment_tree.py) * [Lowest Common Ancestor](data_structures/binary_tree/lowest_common_ancestor.py) * [Maximum Fenwick Tree](data_structures/binary_tree/maximum_fenwick_tree.py) * [Merge Two Binary Trees](data_structures/binary_tree/merge_two_binary_trees.py) * [Non Recursive Segment Tree](data_structures/binary_tree/non_recursive_segment_tree.py) * [Number Of Possible Binary Trees](data_structures/binary_tree/number_of_possible_binary_trees.py) * [Red Black Tree](data_structures/binary_tree/red_black_tree.py) * [Segment Tree](data_structures/binary_tree/segment_tree.py) * [Segment Tree Other](data_structures/binary_tree/segment_tree_other.py) * [Treap](data_structures/binary_tree/treap.py) * [Wavelet Tree](data_structures/binary_tree/wavelet_tree.py) * Disjoint Set * [Alternate Disjoint Set](data_structures/disjoint_set/alternate_disjoint_set.py) * [Disjoint Set](data_structures/disjoint_set/disjoint_set.py) * Hashing * [Double Hash](data_structures/hashing/double_hash.py) * [Hash Table](data_structures/hashing/hash_table.py) * [Hash Table With Linked List](data_structures/hashing/hash_table_with_linked_list.py) * Number Theory * [Prime Numbers](data_structures/hashing/number_theory/prime_numbers.py) * [Quadratic Probing](data_structures/hashing/quadratic_probing.py) * Heap * [Binomial Heap](data_structures/heap/binomial_heap.py) * [Heap](data_structures/heap/heap.py) * [Heap Generic](data_structures/heap/heap_generic.py) * [Max Heap](data_structures/heap/max_heap.py) * [Min Heap](data_structures/heap/min_heap.py) * [Randomized Heap](data_structures/heap/randomized_heap.py) * [Skew Heap](data_structures/heap/skew_heap.py) * Linked List * [Circular Linked List](data_structures/linked_list/circular_linked_list.py) * [Deque Doubly](data_structures/linked_list/deque_doubly.py) * [Doubly Linked List](data_structures/linked_list/doubly_linked_list.py) * [Doubly Linked List Two](data_structures/linked_list/doubly_linked_list_two.py) * [From Sequence](data_structures/linked_list/from_sequence.py) * [Has Loop](data_structures/linked_list/has_loop.py) * [Is Palindrome](data_structures/linked_list/is_palindrome.py) * [Merge Two Lists](data_structures/linked_list/merge_two_lists.py) * [Middle Element Of Linked List](data_structures/linked_list/middle_element_of_linked_list.py) * [Print Reverse](data_structures/linked_list/print_reverse.py) * [Singly Linked List](data_structures/linked_list/singly_linked_list.py) * [Skip List](data_structures/linked_list/skip_list.py) * [Swap Nodes](data_structures/linked_list/swap_nodes.py) * Queue * [Circular Queue](data_structures/queue/circular_queue.py) * [Circular Queue Linked List](data_structures/queue/circular_queue_linked_list.py) * [Double Ended Queue](data_structures/queue/double_ended_queue.py) * [Linked Queue](data_structures/queue/linked_queue.py) * [Priority Queue Using List](data_structures/queue/priority_queue_using_list.py) * [Queue On List](data_structures/queue/queue_on_list.py) * [Queue On Pseudo Stack](data_structures/queue/queue_on_pseudo_stack.py) * Stacks * [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py) * [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py) * [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py) * [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py) * [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py) * [Next Greater Element](data_structures/stacks/next_greater_element.py) * [Postfix Evaluation](data_structures/stacks/postfix_evaluation.py) * [Prefix Evaluation](data_structures/stacks/prefix_evaluation.py) * [Stack](data_structures/stacks/stack.py) * [Stack With Doubly Linked List](data_structures/stacks/stack_with_doubly_linked_list.py) * [Stack With Singly Linked List](data_structures/stacks/stack_with_singly_linked_list.py) * [Stock Span Problem](data_structures/stacks/stock_span_problem.py) * Trie * [Trie](data_structures/trie/trie.py) ## Digital Image Processing * [Change Brightness](digital_image_processing/change_brightness.py) * [Change Contrast](digital_image_processing/change_contrast.py) * [Convert To Negative](digital_image_processing/convert_to_negative.py) * Dithering * [Burkes](digital_image_processing/dithering/burkes.py) * Edge Detection * [Canny](digital_image_processing/edge_detection/canny.py) * Filters * [Bilateral Filter](digital_image_processing/filters/bilateral_filter.py) * [Convolve](digital_image_processing/filters/convolve.py) * [Gabor Filter](digital_image_processing/filters/gabor_filter.py) * [Gaussian Filter](digital_image_processing/filters/gaussian_filter.py) * [Local Binary Pattern](digital_image_processing/filters/local_binary_pattern.py) * [Median Filter](digital_image_processing/filters/median_filter.py) * [Sobel Filter](digital_image_processing/filters/sobel_filter.py) * Histogram Equalization * [Histogram Stretch](digital_image_processing/histogram_equalization/histogram_stretch.py) * [Index Calculation](digital_image_processing/index_calculation.py) * Morphological Operations * [Dilation Operation](digital_image_processing/morphological_operations/dilation_operation.py) * [Erosion Operation](digital_image_processing/morphological_operations/erosion_operation.py) * Resize * [Resize](digital_image_processing/resize/resize.py) * Rotation * [Rotation](digital_image_processing/rotation/rotation.py) * [Sepia](digital_image_processing/sepia.py) * [Test Digital Image Processing](digital_image_processing/test_digital_image_processing.py) ## Divide And Conquer * [Closest Pair Of Points](divide_and_conquer/closest_pair_of_points.py) * [Convex Hull](divide_and_conquer/convex_hull.py) * [Heaps Algorithm](divide_and_conquer/heaps_algorithm.py) * [Heaps Algorithm Iterative](divide_and_conquer/heaps_algorithm_iterative.py) * [Inversions](divide_and_conquer/inversions.py) * [Kth Order Statistic](divide_and_conquer/kth_order_statistic.py) * [Max Difference Pair](divide_and_conquer/max_difference_pair.py) * [Max Subarray Sum](divide_and_conquer/max_subarray_sum.py) * [Mergesort](divide_and_conquer/mergesort.py) * [Peak](divide_and_conquer/peak.py) * [Power](divide_and_conquer/power.py) * [Strassen Matrix Multiplication](divide_and_conquer/strassen_matrix_multiplication.py) ## Dynamic Programming * [Abbreviation](dynamic_programming/abbreviation.py) * [All Construct](dynamic_programming/all_construct.py) * [Bitmask](dynamic_programming/bitmask.py) * [Catalan Numbers](dynamic_programming/catalan_numbers.py) * [Climbing Stairs](dynamic_programming/climbing_stairs.py) * [Edit Distance](dynamic_programming/edit_distance.py) * [Factorial](dynamic_programming/factorial.py) * [Fast Fibonacci](dynamic_programming/fast_fibonacci.py) * [Fibonacci](dynamic_programming/fibonacci.py) * [Floyd Warshall](dynamic_programming/floyd_warshall.py) * [Integer Partition](dynamic_programming/integer_partition.py) * [Iterating Through Submasks](dynamic_programming/iterating_through_submasks.py) * [Knapsack](dynamic_programming/knapsack.py) * [Longest Common Subsequence](dynamic_programming/longest_common_subsequence.py) * [Longest Common Substring](dynamic_programming/longest_common_substring.py) * [Longest Increasing Subsequence](dynamic_programming/longest_increasing_subsequence.py) * [Longest Increasing Subsequence O(Nlogn)](dynamic_programming/longest_increasing_subsequence_o(nlogn).py) * [Longest Sub Array](dynamic_programming/longest_sub_array.py) * [Matrix Chain Order](dynamic_programming/matrix_chain_order.py) * [Max Non Adjacent Sum](dynamic_programming/max_non_adjacent_sum.py) * [Max Sub Array](dynamic_programming/max_sub_array.py) * [Max Sum Contiguous Subsequence](dynamic_programming/max_sum_contiguous_subsequence.py) * [Minimum Coin Change](dynamic_programming/minimum_coin_change.py) * [Minimum Cost Path](dynamic_programming/minimum_cost_path.py) * [Minimum Partition](dynamic_programming/minimum_partition.py) * [Minimum Squares To Represent A Number](dynamic_programming/minimum_squares_to_represent_a_number.py) * [Minimum Steps To One](dynamic_programming/minimum_steps_to_one.py) * [Optimal Binary Search Tree](dynamic_programming/optimal_binary_search_tree.py) * [Rod Cutting](dynamic_programming/rod_cutting.py) * [Subset Generation](dynamic_programming/subset_generation.py) * [Sum Of Subset](dynamic_programming/sum_of_subset.py) ## Electronics * [Carrier Concentration](electronics/carrier_concentration.py) * [Coulombs Law](electronics/coulombs_law.py) * [Electric Power](electronics/electric_power.py) * [Ohms Law](electronics/ohms_law.py) ## File Transfer * [Receive File](file_transfer/receive_file.py) * [Send File](file_transfer/send_file.py) * Tests * [Test Send File](file_transfer/tests/test_send_file.py) ## Financial * [Equated Monthly Installments](financial/equated_monthly_installments.py) * [Interest](financial/interest.py) * [Price Plus Tax](financial/price_plus_tax.py) ## Fractals * [Julia Sets](fractals/julia_sets.py) * [Koch Snowflake](fractals/koch_snowflake.py) * [Mandelbrot](fractals/mandelbrot.py) * [Sierpinski Triangle](fractals/sierpinski_triangle.py) ## Fuzzy Logic * [Fuzzy Operations](fuzzy_logic/fuzzy_operations.py) ## Genetic Algorithm * [Basic String](genetic_algorithm/basic_string.py) ## Geodesy * [Haversine Distance](geodesy/haversine_distance.py) * [Lamberts Ellipsoidal Distance](geodesy/lamberts_ellipsoidal_distance.py) ## Graphics * [Bezier Curve](graphics/bezier_curve.py) * [Vector3 For 2D Rendering](graphics/vector3_for_2d_rendering.py) ## Graphs * [A Star](graphs/a_star.py) * [Articulation Points](graphs/articulation_points.py) * [Basic Graphs](graphs/basic_graphs.py) * [Bellman Ford](graphs/bellman_ford.py) * [Bfs Shortest Path](graphs/bfs_shortest_path.py) * [Bfs Zero One Shortest Path](graphs/bfs_zero_one_shortest_path.py) * [Bidirectional A Star](graphs/bidirectional_a_star.py) * [Bidirectional Breadth First Search](graphs/bidirectional_breadth_first_search.py) * [Boruvka](graphs/boruvka.py) * [Breadth First Search](graphs/breadth_first_search.py) * [Breadth First Search 2](graphs/breadth_first_search_2.py) * [Breadth First Search Shortest Path](graphs/breadth_first_search_shortest_path.py) * [Check Bipartite Graph Bfs](graphs/check_bipartite_graph_bfs.py) * [Check Bipartite Graph Dfs](graphs/check_bipartite_graph_dfs.py) * [Check Cycle](graphs/check_cycle.py) * [Connected Components](graphs/connected_components.py) * [Depth First Search](graphs/depth_first_search.py) * [Depth First Search 2](graphs/depth_first_search_2.py) * [Dijkstra](graphs/dijkstra.py) * [Dijkstra 2](graphs/dijkstra_2.py) * [Dijkstra Algorithm](graphs/dijkstra_algorithm.py) * [Dijkstra Alternate](graphs/dijkstra_alternate.py) * [Dinic](graphs/dinic.py) * [Directed And Undirected (Weighted) Graph](graphs/directed_and_undirected_(weighted)_graph.py) * [Edmonds Karp Multiple Source And Sink](graphs/edmonds_karp_multiple_source_and_sink.py) * [Eulerian Path And Circuit For Undirected Graph](graphs/eulerian_path_and_circuit_for_undirected_graph.py) * [Even Tree](graphs/even_tree.py) * [Finding Bridges](graphs/finding_bridges.py) * [Frequent Pattern Graph Miner](graphs/frequent_pattern_graph_miner.py) * [G Topological Sort](graphs/g_topological_sort.py) * [Gale Shapley Bigraph](graphs/gale_shapley_bigraph.py) * [Graph List](graphs/graph_list.py) * [Graph Matrix](graphs/graph_matrix.py) * [Graphs Floyd Warshall](graphs/graphs_floyd_warshall.py) * [Greedy Best First](graphs/greedy_best_first.py) * [Greedy Min Vertex Cover](graphs/greedy_min_vertex_cover.py) * [Kahns Algorithm Long](graphs/kahns_algorithm_long.py) * [Kahns Algorithm Topo](graphs/kahns_algorithm_topo.py) * [Karger](graphs/karger.py) * [Markov Chain](graphs/markov_chain.py) * [Matching Min Vertex Cover](graphs/matching_min_vertex_cover.py) * [Minimum Path Sum](graphs/minimum_path_sum.py) * [Minimum Spanning Tree Boruvka](graphs/minimum_spanning_tree_boruvka.py) * [Minimum Spanning Tree Kruskal](graphs/minimum_spanning_tree_kruskal.py) * [Minimum Spanning Tree Kruskal2](graphs/minimum_spanning_tree_kruskal2.py) * [Minimum Spanning Tree Prims](graphs/minimum_spanning_tree_prims.py) * [Minimum Spanning Tree Prims2](graphs/minimum_spanning_tree_prims2.py) * [Multi Heuristic Astar](graphs/multi_heuristic_astar.py) * [Page Rank](graphs/page_rank.py) * [Prim](graphs/prim.py) * [Random Graph Generator](graphs/random_graph_generator.py) * [Scc Kosaraju](graphs/scc_kosaraju.py) * [Strongly Connected Components](graphs/strongly_connected_components.py) * [Tarjans Scc](graphs/tarjans_scc.py) * Tests * [Test Min Spanning Tree Kruskal](graphs/tests/test_min_spanning_tree_kruskal.py) * [Test Min Spanning Tree Prim](graphs/tests/test_min_spanning_tree_prim.py) ## Greedy Methods * [Fractional Knapsack](greedy_methods/fractional_knapsack.py) * [Fractional Knapsack 2](greedy_methods/fractional_knapsack_2.py) * [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py) ## Hashes * [Adler32](hashes/adler32.py) * [Chaos Machine](hashes/chaos_machine.py) * [Djb2](hashes/djb2.py) * [Enigma Machine](hashes/enigma_machine.py) * [Hamming Code](hashes/hamming_code.py) * [Luhn](hashes/luhn.py) * [Md5](hashes/md5.py) * [Sdbm](hashes/sdbm.py) * [Sha1](hashes/sha1.py) * [Sha256](hashes/sha256.py) ## Knapsack * [Greedy Knapsack](knapsack/greedy_knapsack.py) * [Knapsack](knapsack/knapsack.py) * Tests * [Test Greedy Knapsack](knapsack/tests/test_greedy_knapsack.py) * [Test Knapsack](knapsack/tests/test_knapsack.py) ## Linear Algebra * Src * [Conjugate Gradient](linear_algebra/src/conjugate_gradient.py) * [Lib](linear_algebra/src/lib.py) * [Polynom For Points](linear_algebra/src/polynom_for_points.py) * [Power Iteration](linear_algebra/src/power_iteration.py) * [Rayleigh Quotient](linear_algebra/src/rayleigh_quotient.py) * [Schur Complement](linear_algebra/src/schur_complement.py) * [Test Linear Algebra](linear_algebra/src/test_linear_algebra.py) * [Transformations 2D](linear_algebra/src/transformations_2d.py) ## Machine Learning * [Astar](machine_learning/astar.py) * [Data Transformations](machine_learning/data_transformations.py) * [Decision Tree](machine_learning/decision_tree.py) * Forecasting * [Run](machine_learning/forecasting/run.py) * [Gaussian Naive Bayes](machine_learning/gaussian_naive_bayes.py) * [Gradient Boosting Regressor](machine_learning/gradient_boosting_regressor.py) * [Gradient Descent](machine_learning/gradient_descent.py) * [K Means Clust](machine_learning/k_means_clust.py) * [K Nearest Neighbours](machine_learning/k_nearest_neighbours.py) * [Knn Sklearn](machine_learning/knn_sklearn.py) * [Linear Discriminant Analysis](machine_learning/linear_discriminant_analysis.py) * [Linear Regression](machine_learning/linear_regression.py) * Local Weighted Learning * [Local Weighted Learning](machine_learning/local_weighted_learning/local_weighted_learning.py) * [Logistic Regression](machine_learning/logistic_regression.py) * Lstm * [Lstm Prediction](machine_learning/lstm/lstm_prediction.py) * [Multilayer Perceptron Classifier](machine_learning/multilayer_perceptron_classifier.py) * [Polymonial Regression](machine_learning/polymonial_regression.py) * [Random Forest Classifier](machine_learning/random_forest_classifier.py) * [Random Forest Regressor](machine_learning/random_forest_regressor.py) * [Scoring Functions](machine_learning/scoring_functions.py) * [Self Organizing Map](machine_learning/self_organizing_map.py) * [Sequential Minimum Optimization](machine_learning/sequential_minimum_optimization.py) * [Similarity Search](machine_learning/similarity_search.py) * [Support Vector Machines](machine_learning/support_vector_machines.py) * [Word Frequency Functions](machine_learning/word_frequency_functions.py) * [Xgboost Classifier](machine_learning/xgboost_classifier.py) * [Xgboost Regressor](machine_learning/xgboost_regressor.py) ## Maths * [3N Plus 1](maths/3n_plus_1.py) * [Abs](maths/abs.py) * [Abs Max](maths/abs_max.py) * [Abs Min](maths/abs_min.py) * [Add](maths/add.py) * [Aliquot Sum](maths/aliquot_sum.py) * [Allocation Number](maths/allocation_number.py) * [Arc Length](maths/arc_length.py) * [Area](maths/area.py) * [Area Under Curve](maths/area_under_curve.py) * [Armstrong Numbers](maths/armstrong_numbers.py) * [Average Absolute Deviation](maths/average_absolute_deviation.py) * [Average Mean](maths/average_mean.py) * [Average Median](maths/average_median.py) * [Average Mode](maths/average_mode.py) * [Bailey Borwein Plouffe](maths/bailey_borwein_plouffe.py) * [Basic Maths](maths/basic_maths.py) * [Binary Exp Mod](maths/binary_exp_mod.py) * [Binary Exponentiation](maths/binary_exponentiation.py) * [Binary Exponentiation 2](maths/binary_exponentiation_2.py) * [Binary Exponentiation 3](maths/binary_exponentiation_3.py) * [Binomial Coefficient](maths/binomial_coefficient.py) * [Binomial Distribution](maths/binomial_distribution.py) * [Bisection](maths/bisection.py) * [Carmichael Number](maths/carmichael_number.py) * [Catalan Number](maths/catalan_number.py) * [Ceil](maths/ceil.py) * [Check Polygon](maths/check_polygon.py) * [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py) * [Collatz Sequence](maths/collatz_sequence.py) * [Combinations](maths/combinations.py) * [Decimal Isolate](maths/decimal_isolate.py) * [Double Factorial Iterative](maths/double_factorial_iterative.py) * [Double Factorial Recursive](maths/double_factorial_recursive.py) * [Entropy](maths/entropy.py) * [Euclidean Distance](maths/euclidean_distance.py) * [Euclidean Gcd](maths/euclidean_gcd.py) * [Euler Method](maths/euler_method.py) * [Euler Modified](maths/euler_modified.py) * [Eulers Totient](maths/eulers_totient.py) * [Extended Euclidean Algorithm](maths/extended_euclidean_algorithm.py) * [Factorial Iterative](maths/factorial_iterative.py) * [Factorial Recursive](maths/factorial_recursive.py) * [Factors](maths/factors.py) * [Fermat Little Theorem](maths/fermat_little_theorem.py) * [Fibonacci](maths/fibonacci.py) * [Find Max](maths/find_max.py) * [Find Max Recursion](maths/find_max_recursion.py) * [Find Min](maths/find_min.py) * [Find Min Recursion](maths/find_min_recursion.py) * [Floor](maths/floor.py) * [Gamma](maths/gamma.py) * [Gamma Recursive](maths/gamma_recursive.py) * [Gaussian](maths/gaussian.py) * [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py) * [Greatest Common Divisor](maths/greatest_common_divisor.py) * [Greedy Coin Change](maths/greedy_coin_change.py) * [Hamming Numbers](maths/hamming_numbers.py) * [Hardy Ramanujanalgo](maths/hardy_ramanujanalgo.py) * [Integration By Simpson Approx](maths/integration_by_simpson_approx.py) * [Is Ip V4 Address Valid](maths/is_ip_v4_address_valid.py) * [Is Square Free](maths/is_square_free.py) * [Jaccard Similarity](maths/jaccard_similarity.py) * [Kadanes](maths/kadanes.py) * [Karatsuba](maths/karatsuba.py) * [Krishnamurthy Number](maths/krishnamurthy_number.py) * [Kth Lexicographic Permutation](maths/kth_lexicographic_permutation.py) * [Largest Of Very Large Numbers](maths/largest_of_very_large_numbers.py) * [Largest Subarray Sum](maths/largest_subarray_sum.py) * [Least Common Multiple](maths/least_common_multiple.py) * [Line Length](maths/line_length.py) * [Lucas Lehmer Primality Test](maths/lucas_lehmer_primality_test.py) * [Lucas Series](maths/lucas_series.py) * [Maclaurin Series](maths/maclaurin_series.py) * [Matrix Exponentiation](maths/matrix_exponentiation.py) * [Max Sum Sliding Window](maths/max_sum_sliding_window.py) * [Median Of Two Arrays](maths/median_of_two_arrays.py) * [Miller Rabin](maths/miller_rabin.py) * [Mobius Function](maths/mobius_function.py) * [Modular Exponential](maths/modular_exponential.py) * [Monte Carlo](maths/monte_carlo.py) * [Monte Carlo Dice](maths/monte_carlo_dice.py) * [Nevilles Method](maths/nevilles_method.py) * [Newton Raphson](maths/newton_raphson.py) * [Number Of Digits](maths/number_of_digits.py) * [Numerical Integration](maths/numerical_integration.py) * [Perfect Cube](maths/perfect_cube.py) * [Perfect Number](maths/perfect_number.py) * [Perfect Square](maths/perfect_square.py) * [Persistence](maths/persistence.py) * [Pi Monte Carlo Estimation](maths/pi_monte_carlo_estimation.py) * [Points Are Collinear 3D](maths/points_are_collinear_3d.py) * [Pollard Rho](maths/pollard_rho.py) * [Polynomial Evaluation](maths/polynomial_evaluation.py) * [Power Using Recursion](maths/power_using_recursion.py) * [Prime Check](maths/prime_check.py) * [Prime Factors](maths/prime_factors.py) * [Prime Numbers](maths/prime_numbers.py) * [Prime Sieve Eratosthenes](maths/prime_sieve_eratosthenes.py) * [Primelib](maths/primelib.py) * [Proth Number](maths/proth_number.py) * [Pythagoras](maths/pythagoras.py) * [Qr Decomposition](maths/qr_decomposition.py) * [Quadratic Equations Complex Numbers](maths/quadratic_equations_complex_numbers.py) * [Radians](maths/radians.py) * [Radix2 Fft](maths/radix2_fft.py) * [Relu](maths/relu.py) * [Runge Kutta](maths/runge_kutta.py) * [Segmented Sieve](maths/segmented_sieve.py) * Series * [Arithmetic](maths/series/arithmetic.py) * [Geometric](maths/series/geometric.py) * [Geometric Series](maths/series/geometric_series.py) * [Harmonic](maths/series/harmonic.py) * [Harmonic Series](maths/series/harmonic_series.py) * [Hexagonal Numbers](maths/series/hexagonal_numbers.py) * [P Series](maths/series/p_series.py) * [Sieve Of Eratosthenes](maths/sieve_of_eratosthenes.py) * [Sigmoid](maths/sigmoid.py) * [Signum](maths/signum.py) * [Simpson Rule](maths/simpson_rule.py) * [Sin](maths/sin.py) * [Sock Merchant](maths/sock_merchant.py) * [Softmax](maths/softmax.py) * [Square Root](maths/square_root.py) * [Sum Of Arithmetic Series](maths/sum_of_arithmetic_series.py) * [Sum Of Digits](maths/sum_of_digits.py) * [Sum Of Geometric Progression](maths/sum_of_geometric_progression.py) * [Sum Of Harmonic Series](maths/sum_of_harmonic_series.py) * [Sylvester Sequence](maths/sylvester_sequence.py) * [Test Prime Check](maths/test_prime_check.py) * [Trapezoidal Rule](maths/trapezoidal_rule.py) * [Triplet Sum](maths/triplet_sum.py) * [Two Pointer](maths/two_pointer.py) * [Two Sum](maths/two_sum.py) * [Ugly Numbers](maths/ugly_numbers.py) * [Volume](maths/volume.py) * [Weird Number](maths/weird_number.py) * [Zellers Congruence](maths/zellers_congruence.py) ## Matrix * [Binary Search Matrix](matrix/binary_search_matrix.py) * [Count Islands In Matrix](matrix/count_islands_in_matrix.py) * [Cramers Rule 2X2](matrix/cramers_rule_2x2.py) * [Inverse Of Matrix](matrix/inverse_of_matrix.py) * [Largest Square Area In Matrix](matrix/largest_square_area_in_matrix.py) * [Matrix Class](matrix/matrix_class.py) * [Matrix Operation](matrix/matrix_operation.py) * [Max Area Of Island](matrix/max_area_of_island.py) * [Nth Fibonacci Using Matrix Exponentiation](matrix/nth_fibonacci_using_matrix_exponentiation.py) * [Rotate Matrix](matrix/rotate_matrix.py) * [Searching In Sorted Matrix](matrix/searching_in_sorted_matrix.py) * [Sherman Morrison](matrix/sherman_morrison.py) * [Spiral Print](matrix/spiral_print.py) * Tests * [Test Matrix Operation](matrix/tests/test_matrix_operation.py) ## Networking Flow * [Ford Fulkerson](networking_flow/ford_fulkerson.py) * [Minimum Cut](networking_flow/minimum_cut.py) ## Neural Network * [2 Hidden Layers Neural Network](neural_network/2_hidden_layers_neural_network.py) * [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py) * [Convolution Neural Network](neural_network/convolution_neural_network.py) * [Perceptron](neural_network/perceptron.py) ## Other * [Activity Selection](other/activity_selection.py) * [Alternative List Arrange](other/alternative_list_arrange.py) * [Check Strong Password](other/check_strong_password.py) * [Davisb Putnamb Logemannb Loveland](other/davisb_putnamb_logemannb_loveland.py) * [Dijkstra Bankers Algorithm](other/dijkstra_bankers_algorithm.py) * [Doomsday](other/doomsday.py) * [Fischer Yates Shuffle](other/fischer_yates_shuffle.py) * [Gauss Easter](other/gauss_easter.py) * [Graham Scan](other/graham_scan.py) * [Greedy](other/greedy.py) * [Least Recently Used](other/least_recently_used.py) * [Lfu Cache](other/lfu_cache.py) * [Linear Congruential Generator](other/linear_congruential_generator.py) * [Lru Cache](other/lru_cache.py) * [Magicdiamondpattern](other/magicdiamondpattern.py) * [Maximum Subarray](other/maximum_subarray.py) * [Nested Brackets](other/nested_brackets.py) * [Password Generator](other/password_generator.py) * [Scoring Algorithm](other/scoring_algorithm.py) * [Sdes](other/sdes.py) * [Tower Of Hanoi](other/tower_of_hanoi.py) ## Physics * [Casimir Effect](physics/casimir_effect.py) * [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py) * [Kinetic Energy](physics/kinetic_energy.py) * [Lorentz Transformation Four Vector](physics/lorentz_transformation_four_vector.py) * [Malus Law](physics/malus_law.py) * [N Body Simulation](physics/n_body_simulation.py) * [Newtons Law Of Gravitation](physics/newtons_law_of_gravitation.py) * [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py) ## Project Euler * Problem 001 * [Sol1](project_euler/problem_001/sol1.py) * [Sol2](project_euler/problem_001/sol2.py) * [Sol3](project_euler/problem_001/sol3.py) * [Sol4](project_euler/problem_001/sol4.py) * [Sol5](project_euler/problem_001/sol5.py) * [Sol6](project_euler/problem_001/sol6.py) * [Sol7](project_euler/problem_001/sol7.py) * Problem 002 * [Sol1](project_euler/problem_002/sol1.py) * [Sol2](project_euler/problem_002/sol2.py) * [Sol3](project_euler/problem_002/sol3.py) * [Sol4](project_euler/problem_002/sol4.py) * [Sol5](project_euler/problem_002/sol5.py) * Problem 003 * [Sol1](project_euler/problem_003/sol1.py) * [Sol2](project_euler/problem_003/sol2.py) * [Sol3](project_euler/problem_003/sol3.py) * Problem 004 * [Sol1](project_euler/problem_004/sol1.py) * [Sol2](project_euler/problem_004/sol2.py) * Problem 005 * [Sol1](project_euler/problem_005/sol1.py) * [Sol2](project_euler/problem_005/sol2.py) * Problem 006 * [Sol1](project_euler/problem_006/sol1.py) * [Sol2](project_euler/problem_006/sol2.py) * [Sol3](project_euler/problem_006/sol3.py) * [Sol4](project_euler/problem_006/sol4.py) * Problem 007 * [Sol1](project_euler/problem_007/sol1.py) * [Sol2](project_euler/problem_007/sol2.py) * [Sol3](project_euler/problem_007/sol3.py) * Problem 008 * [Sol1](project_euler/problem_008/sol1.py) * [Sol2](project_euler/problem_008/sol2.py) * [Sol3](project_euler/problem_008/sol3.py) * Problem 009 * [Sol1](project_euler/problem_009/sol1.py) * [Sol2](project_euler/problem_009/sol2.py) * [Sol3](project_euler/problem_009/sol3.py) * Problem 010 * [Sol1](project_euler/problem_010/sol1.py) * [Sol2](project_euler/problem_010/sol2.py) * [Sol3](project_euler/problem_010/sol3.py) * Problem 011 * [Sol1](project_euler/problem_011/sol1.py) * [Sol2](project_euler/problem_011/sol2.py) * Problem 012 * [Sol1](project_euler/problem_012/sol1.py) * [Sol2](project_euler/problem_012/sol2.py) * Problem 013 * [Sol1](project_euler/problem_013/sol1.py) * Problem 014 * [Sol1](project_euler/problem_014/sol1.py) * [Sol2](project_euler/problem_014/sol2.py) * Problem 015 * [Sol1](project_euler/problem_015/sol1.py) * Problem 016 * [Sol1](project_euler/problem_016/sol1.py) * [Sol2](project_euler/problem_016/sol2.py) * Problem 017 * [Sol1](project_euler/problem_017/sol1.py) * Problem 018 * [Solution](project_euler/problem_018/solution.py) * Problem 019 * [Sol1](project_euler/problem_019/sol1.py) * Problem 020 * [Sol1](project_euler/problem_020/sol1.py) * [Sol2](project_euler/problem_020/sol2.py) * [Sol3](project_euler/problem_020/sol3.py) * [Sol4](project_euler/problem_020/sol4.py) * Problem 021 * [Sol1](project_euler/problem_021/sol1.py) * Problem 022 * [Sol1](project_euler/problem_022/sol1.py) * [Sol2](project_euler/problem_022/sol2.py) * Problem 023 * [Sol1](project_euler/problem_023/sol1.py) * Problem 024 * [Sol1](project_euler/problem_024/sol1.py) * Problem 025 * [Sol1](project_euler/problem_025/sol1.py) * [Sol2](project_euler/problem_025/sol2.py) * [Sol3](project_euler/problem_025/sol3.py) * Problem 026 * [Sol1](project_euler/problem_026/sol1.py) * Problem 027 * [Sol1](project_euler/problem_027/sol1.py) * Problem 028 * [Sol1](project_euler/problem_028/sol1.py) * Problem 029 * [Sol1](project_euler/problem_029/sol1.py) * Problem 030 * [Sol1](project_euler/problem_030/sol1.py) * Problem 031 * [Sol1](project_euler/problem_031/sol1.py) * [Sol2](project_euler/problem_031/sol2.py) * Problem 032 * [Sol32](project_euler/problem_032/sol32.py) * Problem 033 * [Sol1](project_euler/problem_033/sol1.py) * Problem 034 * [Sol1](project_euler/problem_034/sol1.py) * Problem 035 * [Sol1](project_euler/problem_035/sol1.py) * Problem 036 * [Sol1](project_euler/problem_036/sol1.py) * Problem 037 * [Sol1](project_euler/problem_037/sol1.py) * Problem 038 * [Sol1](project_euler/problem_038/sol1.py) * Problem 039 * [Sol1](project_euler/problem_039/sol1.py) * Problem 040 * [Sol1](project_euler/problem_040/sol1.py) * Problem 041 * [Sol1](project_euler/problem_041/sol1.py) * Problem 042 * [Solution42](project_euler/problem_042/solution42.py) * Problem 043 * [Sol1](project_euler/problem_043/sol1.py) * Problem 044 * [Sol1](project_euler/problem_044/sol1.py) * Problem 045 * [Sol1](project_euler/problem_045/sol1.py) * Problem 046 * [Sol1](project_euler/problem_046/sol1.py) * Problem 047 * [Sol1](project_euler/problem_047/sol1.py) * Problem 048 * [Sol1](project_euler/problem_048/sol1.py) * Problem 049 * [Sol1](project_euler/problem_049/sol1.py) * Problem 050 * [Sol1](project_euler/problem_050/sol1.py) * Problem 051 * [Sol1](project_euler/problem_051/sol1.py) * Problem 052 * [Sol1](project_euler/problem_052/sol1.py) * Problem 053 * [Sol1](project_euler/problem_053/sol1.py) * Problem 054 * [Sol1](project_euler/problem_054/sol1.py) * [Test Poker Hand](project_euler/problem_054/test_poker_hand.py) * Problem 055 * [Sol1](project_euler/problem_055/sol1.py) * Problem 056 * [Sol1](project_euler/problem_056/sol1.py) * Problem 057 * [Sol1](project_euler/problem_057/sol1.py) * Problem 058 * [Sol1](project_euler/problem_058/sol1.py) * Problem 059 * [Sol1](project_euler/problem_059/sol1.py) * Problem 062 * [Sol1](project_euler/problem_062/sol1.py) * Problem 063 * [Sol1](project_euler/problem_063/sol1.py) * Problem 064 * [Sol1](project_euler/problem_064/sol1.py) * Problem 065 * [Sol1](project_euler/problem_065/sol1.py) * Problem 067 * [Sol1](project_euler/problem_067/sol1.py) * [Sol2](project_euler/problem_067/sol2.py) * Problem 068 * [Sol1](project_euler/problem_068/sol1.py) * Problem 069 * [Sol1](project_euler/problem_069/sol1.py) * Problem 070 * [Sol1](project_euler/problem_070/sol1.py) * Problem 071 * [Sol1](project_euler/problem_071/sol1.py) * Problem 072 * [Sol1](project_euler/problem_072/sol1.py) * [Sol2](project_euler/problem_072/sol2.py) * Problem 073 * [Sol1](project_euler/problem_073/sol1.py) * Problem 074 * [Sol1](project_euler/problem_074/sol1.py) * [Sol2](project_euler/problem_074/sol2.py) * Problem 075 * [Sol1](project_euler/problem_075/sol1.py) * Problem 076 * [Sol1](project_euler/problem_076/sol1.py) * Problem 077 * [Sol1](project_euler/problem_077/sol1.py) * Problem 078 * [Sol1](project_euler/problem_078/sol1.py) * Problem 080 * [Sol1](project_euler/problem_080/sol1.py) * Problem 081 * [Sol1](project_euler/problem_081/sol1.py) * Problem 085 * [Sol1](project_euler/problem_085/sol1.py) * Problem 086 * [Sol1](project_euler/problem_086/sol1.py) * Problem 087 * [Sol1](project_euler/problem_087/sol1.py) * Problem 089 * [Sol1](project_euler/problem_089/sol1.py) * Problem 091 * [Sol1](project_euler/problem_091/sol1.py) * Problem 092 * [Sol1](project_euler/problem_092/sol1.py) * Problem 097 * [Sol1](project_euler/problem_097/sol1.py) * Problem 099 * [Sol1](project_euler/problem_099/sol1.py) * Problem 101 * [Sol1](project_euler/problem_101/sol1.py) * Problem 102 * [Sol1](project_euler/problem_102/sol1.py) * Problem 104 * [Sol1](project_euler/problem_104/sol1.py) * Problem 107 * [Sol1](project_euler/problem_107/sol1.py) * Problem 109 * [Sol1](project_euler/problem_109/sol1.py) * Problem 112 * [Sol1](project_euler/problem_112/sol1.py) * Problem 113 * [Sol1](project_euler/problem_113/sol1.py) * Problem 114 * [Sol1](project_euler/problem_114/sol1.py) * Problem 115 * [Sol1](project_euler/problem_115/sol1.py) * Problem 116 * [Sol1](project_euler/problem_116/sol1.py) * Problem 119 * [Sol1](project_euler/problem_119/sol1.py) * Problem 120 * [Sol1](project_euler/problem_120/sol1.py) * Problem 121 * [Sol1](project_euler/problem_121/sol1.py) * Problem 123 * [Sol1](project_euler/problem_123/sol1.py) * Problem 125 * [Sol1](project_euler/problem_125/sol1.py) * Problem 129 * [Sol1](project_euler/problem_129/sol1.py) * Problem 135 * [Sol1](project_euler/problem_135/sol1.py) * Problem 144 * [Sol1](project_euler/problem_144/sol1.py) * Problem 145 * [Sol1](project_euler/problem_145/sol1.py) * Problem 173 * [Sol1](project_euler/problem_173/sol1.py) * Problem 174 * [Sol1](project_euler/problem_174/sol1.py) * Problem 180 * [Sol1](project_euler/problem_180/sol1.py) * Problem 188 * [Sol1](project_euler/problem_188/sol1.py) * Problem 191 * [Sol1](project_euler/problem_191/sol1.py) * Problem 203 * [Sol1](project_euler/problem_203/sol1.py) * Problem 205 * [Sol1](project_euler/problem_205/sol1.py) * Problem 206 * [Sol1](project_euler/problem_206/sol1.py) * Problem 207 * [Sol1](project_euler/problem_207/sol1.py) * Problem 234 * [Sol1](project_euler/problem_234/sol1.py) * Problem 301 * [Sol1](project_euler/problem_301/sol1.py) * Problem 493 * [Sol1](project_euler/problem_493/sol1.py) * Problem 551 * [Sol1](project_euler/problem_551/sol1.py) * Problem 587 * [Sol1](project_euler/problem_587/sol1.py) * Problem 686 * [Sol1](project_euler/problem_686/sol1.py) ## Quantum * [Deutsch Jozsa](quantum/deutsch_jozsa.py) * [Half Adder](quantum/half_adder.py) * [Not Gate](quantum/not_gate.py) * [Q Full Adder](quantum/q_full_adder.py) * [Quantum Entanglement](quantum/quantum_entanglement.py) * [Ripple Adder Classic](quantum/ripple_adder_classic.py) * [Single Qubit Measure](quantum/single_qubit_measure.py) * [Superdense Coding](quantum/superdense_coding.py) ## Scheduling * [First Come First Served](scheduling/first_come_first_served.py) * [Highest Response Ratio Next](scheduling/highest_response_ratio_next.py) * [Job Sequencing With Deadline](scheduling/job_sequencing_with_deadline.py) * [Multi Level Feedback Queue](scheduling/multi_level_feedback_queue.py) * [Non Preemptive Shortest Job First](scheduling/non_preemptive_shortest_job_first.py) * [Round Robin](scheduling/round_robin.py) * [Shortest Job First](scheduling/shortest_job_first.py) ## Searches * [Binary Search](searches/binary_search.py) * [Binary Tree Traversal](searches/binary_tree_traversal.py) * [Double Linear Search](searches/double_linear_search.py) * [Double Linear Search Recursion](searches/double_linear_search_recursion.py) * [Fibonacci Search](searches/fibonacci_search.py) * [Hill Climbing](searches/hill_climbing.py) * [Interpolation Search](searches/interpolation_search.py) * [Jump Search](searches/jump_search.py) * [Linear Search](searches/linear_search.py) * [Quick Select](searches/quick_select.py) * [Sentinel Linear Search](searches/sentinel_linear_search.py) * [Simple Binary Search](searches/simple_binary_search.py) * [Simulated Annealing](searches/simulated_annealing.py) * [Tabu Search](searches/tabu_search.py) * [Ternary Search](searches/ternary_search.py) ## Sorts * [Bead Sort](sorts/bead_sort.py) * [Bitonic Sort](sorts/bitonic_sort.py) * [Bogo Sort](sorts/bogo_sort.py) * [Bubble Sort](sorts/bubble_sort.py) * [Bucket Sort](sorts/bucket_sort.py) * [Circle Sort](sorts/circle_sort.py) * [Cocktail Shaker Sort](sorts/cocktail_shaker_sort.py) * [Comb Sort](sorts/comb_sort.py) * [Counting Sort](sorts/counting_sort.py) * [Cycle Sort](sorts/cycle_sort.py) * [Double Sort](sorts/double_sort.py) * [Dutch National Flag Sort](sorts/dutch_national_flag_sort.py) * [Exchange Sort](sorts/exchange_sort.py) * [External Sort](sorts/external_sort.py) * [Gnome Sort](sorts/gnome_sort.py) * [Heap Sort](sorts/heap_sort.py) * [Insertion Sort](sorts/insertion_sort.py) * [Intro Sort](sorts/intro_sort.py) * [Iterative Merge Sort](sorts/iterative_merge_sort.py) * [Merge Insertion Sort](sorts/merge_insertion_sort.py) * [Merge Sort](sorts/merge_sort.py) * [Msd Radix Sort](sorts/msd_radix_sort.py) * [Natural Sort](sorts/natural_sort.py) * [Odd Even Sort](sorts/odd_even_sort.py) * [Odd Even Transposition Parallel](sorts/odd_even_transposition_parallel.py) * [Odd Even Transposition Single Threaded](sorts/odd_even_transposition_single_threaded.py) * [Pancake Sort](sorts/pancake_sort.py) * [Patience Sort](sorts/patience_sort.py) * [Pigeon Sort](sorts/pigeon_sort.py) * [Pigeonhole Sort](sorts/pigeonhole_sort.py) * [Quick Sort](sorts/quick_sort.py) * [Quick Sort 3 Partition](sorts/quick_sort_3_partition.py) * [Radix Sort](sorts/radix_sort.py) * [Random Normal Distribution Quicksort](sorts/random_normal_distribution_quicksort.py) * [Random Pivot Quick Sort](sorts/random_pivot_quick_sort.py) * [Recursive Bubble Sort](sorts/recursive_bubble_sort.py) * [Recursive Insertion Sort](sorts/recursive_insertion_sort.py) * [Recursive Mergesort Array](sorts/recursive_mergesort_array.py) * [Recursive Quick Sort](sorts/recursive_quick_sort.py) * [Selection Sort](sorts/selection_sort.py) * [Shell Sort](sorts/shell_sort.py) * [Shrink Shell Sort](sorts/shrink_shell_sort.py) * [Slowsort](sorts/slowsort.py) * [Stooge Sort](sorts/stooge_sort.py) * [Strand Sort](sorts/strand_sort.py) * [Tim Sort](sorts/tim_sort.py) * [Topological Sort](sorts/topological_sort.py) * [Tree Sort](sorts/tree_sort.py) * [Unknown Sort](sorts/unknown_sort.py) * [Wiggle Sort](sorts/wiggle_sort.py) ## Strings * [Aho Corasick](strings/aho_corasick.py) * [Alternative String Arrange](strings/alternative_string_arrange.py) * [Anagrams](strings/anagrams.py) * [Autocomplete Using Trie](strings/autocomplete_using_trie.py) * [Barcode Validator](strings/barcode_validator.py) * [Boyer Moore Search](strings/boyer_moore_search.py) * [Can String Be Rearranged As Palindrome](strings/can_string_be_rearranged_as_palindrome.py) * [Capitalize](strings/capitalize.py) * [Check Anagrams](strings/check_anagrams.py) * [Credit Card Validator](strings/credit_card_validator.py) * [Detecting English Programmatically](strings/detecting_english_programmatically.py) * [Dna](strings/dna.py) * [Frequency Finder](strings/frequency_finder.py) * [Hamming Distance](strings/hamming_distance.py) * [Indian Phone Validator](strings/indian_phone_validator.py) * [Is Contains Unique Chars](strings/is_contains_unique_chars.py) * [Is Isogram](strings/is_isogram.py) * [Is Palindrome](strings/is_palindrome.py) * [Is Pangram](strings/is_pangram.py) * [Is Spain National Id](strings/is_spain_national_id.py) * [Jaro Winkler](strings/jaro_winkler.py) * [Join](strings/join.py) * [Knuth Morris Pratt](strings/knuth_morris_pratt.py) * [Levenshtein Distance](strings/levenshtein_distance.py) * [Lower](strings/lower.py) * [Manacher](strings/manacher.py) * [Min Cost String Conversion](strings/min_cost_string_conversion.py) * [Naive String Search](strings/naive_string_search.py) * [Ngram](strings/ngram.py) * [Palindrome](strings/palindrome.py) * [Prefix Function](strings/prefix_function.py) * [Rabin Karp](strings/rabin_karp.py) * [Remove Duplicate](strings/remove_duplicate.py) * [Reverse Letters](strings/reverse_letters.py) * [Reverse Long Words](strings/reverse_long_words.py) * [Reverse Words](strings/reverse_words.py) * [Snake Case To Camel Pascal Case](strings/snake_case_to_camel_pascal_case.py) * [Split](strings/split.py) * [Upper](strings/upper.py) * [Wave](strings/wave.py) * [Wildcard Pattern Matching](strings/wildcard_pattern_matching.py) * [Word Occurrence](strings/word_occurrence.py) * [Word Patterns](strings/word_patterns.py) * [Z Function](strings/z_function.py) ## Web Programming * [Co2 Emission](web_programming/co2_emission.py) * [Covid Stats Via Xpath](web_programming/covid_stats_via_xpath.py) * [Crawl Google Results](web_programming/crawl_google_results.py) * [Crawl Google Scholar Citation](web_programming/crawl_google_scholar_citation.py) * [Currency Converter](web_programming/currency_converter.py) * [Current Stock Price](web_programming/current_stock_price.py) * [Current Weather](web_programming/current_weather.py) * [Daily Horoscope](web_programming/daily_horoscope.py) * [Download Images From Google Query](web_programming/download_images_from_google_query.py) * [Emails From Url](web_programming/emails_from_url.py) * [Fetch Anime And Play](web_programming/fetch_anime_and_play.py) * [Fetch Bbc News](web_programming/fetch_bbc_news.py) * [Fetch Github Info](web_programming/fetch_github_info.py) * [Fetch Jobs](web_programming/fetch_jobs.py) * [Fetch Quotes](web_programming/fetch_quotes.py) * [Fetch Well Rx Price](web_programming/fetch_well_rx_price.py) * [Get Imdb Top 250 Movies Csv](web_programming/get_imdb_top_250_movies_csv.py) * [Get Imdbtop](web_programming/get_imdbtop.py) * [Get Top Billioners](web_programming/get_top_billioners.py) * [Get Top Hn Posts](web_programming/get_top_hn_posts.py) * [Get User Tweets](web_programming/get_user_tweets.py) * [Giphy](web_programming/giphy.py) * [Instagram Crawler](web_programming/instagram_crawler.py) * [Instagram Pic](web_programming/instagram_pic.py) * [Instagram Video](web_programming/instagram_video.py) * [Nasa Data](web_programming/nasa_data.py) * [Open Google Results](web_programming/open_google_results.py) * [Random Anime Character](web_programming/random_anime_character.py) * [Recaptcha Verification](web_programming/recaptcha_verification.py) * [Reddit](web_programming/reddit.py) * [Search Books By Isbn](web_programming/search_books_by_isbn.py) * [Slack Message](web_programming/slack_message.py) * [Test Fetch Github Info](web_programming/test_fetch_github_info.py) * [World Covid19 Stats](web_programming/world_covid19_stats.py)
1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Wikipedia: https://en.wikipedia.org/wiki/Enigma_machine Video explanation: https://youtu.be/QwQVMqfoB2E Also check out Numberphile's and Computerphile's videos on this topic This module contains function 'enigma' which emulates the famous Enigma machine from WWII. Module includes: - enigma function - showcase of function usage - 9 randomly generated rotors - reflector (aka static rotor) - original alphabet Created by TrapinchO """ from __future__ import annotations RotorPositionT = tuple[int, int, int] RotorSelectionT = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # -------------------------- default selection -------------------------- # rotors -------------------------- rotor1 = "EGZWVONAHDCLFQMSIPJBYUKXTR" rotor2 = "FOBHMDKEXQNRAULPGSJVTYICZW" rotor3 = "ZJXESIUQLHAVRMDOYGTNFWPBKC" # reflector -------------------------- reflector = { "A": "N", "N": "A", "B": "O", "O": "B", "C": "P", "P": "C", "D": "Q", "Q": "D", "E": "R", "R": "E", "F": "S", "S": "F", "G": "T", "T": "G", "H": "U", "U": "H", "I": "V", "V": "I", "J": "W", "W": "J", "K": "X", "X": "K", "L": "Y", "Y": "L", "M": "Z", "Z": "M", } # -------------------------- extra rotors -------------------------- rotor4 = "RMDJXFUWGISLHVTCQNKYPBEZOA" rotor5 = "SGLCPQWZHKXAREONTFBVIYJUDM" rotor6 = "HVSICLTYKQUBXDWAJZOMFGPREN" rotor7 = "RZWQHFMVDBKICJLNTUXAGYPSOE" rotor8 = "LFKIJODBEGAMQPXVUHYSTCZRWN" rotor9 = "KOAEGVDHXPQZMLFTYWJNBRCIUS" def _validator( rotpos: RotorPositionT, rotsel: RotorSelectionT, pb: str ) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: """ Checks if the values can be used for the 'enigma' function >>> _validator((1,1,1), (rotor1, rotor2, rotor3), 'POLAND') ((1, 1, 1), ('EGZWVONAHDCLFQMSIPJBYUKXTR', 'FOBHMDKEXQNRAULPGSJVTYICZW', \ 'ZJXESIUQLHAVRMDOYGTNFWPBKC'), \ {'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'}) :param rotpos: rotor_positon :param rotsel: rotor_selection :param pb: plugb -> validated and transformed :return: (rotpos, rotsel, pb) """ # Checks if there are 3 unique rotors unique_rotsel = len(set(rotsel)) if unique_rotsel < 3: raise Exception(f"Please use 3 unique rotors (not {unique_rotsel})") # Checks if rotor positions are valid rotorpos1, rotorpos2, rotorpos3 = rotpos if not 0 < rotorpos1 <= len(abc): raise ValueError( "First rotor position is not within range of 1..26 (" f"{rotorpos1}" ) if not 0 < rotorpos2 <= len(abc): raise ValueError( "Second rotor position is not within range of 1..26 (" f"{rotorpos2})" ) if not 0 < rotorpos3 <= len(abc): raise ValueError( "Third rotor position is not within range of 1..26 (" f"{rotorpos3})" ) # Validates string and returns dict pbdict = _plugboard(pb) return rotpos, rotsel, pbdict def _plugboard(pbstring: str) -> dict[str, str]: """ https://en.wikipedia.org/wiki/Enigma_machine#Plugboard >>> _plugboard('PICTURES') {'P': 'I', 'I': 'P', 'C': 'T', 'T': 'C', 'U': 'R', 'R': 'U', 'E': 'S', 'S': 'E'} >>> _plugboard('POLAND') {'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'} In the code, 'pb' stands for 'plugboard' Pairs can be separated by spaces :param pbstring: string containing plugboard setting for the Enigma machine :return: dictionary containing converted pairs """ # tests the input string if it # a) is type string # b) has even length (so pairs can be made) if not isinstance(pbstring, str): raise TypeError(f"Plugboard setting isn't type string ({type(pbstring)})") elif len(pbstring) % 2 != 0: raise Exception(f"Odd number of symbols ({len(pbstring)})") elif pbstring == "": return {} pbstring.replace(" ", "") # Checks if all characters are unique tmppbl = set() for i in pbstring: if i not in abc: raise Exception(f"'{i}' not in list of symbols") elif i in tmppbl: raise Exception(f"Duplicate symbol ({i})") else: tmppbl.add(i) del tmppbl # Created the dictionary pb = {} for j in range(0, len(pbstring) - 1, 2): pb[pbstring[j]] = pbstring[j + 1] pb[pbstring[j + 1]] = pbstring[j] return pb def enigma( text: str, rotor_position: RotorPositionT, rotor_selection: RotorSelectionT = (rotor1, rotor2, rotor3), plugb: str = "", ) -> str: """ The only difference with real-world enigma is that I allowed string input. All characters are converted to uppercase. (non-letter symbol are ignored) How it works: (for every letter in the message) - Input letter goes into the plugboard. If it is connected to another one, switch it. - Letter goes through 3 rotors. Each rotor can be represented as 2 sets of symbol, where one is shuffled. Each symbol from the first set has corresponding symbol in the second set and vice versa. example: | ABCDEFGHIJKLMNOPQRSTUVWXYZ | e.g. F=D and D=F | VKLEPDBGRNWTFCJOHQAMUZYIXS | - Symbol then goes through reflector (static rotor). There it is switched with paired symbol The reflector can be represented as2 sets, each with half of the alphanet. There are usually 10 pairs of letters. Example: | ABCDEFGHIJKLM | e.g. E is paired to X | ZYXWVUTSRQPON | so when E goes in X goes out and vice versa - Letter then goes through the rotors again - If the letter is connected to plugboard, it is switched. - Return the letter >>> enigma('Hello World!', (1, 2, 1), plugb='pictures') 'KORYH JUHHI!' >>> enigma('KORYH, juhhi!', (1, 2, 1), plugb='pictures') 'HELLO, WORLD!' >>> enigma('hello world!', (1, 1, 1), plugb='pictures') 'FPNCZ QWOBU!' >>> enigma('FPNCZ QWOBU', (1, 1, 1), plugb='pictures') 'HELLO WORLD' :param text: input message :param rotor_position: tuple with 3 values in range 1..26 :param rotor_selection: tuple with 3 rotors () :param plugb: string containing plugboard configuration (default '') :return: en/decrypted string """ text = text.upper() rotor_position, rotor_selection, plugboard = _validator( rotor_position, rotor_selection, plugb.upper() ) rotorpos1, rotorpos2, rotorpos3 = rotor_position rotor1, rotor2, rotor3 = rotor_selection rotorpos1 -= 1 rotorpos2 -= 1 rotorpos3 -= 1 result = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: symbol = plugboard[symbol] # rotor ra -------------------------- index = abc.index(symbol) + rotorpos1 symbol = rotor1[index % len(abc)] # rotor rb -------------------------- index = abc.index(symbol) + rotorpos2 symbol = rotor2[index % len(abc)] # rotor rc -------------------------- index = abc.index(symbol) + rotorpos3 symbol = rotor3[index % len(abc)] # reflector -------------------------- # this is the reason you don't need another machine to decipher symbol = reflector[symbol] # 2nd rotors symbol = abc[rotor3.index(symbol) - rotorpos3] symbol = abc[rotor2.index(symbol) - rotorpos2] symbol = abc[rotor1.index(symbol) - rotorpos1] # 2nd plugboard if symbol in plugboard: symbol = plugboard[symbol] # moves/resets rotor positions rotorpos1 += 1 if rotorpos1 >= len(abc): rotorpos1 = 0 rotorpos2 += 1 if rotorpos2 >= len(abc): rotorpos2 = 0 rotorpos3 += 1 if rotorpos3 >= len(abc): rotorpos3 = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(symbol) return "".join(result) if __name__ == "__main__": message = "This is my Python script that emulates the Enigma machine from WWII." rotor_pos = (1, 1, 1) pb = "pictures" rotor_sel = (rotor2, rotor4, rotor8) en = enigma(message, rotor_pos, rotor_sel, pb) print("Encrypted message:", en) print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))
""" Wikipedia: https://en.wikipedia.org/wiki/Enigma_machine Video explanation: https://youtu.be/QwQVMqfoB2E Also check out Numberphile's and Computerphile's videos on this topic This module contains function 'enigma' which emulates the famous Enigma machine from WWII. Module includes: - enigma function - showcase of function usage - 9 randomly generated rotors - reflector (aka static rotor) - original alphabet Created by TrapinchO """ from __future__ import annotations RotorPositionT = tuple[int, int, int] RotorSelectionT = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # -------------------------- default selection -------------------------- # rotors -------------------------- rotor1 = "EGZWVONAHDCLFQMSIPJBYUKXTR" rotor2 = "FOBHMDKEXQNRAULPGSJVTYICZW" rotor3 = "ZJXESIUQLHAVRMDOYGTNFWPBKC" # reflector -------------------------- reflector = { "A": "N", "N": "A", "B": "O", "O": "B", "C": "P", "P": "C", "D": "Q", "Q": "D", "E": "R", "R": "E", "F": "S", "S": "F", "G": "T", "T": "G", "H": "U", "U": "H", "I": "V", "V": "I", "J": "W", "W": "J", "K": "X", "X": "K", "L": "Y", "Y": "L", "M": "Z", "Z": "M", } # -------------------------- extra rotors -------------------------- rotor4 = "RMDJXFUWGISLHVTCQNKYPBEZOA" rotor5 = "SGLCPQWZHKXAREONTFBVIYJUDM" rotor6 = "HVSICLTYKQUBXDWAJZOMFGPREN" rotor7 = "RZWQHFMVDBKICJLNTUXAGYPSOE" rotor8 = "LFKIJODBEGAMQPXVUHYSTCZRWN" rotor9 = "KOAEGVDHXPQZMLFTYWJNBRCIUS" def _validator( rotpos: RotorPositionT, rotsel: RotorSelectionT, pb: str ) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: """ Checks if the values can be used for the 'enigma' function >>> _validator((1,1,1), (rotor1, rotor2, rotor3), 'POLAND') ((1, 1, 1), ('EGZWVONAHDCLFQMSIPJBYUKXTR', 'FOBHMDKEXQNRAULPGSJVTYICZW', \ 'ZJXESIUQLHAVRMDOYGTNFWPBKC'), \ {'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'}) :param rotpos: rotor_positon :param rotsel: rotor_selection :param pb: plugb -> validated and transformed :return: (rotpos, rotsel, pb) """ # Checks if there are 3 unique rotors if (unique_rotsel := len(set(rotsel))) < 3: raise Exception(f"Please use 3 unique rotors (not {unique_rotsel})") # Checks if rotor positions are valid rotorpos1, rotorpos2, rotorpos3 = rotpos if not 0 < rotorpos1 <= len(abc): raise ValueError( "First rotor position is not within range of 1..26 (" f"{rotorpos1}" ) if not 0 < rotorpos2 <= len(abc): raise ValueError( "Second rotor position is not within range of 1..26 (" f"{rotorpos2})" ) if not 0 < rotorpos3 <= len(abc): raise ValueError( "Third rotor position is not within range of 1..26 (" f"{rotorpos3})" ) # Validates string and returns dict pbdict = _plugboard(pb) return rotpos, rotsel, pbdict def _plugboard(pbstring: str) -> dict[str, str]: """ https://en.wikipedia.org/wiki/Enigma_machine#Plugboard >>> _plugboard('PICTURES') {'P': 'I', 'I': 'P', 'C': 'T', 'T': 'C', 'U': 'R', 'R': 'U', 'E': 'S', 'S': 'E'} >>> _plugboard('POLAND') {'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'} In the code, 'pb' stands for 'plugboard' Pairs can be separated by spaces :param pbstring: string containing plugboard setting for the Enigma machine :return: dictionary containing converted pairs """ # tests the input string if it # a) is type string # b) has even length (so pairs can be made) if not isinstance(pbstring, str): raise TypeError(f"Plugboard setting isn't type string ({type(pbstring)})") elif len(pbstring) % 2 != 0: raise Exception(f"Odd number of symbols ({len(pbstring)})") elif pbstring == "": return {} pbstring.replace(" ", "") # Checks if all characters are unique tmppbl = set() for i in pbstring: if i not in abc: raise Exception(f"'{i}' not in list of symbols") elif i in tmppbl: raise Exception(f"Duplicate symbol ({i})") else: tmppbl.add(i) del tmppbl # Created the dictionary pb = {} for j in range(0, len(pbstring) - 1, 2): pb[pbstring[j]] = pbstring[j + 1] pb[pbstring[j + 1]] = pbstring[j] return pb def enigma( text: str, rotor_position: RotorPositionT, rotor_selection: RotorSelectionT = (rotor1, rotor2, rotor3), plugb: str = "", ) -> str: """ The only difference with real-world enigma is that I allowed string input. All characters are converted to uppercase. (non-letter symbol are ignored) How it works: (for every letter in the message) - Input letter goes into the plugboard. If it is connected to another one, switch it. - Letter goes through 3 rotors. Each rotor can be represented as 2 sets of symbol, where one is shuffled. Each symbol from the first set has corresponding symbol in the second set and vice versa. example: | ABCDEFGHIJKLMNOPQRSTUVWXYZ | e.g. F=D and D=F | VKLEPDBGRNWTFCJOHQAMUZYIXS | - Symbol then goes through reflector (static rotor). There it is switched with paired symbol The reflector can be represented as2 sets, each with half of the alphanet. There are usually 10 pairs of letters. Example: | ABCDEFGHIJKLM | e.g. E is paired to X | ZYXWVUTSRQPON | so when E goes in X goes out and vice versa - Letter then goes through the rotors again - If the letter is connected to plugboard, it is switched. - Return the letter >>> enigma('Hello World!', (1, 2, 1), plugb='pictures') 'KORYH JUHHI!' >>> enigma('KORYH, juhhi!', (1, 2, 1), plugb='pictures') 'HELLO, WORLD!' >>> enigma('hello world!', (1, 1, 1), plugb='pictures') 'FPNCZ QWOBU!' >>> enigma('FPNCZ QWOBU', (1, 1, 1), plugb='pictures') 'HELLO WORLD' :param text: input message :param rotor_position: tuple with 3 values in range 1..26 :param rotor_selection: tuple with 3 rotors () :param plugb: string containing plugboard configuration (default '') :return: en/decrypted string """ text = text.upper() rotor_position, rotor_selection, plugboard = _validator( rotor_position, rotor_selection, plugb.upper() ) rotorpos1, rotorpos2, rotorpos3 = rotor_position rotor1, rotor2, rotor3 = rotor_selection rotorpos1 -= 1 rotorpos2 -= 1 rotorpos3 -= 1 result = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: symbol = plugboard[symbol] # rotor ra -------------------------- index = abc.index(symbol) + rotorpos1 symbol = rotor1[index % len(abc)] # rotor rb -------------------------- index = abc.index(symbol) + rotorpos2 symbol = rotor2[index % len(abc)] # rotor rc -------------------------- index = abc.index(symbol) + rotorpos3 symbol = rotor3[index % len(abc)] # reflector -------------------------- # this is the reason you don't need another machine to decipher symbol = reflector[symbol] # 2nd rotors symbol = abc[rotor3.index(symbol) - rotorpos3] symbol = abc[rotor2.index(symbol) - rotorpos2] symbol = abc[rotor1.index(symbol) - rotorpos1] # 2nd plugboard if symbol in plugboard: symbol = plugboard[symbol] # moves/resets rotor positions rotorpos1 += 1 if rotorpos1 >= len(abc): rotorpos1 = 0 rotorpos2 += 1 if rotorpos2 >= len(abc): rotorpos2 = 0 rotorpos3 += 1 if rotorpos3 >= len(abc): rotorpos3 = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(symbol) return "".join(result) if __name__ == "__main__": message = "This is my Python script that emulates the Enigma machine from WWII." rotor_pos = (1, 1, 1) pb = "pictures" rotor_sel = (rotor2, rotor4, rotor8) en = enigma(message, rotor_pos, rotor_sel, pb) print("Encrypted message:", en) print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))
1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" - A linked list is similar to an array, it holds values. However, links in a linked list do not have indexes. - This is an example of a double ended, doubly linked list. - Each link references the next link and the previous one. - A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list. - Advantages over SLL - It can be traversed in both forward and backward direction. Delete operation is more efficient """ class Node: def __init__(self, data: int, previous=None, next_node=None): self.data = data self.previous = previous self.next = next_node def __str__(self) -> str: return f"{self.data}" def get_data(self) -> int: return self.data def get_next(self): return self.next def get_previous(self): return self.previous class LinkedListIterator: def __init__(self, head): self.current = head def __iter__(self): return self def __next__(self): if not self.current: raise StopIteration else: value = self.current.get_data() self.current = self.current.get_next() return value class LinkedList: def __init__(self): self.head = None # First node in list self.tail = None # Last node in list def __str__(self): current = self.head nodes = [] while current is not None: nodes.append(current.get_data()) current = current.get_next() return " ".join(str(node) for node in nodes) def __contains__(self, value: int): current = self.head while current: if current.get_data() == value: return True current = current.get_next() return False def __iter__(self): return LinkedListIterator(self.head) def get_head_data(self): if self.head: return self.head.get_data() return None def get_tail_data(self): if self.tail: return self.tail.get_data() return None def set_head(self, node: Node) -> None: if self.head is None: self.head = node self.tail = node else: self.insert_before_node(self.head, node) def set_tail(self, node: Node) -> None: if self.head is None: self.set_head(node) else: self.insert_after_node(self.tail, node) def insert(self, value: int) -> None: node = Node(value) if self.head is None: self.set_head(node) else: self.set_tail(node) def insert_before_node(self, node: Node, node_to_insert: Node) -> None: node_to_insert.next = node node_to_insert.previous = node.previous if node.get_previous() is None: self.head = node_to_insert else: node.previous.next = node_to_insert node.previous = node_to_insert def insert_after_node(self, node: Node, node_to_insert: Node) -> None: node_to_insert.previous = node node_to_insert.next = node.next if node.get_next() is None: self.tail = node_to_insert else: node.next.previous = node_to_insert node.next = node_to_insert def insert_at_position(self, position: int, value: int) -> None: current_position = 1 new_node = Node(value) node = self.head while node: if current_position == position: self.insert_before_node(node, new_node) return None current_position += 1 node = node.next self.insert_after_node(self.tail, new_node) def get_node(self, item: int) -> Node: node = self.head while node: if node.get_data() == item: return node node = node.get_next() raise Exception("Node not found") def delete_value(self, value): node = self.get_node(value) if node is not None: if node == self.head: self.head = self.head.get_next() if node == self.tail: self.tail = self.tail.get_previous() self.remove_node_pointers(node) @staticmethod def remove_node_pointers(node: Node) -> None: if node.get_next(): node.next.previous = node.previous if node.get_previous(): node.previous.next = node.next node.next = None node.previous = None def is_empty(self): return self.head is None def create_linked_list() -> None: """ >>> new_linked_list = LinkedList() >>> new_linked_list.get_head_data() is None True >>> new_linked_list.get_tail_data() is None True >>> new_linked_list.is_empty() True >>> new_linked_list.insert(10) >>> new_linked_list.get_head_data() 10 >>> new_linked_list.get_tail_data() 10 >>> new_linked_list.insert_at_position(position=3, value=20) >>> new_linked_list.get_head_data() 10 >>> new_linked_list.get_tail_data() 20 >>> new_linked_list.set_head(Node(1000)) >>> new_linked_list.get_head_data() 1000 >>> new_linked_list.get_tail_data() 20 >>> new_linked_list.set_tail(Node(2000)) >>> new_linked_list.get_head_data() 1000 >>> new_linked_list.get_tail_data() 2000 >>> for value in new_linked_list: ... print(value) 1000 10 20 2000 >>> new_linked_list.is_empty() False >>> for value in new_linked_list: ... print(value) 1000 10 20 2000 >>> 10 in new_linked_list True >>> new_linked_list.delete_value(value=10) >>> 10 in new_linked_list False >>> new_linked_list.delete_value(value=2000) >>> new_linked_list.get_tail_data() 20 >>> new_linked_list.delete_value(value=1000) >>> new_linked_list.get_tail_data() 20 >>> new_linked_list.get_head_data() 20 >>> for value in new_linked_list: ... print(value) 20 >>> new_linked_list.delete_value(value=20) >>> for value in new_linked_list: ... print(value) >>> for value in range(1,10): ... new_linked_list.insert(value=value) >>> for value in new_linked_list: ... print(value) 1 2 3 4 5 6 7 8 9 """ if __name__ == "__main__": import doctest doctest.testmod()
""" - A linked list is similar to an array, it holds values. However, links in a linked list do not have indexes. - This is an example of a double ended, doubly linked list. - Each link references the next link and the previous one. - A Doubly Linked List (DLL) contains an extra pointer, typically called previous pointer, together with next pointer and data which are there in singly linked list. - Advantages over SLL - It can be traversed in both forward and backward direction. Delete operation is more efficient """ class Node: def __init__(self, data: int, previous=None, next_node=None): self.data = data self.previous = previous self.next = next_node def __str__(self) -> str: return f"{self.data}" def get_data(self) -> int: return self.data def get_next(self): return self.next def get_previous(self): return self.previous class LinkedListIterator: def __init__(self, head): self.current = head def __iter__(self): return self def __next__(self): if not self.current: raise StopIteration else: value = self.current.get_data() self.current = self.current.get_next() return value class LinkedList: def __init__(self): self.head = None # First node in list self.tail = None # Last node in list def __str__(self): current = self.head nodes = [] while current is not None: nodes.append(current.get_data()) current = current.get_next() return " ".join(str(node) for node in nodes) def __contains__(self, value: int): current = self.head while current: if current.get_data() == value: return True current = current.get_next() return False def __iter__(self): return LinkedListIterator(self.head) def get_head_data(self): if self.head: return self.head.get_data() return None def get_tail_data(self): if self.tail: return self.tail.get_data() return None def set_head(self, node: Node) -> None: if self.head is None: self.head = node self.tail = node else: self.insert_before_node(self.head, node) def set_tail(self, node: Node) -> None: if self.head is None: self.set_head(node) else: self.insert_after_node(self.tail, node) def insert(self, value: int) -> None: node = Node(value) if self.head is None: self.set_head(node) else: self.set_tail(node) def insert_before_node(self, node: Node, node_to_insert: Node) -> None: node_to_insert.next = node node_to_insert.previous = node.previous if node.get_previous() is None: self.head = node_to_insert else: node.previous.next = node_to_insert node.previous = node_to_insert def insert_after_node(self, node: Node, node_to_insert: Node) -> None: node_to_insert.previous = node node_to_insert.next = node.next if node.get_next() is None: self.tail = node_to_insert else: node.next.previous = node_to_insert node.next = node_to_insert def insert_at_position(self, position: int, value: int) -> None: current_position = 1 new_node = Node(value) node = self.head while node: if current_position == position: self.insert_before_node(node, new_node) return None current_position += 1 node = node.next self.insert_after_node(self.tail, new_node) def get_node(self, item: int) -> Node: node = self.head while node: if node.get_data() == item: return node node = node.get_next() raise Exception("Node not found") def delete_value(self, value): if (node := self.get_node(value)) is not None: if node == self.head: self.head = self.head.get_next() if node == self.tail: self.tail = self.tail.get_previous() self.remove_node_pointers(node) @staticmethod def remove_node_pointers(node: Node) -> None: if node.get_next(): node.next.previous = node.previous if node.get_previous(): node.previous.next = node.next node.next = None node.previous = None def is_empty(self): return self.head is None def create_linked_list() -> None: """ >>> new_linked_list = LinkedList() >>> new_linked_list.get_head_data() is None True >>> new_linked_list.get_tail_data() is None True >>> new_linked_list.is_empty() True >>> new_linked_list.insert(10) >>> new_linked_list.get_head_data() 10 >>> new_linked_list.get_tail_data() 10 >>> new_linked_list.insert_at_position(position=3, value=20) >>> new_linked_list.get_head_data() 10 >>> new_linked_list.get_tail_data() 20 >>> new_linked_list.set_head(Node(1000)) >>> new_linked_list.get_head_data() 1000 >>> new_linked_list.get_tail_data() 20 >>> new_linked_list.set_tail(Node(2000)) >>> new_linked_list.get_head_data() 1000 >>> new_linked_list.get_tail_data() 2000 >>> for value in new_linked_list: ... print(value) 1000 10 20 2000 >>> new_linked_list.is_empty() False >>> for value in new_linked_list: ... print(value) 1000 10 20 2000 >>> 10 in new_linked_list True >>> new_linked_list.delete_value(value=10) >>> 10 in new_linked_list False >>> new_linked_list.delete_value(value=2000) >>> new_linked_list.get_tail_data() 20 >>> new_linked_list.delete_value(value=1000) >>> new_linked_list.get_tail_data() 20 >>> new_linked_list.get_head_data() 20 >>> for value in new_linked_list: ... print(value) 20 >>> new_linked_list.delete_value(value=20) >>> for value in new_linked_list: ... print(value) >>> for value in range(1,10): ... new_linked_list.insert(value=value) >>> for value in new_linked_list: ... print(value) 1 2 3 4 5 6 7 8 9 """ if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is a pure Python implementation of Dynamic Programming solution to the fibonacci sequence problem. """ class Fibonacci: def __init__(self) -> None: self.sequence = [0, 1] def get(self, index: int) -> list: """ Get the Fibonacci number of `index`. If the number does not exist, calculate all missing numbers leading up to the number of `index`. >>> Fibonacci().get(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] >>> Fibonacci().get(5) [0, 1, 1, 2, 3] """ difference = index - (len(self.sequence) - 2) if difference >= 1: for _ in range(difference): self.sequence.append(self.sequence[-1] + self.sequence[-2]) return self.sequence[:index] def main(): print( "Fibonacci Series Using Dynamic Programming\n", "Enter the index of the Fibonacci number you want to calculate ", "in the prompt below. (To exit enter exit or Ctrl-C)\n", sep="", ) fibonacci = Fibonacci() while True: prompt: str = input(">> ") if prompt in {"exit", "quit"}: break try: index: int = int(prompt) except ValueError: print("Enter a number or 'exit'") continue print(fibonacci.get(index)) if __name__ == "__main__": main()
""" This is a pure Python implementation of Dynamic Programming solution to the fibonacci sequence problem. """ class Fibonacci: def __init__(self) -> None: self.sequence = [0, 1] def get(self, index: int) -> list: """ Get the Fibonacci number of `index`. If the number does not exist, calculate all missing numbers leading up to the number of `index`. >>> Fibonacci().get(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] >>> Fibonacci().get(5) [0, 1, 1, 2, 3] """ if (difference := index - (len(self.sequence) - 2)) >= 1: for _ in range(difference): self.sequence.append(self.sequence[-1] + self.sequence[-2]) return self.sequence[:index] def main(): print( "Fibonacci Series Using Dynamic Programming\n", "Enter the index of the Fibonacci number you want to calculate ", "in the prompt below. (To exit enter exit or Ctrl-C)\n", sep="", ) fibonacci = Fibonacci() while True: prompt: str = input(">> ") if prompt in {"exit", "quit"}: break try: index: int = int(prompt) except ValueError: print("Enter a number or 'exit'") continue print(fibonacci.get(index)) if __name__ == "__main__": main()
1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other 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) eta = k11 + k22 - 2.0 * k12 # select the new alpha2 which could get the minimal objectives if eta > 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,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import re def indian_phone_validator(phone: str) -> bool: """ Determine whether the string is a valid phone number or not :param phone: :return: Boolean >>> indian_phone_validator("+91123456789") False >>> indian_phone_validator("+919876543210") True >>> indian_phone_validator("01234567896") False >>> indian_phone_validator("919876543218") True >>> indian_phone_validator("+91-1234567899") False >>> indian_phone_validator("+91-9876543218") True """ pat = re.compile(r"^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$") match = re.search(pat, phone) if match: return match.string == phone return False if __name__ == "__main__": print(indian_phone_validator("+918827897895"))
import re def indian_phone_validator(phone: str) -> bool: """ Determine whether the string is a valid phone number or not :param phone: :return: Boolean >>> indian_phone_validator("+91123456789") False >>> indian_phone_validator("+919876543210") True >>> indian_phone_validator("01234567896") False >>> indian_phone_validator("919876543218") True >>> indian_phone_validator("+91-1234567899") False >>> indian_phone_validator("+91-9876543218") True """ pat = re.compile(r"^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$") if match := re.search(pat, phone): return match.string == phone return False if __name__ == "__main__": print(indian_phone_validator("+918827897895"))
1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 3: https://projecteuler.net/problem=3 Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? References: - https://en.wikipedia.org/wiki/Prime_number#Unique_factorization """ def solution(n: int = 600851475143) -> int: """ Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 >>> solution(3.4) 3 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") prime = 1 i = 2 while i * i <= n: while n % i == 0: prime = i n //= i i += 1 if n > 1: prime = n return int(prime) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 3: https://projecteuler.net/problem=3 Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? References: - https://en.wikipedia.org/wiki/Prime_number#Unique_factorization """ def solution(n: int = 600851475143) -> int: """ Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 >>> solution(3.4) 3 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") prime = 1 i = 2 while i * i <= n: while n % i == 0: prime = i n //= i i += 1 if n > 1: prime = n return int(prime) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 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 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,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Source : https://computersciencewiki.org/index.php/Max-pooling_/_Pooling # Importing the libraries import numpy as np from PIL import Image # Maxpooling Function def maxpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: """ This function is used to perform maxpooling on the input array of 2D matrix(image) Args: arr: numpy array size: size of pooling matrix stride: the number of pixels shifts over the input matrix Returns: numpy array of maxpooled matrix Sample Input Output: >>> maxpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2) array([[ 6., 8.], [14., 16.]]) >>> maxpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1) array([[241., 180.], [241., 157.]]) """ arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") i = 0 j = 0 mat_i = 0 mat_j = 0 # compute the shape of the output matrix maxpool_shape = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape updated_arr = np.zeros((maxpool_shape, maxpool_shape)) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix updated_arr[mat_i][mat_j] = np.max(arr[i : i + size, j : j + size]) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 j = 0 mat_j = 0 return updated_arr # Averagepooling Function def avgpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: """ This function is used to perform avgpooling on the input array of 2D matrix(image) Args: arr: numpy array size: size of pooling matrix stride: the number of pixels shifts over the input matrix Returns: numpy array of avgpooled matrix Sample Input Output: >>> avgpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2) array([[ 3., 5.], [11., 13.]]) >>> avgpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1) array([[161., 102.], [114., 69.]]) """ arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") i = 0 j = 0 mat_i = 0 mat_j = 0 # compute the shape of the output matrix avgpool_shape = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape updated_arr = np.zeros((avgpool_shape, avgpool_shape)) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix updated_arr[mat_i][mat_j] = int(np.average(arr[i : i + size, j : j + size])) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 j = 0 mat_j = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="avgpooling", verbose=True) # Loading the image image = Image.open("path_to_image") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
# Source : https://computersciencewiki.org/index.php/Max-pooling_/_Pooling # Importing the libraries import numpy as np from PIL import Image # Maxpooling Function def maxpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: """ This function is used to perform maxpooling on the input array of 2D matrix(image) Args: arr: numpy array size: size of pooling matrix stride: the number of pixels shifts over the input matrix Returns: numpy array of maxpooled matrix Sample Input Output: >>> maxpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2) array([[ 6., 8.], [14., 16.]]) >>> maxpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1) array([[241., 180.], [241., 157.]]) """ arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") i = 0 j = 0 mat_i = 0 mat_j = 0 # compute the shape of the output matrix maxpool_shape = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape updated_arr = np.zeros((maxpool_shape, maxpool_shape)) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix updated_arr[mat_i][mat_j] = np.max(arr[i : i + size, j : j + size]) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 j = 0 mat_j = 0 return updated_arr # Averagepooling Function def avgpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: """ This function is used to perform avgpooling on the input array of 2D matrix(image) Args: arr: numpy array size: size of pooling matrix stride: the number of pixels shifts over the input matrix Returns: numpy array of avgpooled matrix Sample Input Output: >>> avgpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2) array([[ 3., 5.], [11., 13.]]) >>> avgpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1) array([[161., 102.], [114., 69.]]) """ arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") i = 0 j = 0 mat_i = 0 mat_j = 0 # compute the shape of the output matrix avgpool_shape = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape updated_arr = np.zeros((avgpool_shape, avgpool_shape)) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix updated_arr[mat_i][mat_j] = int(np.average(arr[i : i + size, j : j + size])) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 j = 0 mat_j = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="avgpooling", verbose=True) # Loading the image image = Image.open("path_to_image") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#
#
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Peak signal-to-noise ratio - PSNR https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio Source: https://tutorials.techonical.com/how-to-calculate-psnr-value-of-two-images-using-python """ import math import os import cv2 import numpy as np PIXEL_MAX = 255.0 def peak_signal_to_noise_ratio(original: float, contrast: float) -> float: mse = np.mean((original - contrast) ** 2) if mse == 0: return 100 return 20 * math.log10(PIXEL_MAX / math.sqrt(mse)) def main() -> None: dir_path = os.path.dirname(os.path.realpath(__file__)) # Loading images (original image and compressed image) original = cv2.imread(os.path.join(dir_path, "image_data/original_image.png")) contrast = cv2.imread(os.path.join(dir_path, "image_data/compressed_image.png"), 1) original2 = cv2.imread(os.path.join(dir_path, "image_data/PSNR-example-base.png")) contrast2 = cv2.imread( os.path.join(dir_path, "image_data/PSNR-example-comp-10.jpg"), 1 ) # Value expected: 29.73dB print("-- First Test --") print(f"PSNR value is {peak_signal_to_noise_ratio(original, contrast)} dB") # # Value expected: 31.53dB (Wikipedia Example) print("\n-- Second Test --") print(f"PSNR value is {peak_signal_to_noise_ratio(original2, contrast2)} dB") if __name__ == "__main__": main()
""" Peak signal-to-noise ratio - PSNR https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio Source: https://tutorials.techonical.com/how-to-calculate-psnr-value-of-two-images-using-python """ import math import os import cv2 import numpy as np PIXEL_MAX = 255.0 def peak_signal_to_noise_ratio(original: float, contrast: float) -> float: mse = np.mean((original - contrast) ** 2) if mse == 0: return 100 return 20 * math.log10(PIXEL_MAX / math.sqrt(mse)) def main() -> None: dir_path = os.path.dirname(os.path.realpath(__file__)) # Loading images (original image and compressed image) original = cv2.imread(os.path.join(dir_path, "image_data/original_image.png")) contrast = cv2.imread(os.path.join(dir_path, "image_data/compressed_image.png"), 1) original2 = cv2.imread(os.path.join(dir_path, "image_data/PSNR-example-base.png")) contrast2 = cv2.imread( os.path.join(dir_path, "image_data/PSNR-example-comp-10.jpg"), 1 ) # Value expected: 29.73dB print("-- First Test --") print(f"PSNR value is {peak_signal_to_noise_ratio(original, contrast)} dB") # # Value expected: 31.53dB (Wikipedia Example) print("\n-- Second Test --") print(f"PSNR value is {peak_signal_to_noise_ratio(original2, contrast2)} dB") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import math from collections.abc import Generator def slow_primes(max_n: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(slow_primes(0)) [] >>> list(slow_primes(-1)) [] >>> list(slow_primes(-10)) [] >>> list(slow_primes(25)) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> list(slow_primes(11)) [2, 3, 5, 7, 11] >>> list(slow_primes(33)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] >>> list(slow_primes(10000))[-1] 9973 """ numbers: Generator = (i for i in range(1, (max_n + 1))) for i in (n for n in numbers if n > 1): for j in range(2, i): if (i % j) == 0: break else: yield i def primes(max_n: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(primes(0)) [] >>> list(primes(-1)) [] >>> list(primes(-10)) [] >>> list(primes(25)) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> list(primes(11)) [2, 3, 5, 7, 11] >>> list(primes(33)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] >>> list(primes(10000))[-1] 9973 """ numbers: Generator = (i for i in range(1, (max_n + 1))) for i in (n for n in numbers if n > 1): # only need to check for factors up to sqrt(i) bound = int(math.sqrt(i)) + 1 for j in range(2, bound): if (i % j) == 0: break else: yield i def fast_primes(max_n: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(fast_primes(0)) [] >>> list(fast_primes(-1)) [] >>> list(fast_primes(-10)) [] >>> list(fast_primes(25)) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> list(fast_primes(11)) [2, 3, 5, 7, 11] >>> list(fast_primes(33)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] >>> list(fast_primes(10000))[-1] 9973 """ numbers: Generator = (i for i in range(1, (max_n + 1), 2)) # It's useless to test even numbers as they will not be prime if max_n > 2: yield 2 # Because 2 will not be tested, it's necessary to yield it now for i in (n for n in numbers if n > 1): bound = int(math.sqrt(i)) + 1 for j in range(3, bound, 2): # As we removed the even numbers, we don't need them now if (i % j) == 0: break else: yield i if __name__ == "__main__": number = int(input("Calculate primes up to:\n>> ").strip()) for ret in primes(number): print(ret) # Let's benchmark them side-by-side... from timeit import timeit print( timeit( "slow_primes(1_000_000_000_000)", setup="from __main__ import slow_primes", number=1_000_000, ) ) print( timeit( "primes(1_000_000_000_000)", setup="from __main__ import primes", number=1_000_000, ) ) print( timeit( "fast_primes(1_000_000_000_000)", setup="from __main__ import fast_primes", number=1_000_000, ) )
import math from collections.abc import Generator def slow_primes(max_n: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(slow_primes(0)) [] >>> list(slow_primes(-1)) [] >>> list(slow_primes(-10)) [] >>> list(slow_primes(25)) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> list(slow_primes(11)) [2, 3, 5, 7, 11] >>> list(slow_primes(33)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] >>> list(slow_primes(10000))[-1] 9973 """ numbers: Generator = (i for i in range(1, (max_n + 1))) for i in (n for n in numbers if n > 1): for j in range(2, i): if (i % j) == 0: break else: yield i def primes(max_n: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(primes(0)) [] >>> list(primes(-1)) [] >>> list(primes(-10)) [] >>> list(primes(25)) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> list(primes(11)) [2, 3, 5, 7, 11] >>> list(primes(33)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] >>> list(primes(10000))[-1] 9973 """ numbers: Generator = (i for i in range(1, (max_n + 1))) for i in (n for n in numbers if n > 1): # only need to check for factors up to sqrt(i) bound = int(math.sqrt(i)) + 1 for j in range(2, bound): if (i % j) == 0: break else: yield i def fast_primes(max_n: int) -> Generator[int, None, None]: """ Return a list of all primes numbers up to max. >>> list(fast_primes(0)) [] >>> list(fast_primes(-1)) [] >>> list(fast_primes(-10)) [] >>> list(fast_primes(25)) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> list(fast_primes(11)) [2, 3, 5, 7, 11] >>> list(fast_primes(33)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] >>> list(fast_primes(10000))[-1] 9973 """ numbers: Generator = (i for i in range(1, (max_n + 1), 2)) # It's useless to test even numbers as they will not be prime if max_n > 2: yield 2 # Because 2 will not be tested, it's necessary to yield it now for i in (n for n in numbers if n > 1): bound = int(math.sqrt(i)) + 1 for j in range(3, bound, 2): # As we removed the even numbers, we don't need them now if (i % j) == 0: break else: yield i if __name__ == "__main__": number = int(input("Calculate primes up to:\n>> ").strip()) for ret in primes(number): print(ret) # Let's benchmark them side-by-side... from timeit import timeit print( timeit( "slow_primes(1_000_000_000_000)", setup="from __main__ import slow_primes", number=1_000_000, ) ) print( timeit( "primes(1_000_000_000_000)", setup="from __main__ import primes", number=1_000_000, ) ) print( timeit( "fast_primes(1_000_000_000_000)", setup="from __main__ import fast_primes", number=1_000_000, ) )
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Compression Data compression is everywhere, you need it to store data without taking too much space. Either the compression lose some data (then we talk about lossy compression, such as .jpg) or it does not (and then it is lossless compression, such as .png) Lossless compression is mainly used for archive purpose as it allow storing data without losing information about the file archived. On the other hand, lossy compression is used for transfer of file where quality isn't necessarily what is required (i.e: images on Twitter). * <https://www.sciencedirect.com/topics/computer-science/compression-algorithm> * <https://en.wikipedia.org/wiki/Data_compression> * <https://en.wikipedia.org/wiki/Pigeonhole_principle>
# Compression Data compression is everywhere, you need it to store data without taking too much space. Either the compression lose some data (then we talk about lossy compression, such as .jpg) or it does not (and then it is lossless compression, such as .png) Lossless compression is mainly used for archive purpose as it allow storing data without losing information about the file archived. On the other hand, lossy compression is used for transfer of file where quality isn't necessarily what is required (i.e: images on Twitter). * <https://www.sciencedirect.com/topics/computer-science/compression-algorithm> * <https://en.wikipedia.org/wiki/Data_compression> * <https://en.wikipedia.org/wiki/Pigeonhole_principle>
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# floyd_warshall.py """ The problem is to find the shortest distance between all pairs of vertices in a weighted directed graph that can have negative edge weights. """ def _print_dist(dist, v): print("\nThe shortest path matrix using Floyd Warshall algorithm\n") for i in range(v): for j in range(v): if dist[i][j] != float("inf"): print(int(dist[i][j]), end="\t") else: print("INF", end="\t") print() def floyd_warshall(graph, v): """ :param graph: 2D array calculated from weight[edge[i, j]] :type graph: List[List[float]] :param v: number of vertices :type v: int :return: shortest distance between all vertex pairs distance[u][v] will contain the shortest distance from vertex u to v. 1. For all edges from v to n, distance[i][j] = weight(edge(i, j)). 3. The algorithm then performs distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j]) for each possible pair i, j of vertices. 4. The above is repeated for each vertex k in the graph. 5. Whenever distance[i][j] is given a new minimum value, next vertex[i][j] is updated to the next vertex[i][k]. """ dist = [[float("inf") for _ in range(v)] for _ in range(v)] for i in range(v): for j in range(v): dist[i][j] = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(v): # looping through rows of graph array for i in range(v): # looping through columns of graph array for j in range(v): if ( dist[i][k] != float("inf") and dist[k][j] != float("inf") and dist[i][k] + dist[k][j] < dist[i][j] ): dist[i][j] = dist[i][k] + dist[k][j] _print_dist(dist, v) return dist, v if __name__ == "__main__": v = int(input("Enter number of vertices: ")) e = int(input("Enter number of edges: ")) graph = [[float("inf") for i in range(v)] for j in range(v)] for i in range(v): graph[i][i] = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print("\nEdge ", i + 1) src = int(input("Enter source:")) dst = int(input("Enter destination:")) weight = float(input("Enter weight:")) graph[src][dst] = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
# floyd_warshall.py """ The problem is to find the shortest distance between all pairs of vertices in a weighted directed graph that can have negative edge weights. """ def _print_dist(dist, v): print("\nThe shortest path matrix using Floyd Warshall algorithm\n") for i in range(v): for j in range(v): if dist[i][j] != float("inf"): print(int(dist[i][j]), end="\t") else: print("INF", end="\t") print() def floyd_warshall(graph, v): """ :param graph: 2D array calculated from weight[edge[i, j]] :type graph: List[List[float]] :param v: number of vertices :type v: int :return: shortest distance between all vertex pairs distance[u][v] will contain the shortest distance from vertex u to v. 1. For all edges from v to n, distance[i][j] = weight(edge(i, j)). 3. The algorithm then performs distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j]) for each possible pair i, j of vertices. 4. The above is repeated for each vertex k in the graph. 5. Whenever distance[i][j] is given a new minimum value, next vertex[i][j] is updated to the next vertex[i][k]. """ dist = [[float("inf") for _ in range(v)] for _ in range(v)] for i in range(v): for j in range(v): dist[i][j] = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(v): # looping through rows of graph array for i in range(v): # looping through columns of graph array for j in range(v): if ( dist[i][k] != float("inf") and dist[k][j] != float("inf") and dist[i][k] + dist[k][j] < dist[i][j] ): dist[i][j] = dist[i][k] + dist[k][j] _print_dist(dist, v) return dist, v if __name__ == "__main__": v = int(input("Enter number of vertices: ")) e = int(input("Enter number of edges: ")) graph = [[float("inf") for i in range(v)] for j in range(v)] for i in range(v): graph[i][i] = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print("\nEdge ", i + 1) src = int(input("Enter source:")) dst = int(input("Enter destination:")) weight = float(input("Enter weight:")) graph[src][dst] = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" wiki: https://en.wikipedia.org/wiki/Pangram """ def is_pangram( input_str: str = "The quick brown fox jumps over the lazy dog", ) -> bool: """ A Pangram String contains all the alphabets at least once. >>> is_pangram("The quick brown fox jumps over the lazy dog") True >>> is_pangram("Waltz, bad nymph, for quick jigs vex.") True >>> is_pangram("Jived fox nymph grabs quick waltz.") True >>> is_pangram("My name is Unknown") False >>> is_pangram("The quick brown fox jumps over the la_y dog") False >>> is_pangram() True """ # Declare frequency as a set to have unique occurrences of letters frequency = set() # Replace all the whitespace in our sentence input_str = input_str.replace(" ", "") for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower()) return len(frequency) == 26 def is_pangram_faster( input_str: str = "The quick brown fox jumps over the lazy dog", ) -> bool: """ >>> is_pangram_faster("The quick brown fox jumps over the lazy dog") True >>> is_pangram_faster("Waltz, bad nymph, for quick jigs vex.") True >>> is_pangram_faster("Jived fox nymph grabs quick waltz.") True >>> is_pangram_faster("The quick brown fox jumps over the la_y dog") False >>> is_pangram_faster() True """ flag = [False] * 26 for char in input_str: if char.islower(): flag[ord(char) - 97] = True elif char.isupper(): flag[ord(char) - 65] = True return all(flag) def is_pangram_fastest( input_str: str = "The quick brown fox jumps over the lazy dog", ) -> bool: """ >>> is_pangram_fastest("The quick brown fox jumps over the lazy dog") True >>> is_pangram_fastest("Waltz, bad nymph, for quick jigs vex.") True >>> is_pangram_fastest("Jived fox nymph grabs quick waltz.") True >>> is_pangram_fastest("The quick brown fox jumps over the la_y dog") False >>> is_pangram_fastest() True """ return len({char for char in input_str.lower() if char.isalpha()}) == 26 def benchmark() -> None: """ Benchmark code comparing different version. """ from timeit import timeit setup = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest" print(timeit("is_pangram()", setup=setup)) print(timeit("is_pangram_faster()", setup=setup)) print(timeit("is_pangram_fastest()", setup=setup)) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
""" wiki: https://en.wikipedia.org/wiki/Pangram """ def is_pangram( input_str: str = "The quick brown fox jumps over the lazy dog", ) -> bool: """ A Pangram String contains all the alphabets at least once. >>> is_pangram("The quick brown fox jumps over the lazy dog") True >>> is_pangram("Waltz, bad nymph, for quick jigs vex.") True >>> is_pangram("Jived fox nymph grabs quick waltz.") True >>> is_pangram("My name is Unknown") False >>> is_pangram("The quick brown fox jumps over the la_y dog") False >>> is_pangram() True """ # Declare frequency as a set to have unique occurrences of letters frequency = set() # Replace all the whitespace in our sentence input_str = input_str.replace(" ", "") for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower()) return len(frequency) == 26 def is_pangram_faster( input_str: str = "The quick brown fox jumps over the lazy dog", ) -> bool: """ >>> is_pangram_faster("The quick brown fox jumps over the lazy dog") True >>> is_pangram_faster("Waltz, bad nymph, for quick jigs vex.") True >>> is_pangram_faster("Jived fox nymph grabs quick waltz.") True >>> is_pangram_faster("The quick brown fox jumps over the la_y dog") False >>> is_pangram_faster() True """ flag = [False] * 26 for char in input_str: if char.islower(): flag[ord(char) - 97] = True elif char.isupper(): flag[ord(char) - 65] = True return all(flag) def is_pangram_fastest( input_str: str = "The quick brown fox jumps over the lazy dog", ) -> bool: """ >>> is_pangram_fastest("The quick brown fox jumps over the lazy dog") True >>> is_pangram_fastest("Waltz, bad nymph, for quick jigs vex.") True >>> is_pangram_fastest("Jived fox nymph grabs quick waltz.") True >>> is_pangram_fastest("The quick brown fox jumps over the la_y dog") False >>> is_pangram_fastest() True """ return len({char for char in input_str.lower() if char.isalpha()}) == 26 def benchmark() -> None: """ Benchmark code comparing different version. """ from timeit import timeit setup = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest" print(timeit("is_pangram()", setup=setup)) print(timeit("is_pangram_faster()", setup=setup)) print(timeit("is_pangram_fastest()", setup=setup)) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 116: https://projecteuler.net/problem=116 A row of five grey square tiles is to have a number of its tiles replaced with coloured oblong tiles chosen from red (length two), green (length three), or blue (length four). If red tiles are chosen there are exactly seven ways this can be done. |red,red|grey|grey|grey| |grey|red,red|grey|grey| |grey|grey|red,red|grey| |grey|grey|grey|red,red| |red,red|red,red|grey| |red,red|grey|red,red| |grey|red,red|red,red| If green tiles are chosen there are three ways. |green,green,green|grey|grey| |grey|green,green,green|grey| |grey|grey|green,green,green| And if blue tiles are chosen there are two ways. |blue,blue,blue,blue|grey| |grey|blue,blue,blue,blue| Assuming that colours cannot be mixed there are 7 + 3 + 2 = 12 ways of replacing the grey tiles in a row measuring five units in length. How many different ways can the grey tiles in a row measuring fifty units in length be replaced if colours cannot be mixed and at least one coloured tile must be used? NOTE: This is related to Problem 117 (https://projecteuler.net/problem=117). """ def solution(length: int = 50) -> int: """ Returns the number of different ways can the grey tiles in a row of the given length be replaced if colours cannot be mixed and at least one coloured tile must be used >>> solution(5) 12 """ different_colour_ways_number = [[0] * 3 for _ in range(length + 1)] for row_length in range(length + 1): for tile_length in range(2, 5): for tile_start in range(row_length - tile_length + 1): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length]) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 116: https://projecteuler.net/problem=116 A row of five grey square tiles is to have a number of its tiles replaced with coloured oblong tiles chosen from red (length two), green (length three), or blue (length four). If red tiles are chosen there are exactly seven ways this can be done. |red,red|grey|grey|grey| |grey|red,red|grey|grey| |grey|grey|red,red|grey| |grey|grey|grey|red,red| |red,red|red,red|grey| |red,red|grey|red,red| |grey|red,red|red,red| If green tiles are chosen there are three ways. |green,green,green|grey|grey| |grey|green,green,green|grey| |grey|grey|green,green,green| And if blue tiles are chosen there are two ways. |blue,blue,blue,blue|grey| |grey|blue,blue,blue,blue| Assuming that colours cannot be mixed there are 7 + 3 + 2 = 12 ways of replacing the grey tiles in a row measuring five units in length. How many different ways can the grey tiles in a row measuring fifty units in length be replaced if colours cannot be mixed and at least one coloured tile must be used? NOTE: This is related to Problem 117 (https://projecteuler.net/problem=117). """ def solution(length: int = 50) -> int: """ Returns the number of different ways can the grey tiles in a row of the given length be replaced if colours cannot be mixed and at least one coloured tile must be used >>> solution(5) 12 """ different_colour_ways_number = [[0] * 3 for _ in range(length + 1)] for row_length in range(length + 1): for tile_length in range(2, 5): for tile_start in range(row_length - tile_length + 1): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length]) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Name scores Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? """ import os def solution(): """Returns the total of all the name scores in the file. >>> solution() 871198282 """ total_sum = 0 temp_sum = 0 with open(os.path.dirname(__file__) + "/p022_names.txt") as file: name = str(file.readlines()[0]) name = name.replace('"', "").split(",") name.sort() for i in range(len(name)): for j in name[i]: temp_sum += ord(j) - ord("A") + 1 total_sum += (i + 1) * temp_sum temp_sum = 0 return total_sum if __name__ == "__main__": print(solution())
""" Name scores Problem 22 Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file? """ import os def solution(): """Returns the total of all the name scores in the file. >>> solution() 871198282 """ total_sum = 0 temp_sum = 0 with open(os.path.dirname(__file__) + "/p022_names.txt") as file: name = str(file.readlines()[0]) name = name.replace('"', "").split(",") name.sort() for i in range(len(name)): for j in name[i]: temp_sum += ord(j) - ord("A") + 1 total_sum += (i + 1) * temp_sum temp_sum = 0 return total_sum if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 8: https://projecteuler.net/problem=8 Largest product in a series The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ from functools import reduce N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def solution(n: str = N) -> int: """ Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. >>> solution("13978431290823798458352374") 609638400 >>> solution("13978431295823798458352374") 2612736000 >>> solution("1397843129582379841238352374") 209018880 """ return max( # mypy cannot properly interpret reduce int(reduce(lambda x, y: str(int(x) * int(y)), n[i : i + 13])) for i in range(len(n) - 12) ) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 8: https://projecteuler.net/problem=8 Largest product in a series The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ from functools import reduce N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def solution(n: str = N) -> int: """ Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. >>> solution("13978431290823798458352374") 609638400 >>> solution("13978431295823798458352374") 2612736000 >>> solution("1397843129582379841238352374") 209018880 """ return max( # mypy cannot properly interpret reduce int(reduce(lambda x, y: str(int(x) * int(y)), n[i : i + 13])) for i in range(len(n) - 12) ) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Borůvka's algorithm. Determines the minimum spanning tree (MST) of a graph using the Borůvka's algorithm. Borůvka's algorithm is a greedy algorithm for finding a minimum spanning tree in a connected graph, or a minimum spanning forest if a graph that is not connected. The time complexity of this algorithm is O(ELogV), where E represents the number of edges, while V represents the number of nodes. O(number_of_edges Log number_of_nodes) The space complexity of this algorithm is O(V + E), since we have to keep a couple of lists whose sizes are equal to the number of nodes, as well as keep all the edges of a graph inside of the data structure itself. Borůvka's algorithm gives us pretty much the same result as other MST Algorithms - they all find the minimum spanning tree, and the time complexity is approximately the same. One advantage that Borůvka's algorithm has compared to the alternatives is that it doesn't need to presort the edges or maintain a priority queue in order to find the minimum spanning tree. Even though that doesn't help its complexity, since it still passes the edges logE times, it is a bit simpler to code. Details: https://en.wikipedia.org/wiki/Bor%C5%AFvka%27s_algorithm """ from __future__ import annotations from typing import Any class Graph: def __init__(self, num_of_nodes: int) -> None: """ Arguments: num_of_nodes - the number of nodes in the graph Attributes: m_num_of_nodes - the number of nodes in the graph. m_edges - the list of edges. m_component - the dictionary which stores the index of the component which a node belongs to. """ self.m_num_of_nodes = num_of_nodes self.m_edges: list[list[int]] = [] self.m_component: dict[int, int] = {} def add_edge(self, u_node: int, v_node: int, weight: int) -> None: """Adds an edge in the format [first, second, edge weight] to graph.""" self.m_edges.append([u_node, v_node, weight]) def find_component(self, u_node: int) -> int: """Propagates a new component throughout a given component.""" if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node]) def set_component(self, u_node: int) -> None: """Finds the component index of a given node""" if self.m_component[u_node] != u_node: for k in self.m_component: self.m_component[k] = self.find_component(k) def union(self, component_size: list[int], u_node: int, v_node: int) -> None: """Union finds the roots of components for two nodes, compares the components in terms of size, and attaches the smaller one to the larger one to form single component""" if component_size[u_node] <= component_size[v_node]: self.m_component[u_node] = v_node component_size[v_node] += component_size[u_node] self.set_component(u_node) elif component_size[u_node] >= component_size[v_node]: self.m_component[v_node] = self.find_component(u_node) component_size[u_node] += component_size[v_node] self.set_component(v_node) def boruvka(self) -> None: """Performs Borůvka's algorithm to find MST.""" # Initialize additional lists required to algorithm. component_size = [] mst_weight = 0 minimum_weight_edge: list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes): self.m_component.update({node: node}) component_size.append(1) num_of_components = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: u, v, w = edge u_component = self.m_component[u] v_component = self.m_component[v] if u_component != v_component: """If the current minimum weight edge of component u doesn't exist (is -1), or if it's greater than the edge we're observing right now, we will assign the value of the edge we're observing to it. If the current minimum weight edge of component v doesn't exist (is -1), or if it's greater than the edge we're observing right now, we will assign the value of the edge we're observing to it""" for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): minimum_weight_edge[component] = [u, v, w] for edge in minimum_weight_edge: if isinstance(edge, list): u, v, w = edge u_component = self.m_component[u] v_component = self.m_component[v] if u_component != v_component: mst_weight += w self.union(component_size, u_component, v_component) print(f"Added edge [{u} - {v}]\nAdded weight: {w}\n") num_of_components -= 1 minimum_weight_edge = [-1] * self.m_num_of_nodes print(f"The total weight of the minimal spanning tree is: {mst_weight}") def test_vector() -> None: """ >>> g = Graph(8) >>> for u_v_w in ((0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4), ... (3, 4, 8), (4, 5, 10), (4, 6, 6), (4, 7, 5), (5, 7, 15), (6, 7, 4)): ... g.add_edge(*u_v_w) >>> g.boruvka() Added edge [0 - 3] Added weight: 5 <BLANKLINE> Added edge [0 - 1] Added weight: 10 <BLANKLINE> Added edge [2 - 3] Added weight: 4 <BLANKLINE> Added edge [4 - 7] Added weight: 5 <BLANKLINE> Added edge [4 - 5] Added weight: 10 <BLANKLINE> Added edge [6 - 7] Added weight: 4 <BLANKLINE> Added edge [3 - 4] Added weight: 8 <BLANKLINE> The total weight of the minimal spanning tree is: 46 """ if __name__ == "__main__": import doctest doctest.testmod()
"""Borůvka's algorithm. Determines the minimum spanning tree (MST) of a graph using the Borůvka's algorithm. Borůvka's algorithm is a greedy algorithm for finding a minimum spanning tree in a connected graph, or a minimum spanning forest if a graph that is not connected. The time complexity of this algorithm is O(ELogV), where E represents the number of edges, while V represents the number of nodes. O(number_of_edges Log number_of_nodes) The space complexity of this algorithm is O(V + E), since we have to keep a couple of lists whose sizes are equal to the number of nodes, as well as keep all the edges of a graph inside of the data structure itself. Borůvka's algorithm gives us pretty much the same result as other MST Algorithms - they all find the minimum spanning tree, and the time complexity is approximately the same. One advantage that Borůvka's algorithm has compared to the alternatives is that it doesn't need to presort the edges or maintain a priority queue in order to find the minimum spanning tree. Even though that doesn't help its complexity, since it still passes the edges logE times, it is a bit simpler to code. Details: https://en.wikipedia.org/wiki/Bor%C5%AFvka%27s_algorithm """ from __future__ import annotations from typing import Any class Graph: def __init__(self, num_of_nodes: int) -> None: """ Arguments: num_of_nodes - the number of nodes in the graph Attributes: m_num_of_nodes - the number of nodes in the graph. m_edges - the list of edges. m_component - the dictionary which stores the index of the component which a node belongs to. """ self.m_num_of_nodes = num_of_nodes self.m_edges: list[list[int]] = [] self.m_component: dict[int, int] = {} def add_edge(self, u_node: int, v_node: int, weight: int) -> None: """Adds an edge in the format [first, second, edge weight] to graph.""" self.m_edges.append([u_node, v_node, weight]) def find_component(self, u_node: int) -> int: """Propagates a new component throughout a given component.""" if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node]) def set_component(self, u_node: int) -> None: """Finds the component index of a given node""" if self.m_component[u_node] != u_node: for k in self.m_component: self.m_component[k] = self.find_component(k) def union(self, component_size: list[int], u_node: int, v_node: int) -> None: """Union finds the roots of components for two nodes, compares the components in terms of size, and attaches the smaller one to the larger one to form single component""" if component_size[u_node] <= component_size[v_node]: self.m_component[u_node] = v_node component_size[v_node] += component_size[u_node] self.set_component(u_node) elif component_size[u_node] >= component_size[v_node]: self.m_component[v_node] = self.find_component(u_node) component_size[u_node] += component_size[v_node] self.set_component(v_node) def boruvka(self) -> None: """Performs Borůvka's algorithm to find MST.""" # Initialize additional lists required to algorithm. component_size = [] mst_weight = 0 minimum_weight_edge: list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes): self.m_component.update({node: node}) component_size.append(1) num_of_components = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: u, v, w = edge u_component = self.m_component[u] v_component = self.m_component[v] if u_component != v_component: """If the current minimum weight edge of component u doesn't exist (is -1), or if it's greater than the edge we're observing right now, we will assign the value of the edge we're observing to it. If the current minimum weight edge of component v doesn't exist (is -1), or if it's greater than the edge we're observing right now, we will assign the value of the edge we're observing to it""" for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): minimum_weight_edge[component] = [u, v, w] for edge in minimum_weight_edge: if isinstance(edge, list): u, v, w = edge u_component = self.m_component[u] v_component = self.m_component[v] if u_component != v_component: mst_weight += w self.union(component_size, u_component, v_component) print(f"Added edge [{u} - {v}]\nAdded weight: {w}\n") num_of_components -= 1 minimum_weight_edge = [-1] * self.m_num_of_nodes print(f"The total weight of the minimal spanning tree is: {mst_weight}") def test_vector() -> None: """ >>> g = Graph(8) >>> for u_v_w in ((0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4), ... (3, 4, 8), (4, 5, 10), (4, 6, 6), (4, 7, 5), (5, 7, 15), (6, 7, 4)): ... g.add_edge(*u_v_w) >>> g.boruvka() Added edge [0 - 3] Added weight: 5 <BLANKLINE> Added edge [0 - 1] Added weight: 10 <BLANKLINE> Added edge [2 - 3] Added weight: 4 <BLANKLINE> Added edge [4 - 7] Added weight: 5 <BLANKLINE> Added edge [4 - 5] Added weight: 10 <BLANKLINE> Added edge [6 - 7] Added weight: 4 <BLANKLINE> Added edge [3 - 4] Added weight: 8 <BLANKLINE> The total weight of the minimal spanning tree is: 46 """ if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A XNOR Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are different, and 1 (True), if the inputs are same. It's similar to adding a NOT gate to an XOR gate Following is the truth table of a XNOR Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 1 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 1 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def xnor_gate(input_1: int, input_2: int) -> int: """ Calculate XOR of the input values >>> xnor_gate(0, 0) 1 >>> xnor_gate(0, 1) 0 >>> xnor_gate(1, 0) 0 >>> xnor_gate(1, 1) 1 """ return 1 if input_1 == input_2 else 0 def test_xnor_gate() -> None: """ Tests the xnor_gate function """ assert xnor_gate(0, 0) == 1 assert xnor_gate(0, 1) == 0 assert xnor_gate(1, 0) == 0 assert xnor_gate(1, 1) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
""" A XNOR Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are different, and 1 (True), if the inputs are same. It's similar to adding a NOT gate to an XOR gate Following is the truth table of a XNOR Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 1 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 1 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def xnor_gate(input_1: int, input_2: int) -> int: """ Calculate XOR of the input values >>> xnor_gate(0, 0) 1 >>> xnor_gate(0, 1) 0 >>> xnor_gate(1, 0) 0 >>> xnor_gate(1, 1) 1 """ return 1 if input_1 == input_2 else 0 def test_xnor_gate() -> None: """ Tests the xnor_gate function """ assert xnor_gate(0, 0) == 1 assert xnor_gate(0, 1) == 0 assert xnor_gate(1, 0) == 0 assert xnor_gate(1, 1) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""example of simple chaos machine""" # Chaos Machine (K, t, m) K = [0.33, 0.44, 0.55, 0.44, 0.33] t = 3 m = 5 # Buffer Space (with Parameters Space) buffer_space: list[float] = [] params_space: list[float] = [] # Machine Time machine_time = 0 def push(seed): global buffer_space, params_space, machine_time, K, m, t # Choosing Dynamical Systems (All) for key, value in enumerate(buffer_space): # Evolution Parameter e = float(seed / value) # Control Theory: Orbit Change value = (buffer_space[(key + 1) % m] + e) % 1 # Control Theory: Trajectory Change r = (params_space[key] + e) % 1 + 3 # Modification (Transition Function) - Jumps buffer_space[key] = round(float(r * value * (1 - value)), 10) params_space[key] = r # Saving to Parameters Space # Logistic Map assert max(buffer_space) < 1 assert max(params_space) < 4 # Machine Time machine_time += 1 def pull(): global buffer_space, params_space, machine_time, K, m, t # PRNG (Xorshift by George Marsaglia) def xorshift(x, y): x ^= y >> 13 y ^= x << 17 x ^= y >> 5 return x # Choosing Dynamical Systems (Increment) key = machine_time % m # Evolution (Time Length) for _ in range(0, t): # Variables (Position + Parameters) r = params_space[key] value = buffer_space[key] # Modification (Transition Function) - Flow buffer_space[key] = round(float(r * value * (1 - value)), 10) params_space[key] = (machine_time * 0.01 + r * 1.01) % 1 + 3 # Choosing Chaotic Data x = int(buffer_space[(key + 2) % m] * (10**10)) y = int(buffer_space[(key - 2) % m] * (10**10)) # Machine Time machine_time += 1 return xorshift(x, y) % 0xFFFFFFFF def reset(): global buffer_space, params_space, machine_time, K, m, t buffer_space = K params_space = [0] * m machine_time = 0 if __name__ == "__main__": # Initialization reset() # Pushing Data (Input) import random message = random.sample(range(0xFFFFFFFF), 100) for chunk in message: push(chunk) # for controlling inp = "" # Pulling Data (Output) while inp in ("e", "E"): print(f"{format(pull(), '#04x')}") print(buffer_space) print(params_space) inp = input("(e)exit? ").strip()
"""example of simple chaos machine""" # Chaos Machine (K, t, m) K = [0.33, 0.44, 0.55, 0.44, 0.33] t = 3 m = 5 # Buffer Space (with Parameters Space) buffer_space: list[float] = [] params_space: list[float] = [] # Machine Time machine_time = 0 def push(seed): global buffer_space, params_space, machine_time, K, m, t # Choosing Dynamical Systems (All) for key, value in enumerate(buffer_space): # Evolution Parameter e = float(seed / value) # Control Theory: Orbit Change value = (buffer_space[(key + 1) % m] + e) % 1 # Control Theory: Trajectory Change r = (params_space[key] + e) % 1 + 3 # Modification (Transition Function) - Jumps buffer_space[key] = round(float(r * value * (1 - value)), 10) params_space[key] = r # Saving to Parameters Space # Logistic Map assert max(buffer_space) < 1 assert max(params_space) < 4 # Machine Time machine_time += 1 def pull(): global buffer_space, params_space, machine_time, K, m, t # PRNG (Xorshift by George Marsaglia) def xorshift(x, y): x ^= y >> 13 y ^= x << 17 x ^= y >> 5 return x # Choosing Dynamical Systems (Increment) key = machine_time % m # Evolution (Time Length) for _ in range(0, t): # Variables (Position + Parameters) r = params_space[key] value = buffer_space[key] # Modification (Transition Function) - Flow buffer_space[key] = round(float(r * value * (1 - value)), 10) params_space[key] = (machine_time * 0.01 + r * 1.01) % 1 + 3 # Choosing Chaotic Data x = int(buffer_space[(key + 2) % m] * (10**10)) y = int(buffer_space[(key - 2) % m] * (10**10)) # Machine Time machine_time += 1 return xorshift(x, y) % 0xFFFFFFFF def reset(): global buffer_space, params_space, machine_time, K, m, t buffer_space = K params_space = [0] * m machine_time = 0 if __name__ == "__main__": # Initialization reset() # Pushing Data (Input) import random message = random.sample(range(0xFFFFFFFF), 100) for chunk in message: push(chunk) # for controlling inp = "" # Pulling Data (Output) while inp in ("e", "E"): print(f"{format(pull(), '#04x')}") print(buffer_space) print(params_space) inp = input("(e)exit? ").strip()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other 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
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Illustrate how to implement inorder traversal in binary search tree. Author: Gurneet Singh https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/ """ class BinaryTreeNode: """Defining the structure of BinaryTreeNode""" def __init__(self, data: int) -> None: self.data = data self.left_child: BinaryTreeNode | None = None self.right_child: BinaryTreeNode | None = None def insert(node: BinaryTreeNode | None, new_value: int) -> BinaryTreeNode | None: """ If the binary search tree is empty, make a new node and declare it as root. >>> node_a = BinaryTreeNode(12345) >>> node_b = insert(node_a, 67890) >>> node_a.left_child == node_b.left_child True >>> node_a.right_child == node_b.right_child True >>> node_a.data == node_b.data True """ if node is None: node = BinaryTreeNode(new_value) return node # binary search tree is not empty, # so we will insert it into the tree # if new_value is less than value of data in node, # add it to left subtree and proceed recursively if new_value < node.data: node.left_child = insert(node.left_child, new_value) else: # if new_value is greater than value of data in node, # add it to right subtree and proceed recursively node.right_child = insert(node.right_child, new_value) return node def inorder(node: None | BinaryTreeNode) -> list[int]: # if node is None,return """ >>> inorder(make_tree()) [6, 10, 14, 15, 20, 25, 60] """ if node: inorder_array = inorder(node.left_child) inorder_array = inorder_array + [node.data] inorder_array = inorder_array + inorder(node.right_child) else: inorder_array = [] return inorder_array def make_tree() -> BinaryTreeNode | None: root = insert(None, 15) insert(root, 10) insert(root, 25) insert(root, 6) insert(root, 14) insert(root, 20) insert(root, 60) return root def main() -> None: # main function root = make_tree() print("Printing values of binary search tree in Inorder Traversal.") inorder(root) if __name__ == "__main__": import doctest doctest.testmod() main()
""" Illustrate how to implement inorder traversal in binary search tree. Author: Gurneet Singh https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/ """ class BinaryTreeNode: """Defining the structure of BinaryTreeNode""" def __init__(self, data: int) -> None: self.data = data self.left_child: BinaryTreeNode | None = None self.right_child: BinaryTreeNode | None = None def insert(node: BinaryTreeNode | None, new_value: int) -> BinaryTreeNode | None: """ If the binary search tree is empty, make a new node and declare it as root. >>> node_a = BinaryTreeNode(12345) >>> node_b = insert(node_a, 67890) >>> node_a.left_child == node_b.left_child True >>> node_a.right_child == node_b.right_child True >>> node_a.data == node_b.data True """ if node is None: node = BinaryTreeNode(new_value) return node # binary search tree is not empty, # so we will insert it into the tree # if new_value is less than value of data in node, # add it to left subtree and proceed recursively if new_value < node.data: node.left_child = insert(node.left_child, new_value) else: # if new_value is greater than value of data in node, # add it to right subtree and proceed recursively node.right_child = insert(node.right_child, new_value) return node def inorder(node: None | BinaryTreeNode) -> list[int]: # if node is None,return """ >>> inorder(make_tree()) [6, 10, 14, 15, 20, 25, 60] """ if node: inorder_array = inorder(node.left_child) inorder_array = inorder_array + [node.data] inorder_array = inorder_array + inorder(node.right_child) else: inorder_array = [] return inorder_array def make_tree() -> BinaryTreeNode | None: root = insert(None, 15) insert(root, 10) insert(root, 25) insert(root, 6) insert(root, 14) insert(root, 20) insert(root, 60) return root def main() -> None: # main function root = make_tree() print("Printing values of binary search tree in Inorder Traversal.") inorder(root) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Author: João Gustavo A. Amorim & Gabriel Kunz # Author email: [email protected] and [email protected] # Coding date: apr 2019 # Black: True """ * This code implement the Hamming code: https://en.wikipedia.org/wiki/Hamming_code - In telecommunication, Hamming codes are a family of linear error-correcting codes. Hamming codes can detect up to two-bit errors or correct one-bit errors without detection of uncorrected errors. By contrast, the simple parity code cannot correct errors, and can detect only an odd number of bits in error. Hamming codes are perfect codes, that is, they achieve the highest possible rate for codes with their block length and minimum distance of three. * the implemented code consists of: * a function responsible for encoding the message (emitterConverter) * return the encoded message * a function responsible for decoding the message (receptorConverter) * return the decoded message and a ack of data integrity * how to use: to be used you must declare how many parity bits (sizePari) you want to include in the message. it is desired (for test purposes) to select a bit to be set as an error. This serves to check whether the code is working correctly. Lastly, the variable of the message/word that must be desired to be encoded (text). * how this work: declaration of variables (sizePari, be, text) converts the message/word (text) to binary using the text_to_bits function encodes the message using the rules of hamming encoding decodes the message using the rules of hamming encoding print the original message, the encoded message and the decoded message forces an error in the coded text variable decodes the message that was forced the error print the original message, the encoded message, the bit changed message and the decoded message """ # Imports import numpy as np # Functions of binary conversion-------------------------------------- def text_to_bits(text, encoding="utf-8", errors="surrogatepass"): """ >>> text_to_bits("msg") '011011010111001101100111' """ bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) def text_from_bits(bits, encoding="utf-8", errors="surrogatepass"): """ >>> text_from_bits('011011010111001101100111') 'msg' """ n = int(bits, 2) return n.to_bytes((n.bit_length() + 7) // 8, "big").decode(encoding, errors) or "\0" # Functions of hamming code------------------------------------------- def emitter_converter(size_par, data): """ :param size_par: how many parity bits the message must have :param data: information bits :return: message to be transmitted by unreliable medium - bits of information merged with parity bits >>> emitter_converter(4, "101010111111") ['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1'] """ if size_par + len(data) <= 2**size_par - (len(data) - 1): raise ValueError("size of parity don't match with size of data") data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data) + 1)] # sorted information data for the size of the output data data_ord = [] # data position template + parity data_out_gab = [] # parity bit counter qtd_bp = 0 # counter position of data bits cont_data = 0 for x in range(1, size_par + len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par: if (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a given parity cont_bo = 0 # counter to control the loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1": if x == "1": cont_bo += 1 cont_loop += 1 parity.append(cont_bo % 2) qtd_bp += 1 # Mount the message cont_bp = 0 # parity bit counter for x in range(0, size_par + len(data)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) return data_out def receptor_converter(size_par, data): """ >>> receptor_converter(4, "1111010010111111") (['1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1'], True) """ # data position template + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 # list of parity received parity_received = [] data_output = [] for x in range(1, len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_output.append(data[cont_data]) else: parity_received.append(data[cont_data]) cont_data += 1 # -----------calculates the parity with the data data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data_output) + 1)] # sorted information data for the size of the output data data_ord = [] # Data position feedback + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 for x in range(1, size_par + len(data_output) + 1): # Performs a template position of bits - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data_output[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a certain parity cont_bo = 0 # Counter to control loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1" and x == "1": cont_bo += 1 cont_loop += 1 parity.append(str(cont_bo % 2)) qtd_bp += 1 # Mount the message cont_bp = 0 # Parity bit counter for x in range(0, size_par + len(data_output)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) ack = parity_received == parity return data_output, ack # --------------------------------------------------------------------- """ # Example how to use # number of parity bits sizePari = 4 # location of the bit that will be forced an error be = 2 # Message/word to be encoded and decoded with hamming # text = input("Enter the word to be read: ") text = "Message01" # Convert the message to binary binaryText = text_to_bits(text) # Prints the binary of the string print("Text input in binary is '" + binaryText + "'") # total transmitted bits totalBits = len(binaryText) + sizePari print("Size of data is " + str(totalBits)) print("\n --Message exchange--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) print("\n --Force error--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) # forces error dataOut[-be] = "1" * (dataOut[-be] == "0") + "0" * (dataOut[-be] == "1") print("Data after transmission -> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) """
# Author: João Gustavo A. Amorim & Gabriel Kunz # Author email: [email protected] and [email protected] # Coding date: apr 2019 # Black: True """ * This code implement the Hamming code: https://en.wikipedia.org/wiki/Hamming_code - In telecommunication, Hamming codes are a family of linear error-correcting codes. Hamming codes can detect up to two-bit errors or correct one-bit errors without detection of uncorrected errors. By contrast, the simple parity code cannot correct errors, and can detect only an odd number of bits in error. Hamming codes are perfect codes, that is, they achieve the highest possible rate for codes with their block length and minimum distance of three. * the implemented code consists of: * a function responsible for encoding the message (emitterConverter) * return the encoded message * a function responsible for decoding the message (receptorConverter) * return the decoded message and a ack of data integrity * how to use: to be used you must declare how many parity bits (sizePari) you want to include in the message. it is desired (for test purposes) to select a bit to be set as an error. This serves to check whether the code is working correctly. Lastly, the variable of the message/word that must be desired to be encoded (text). * how this work: declaration of variables (sizePari, be, text) converts the message/word (text) to binary using the text_to_bits function encodes the message using the rules of hamming encoding decodes the message using the rules of hamming encoding print the original message, the encoded message and the decoded message forces an error in the coded text variable decodes the message that was forced the error print the original message, the encoded message, the bit changed message and the decoded message """ # Imports import numpy as np # Functions of binary conversion-------------------------------------- def text_to_bits(text, encoding="utf-8", errors="surrogatepass"): """ >>> text_to_bits("msg") '011011010111001101100111' """ bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) def text_from_bits(bits, encoding="utf-8", errors="surrogatepass"): """ >>> text_from_bits('011011010111001101100111') 'msg' """ n = int(bits, 2) return n.to_bytes((n.bit_length() + 7) // 8, "big").decode(encoding, errors) or "\0" # Functions of hamming code------------------------------------------- def emitter_converter(size_par, data): """ :param size_par: how many parity bits the message must have :param data: information bits :return: message to be transmitted by unreliable medium - bits of information merged with parity bits >>> emitter_converter(4, "101010111111") ['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1'] """ if size_par + len(data) <= 2**size_par - (len(data) - 1): raise ValueError("size of parity don't match with size of data") data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data) + 1)] # sorted information data for the size of the output data data_ord = [] # data position template + parity data_out_gab = [] # parity bit counter qtd_bp = 0 # counter position of data bits cont_data = 0 for x in range(1, size_par + len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par: if (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a given parity cont_bo = 0 # counter to control the loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1": if x == "1": cont_bo += 1 cont_loop += 1 parity.append(cont_bo % 2) qtd_bp += 1 # Mount the message cont_bp = 0 # parity bit counter for x in range(0, size_par + len(data)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) return data_out def receptor_converter(size_par, data): """ >>> receptor_converter(4, "1111010010111111") (['1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1'], True) """ # data position template + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 # list of parity received parity_received = [] data_output = [] for x in range(1, len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_output.append(data[cont_data]) else: parity_received.append(data[cont_data]) cont_data += 1 # -----------calculates the parity with the data data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data_output) + 1)] # sorted information data for the size of the output data data_ord = [] # Data position feedback + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 for x in range(1, size_par + len(data_output) + 1): # Performs a template position of bits - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data_output[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a certain parity cont_bo = 0 # Counter to control loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1" and x == "1": cont_bo += 1 cont_loop += 1 parity.append(str(cont_bo % 2)) qtd_bp += 1 # Mount the message cont_bp = 0 # Parity bit counter for x in range(0, size_par + len(data_output)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) ack = parity_received == parity return data_output, ack # --------------------------------------------------------------------- """ # Example how to use # number of parity bits sizePari = 4 # location of the bit that will be forced an error be = 2 # Message/word to be encoded and decoded with hamming # text = input("Enter the word to be read: ") text = "Message01" # Convert the message to binary binaryText = text_to_bits(text) # Prints the binary of the string print("Text input in binary is '" + binaryText + "'") # total transmitted bits totalBits = len(binaryText) + sizePari print("Size of data is " + str(totalBits)) print("\n --Message exchange--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) print("\n --Force error--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) # forces error dataOut[-be] = "1" * (dataOut[-be] == "0") + "0" * (dataOut[-be] == "1") print("Data after transmission -> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) """
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#
#
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
class FlowNetwork: def __init__(self, graph, sources, sinks): self.source_index = None self.sink_index = None self.graph = graph self._normalize_graph(sources, sinks) self.vertices_count = len(graph) self.maximum_flow_algorithm = None # make only one source and one sink def _normalize_graph(self, sources, sinks): if sources is int: sources = [sources] if sinks is int: sinks = [sinks] if len(sources) == 0 or len(sinks) == 0: return self.source_index = sources[0] self.sink_index = sinks[0] # make fake vertex if there are more # than one source or sink if len(sources) > 1 or len(sinks) > 1: max_input_flow = 0 for i in sources: max_input_flow += sum(self.graph[i]) size = len(self.graph) + 1 for room in self.graph: room.insert(0, 0) self.graph.insert(0, [0] * size) for i in sources: self.graph[0][i + 1] = max_input_flow self.source_index = 0 size = len(self.graph) + 1 for room in self.graph: room.append(0) self.graph.append([0] * size) for i in sinks: self.graph[i + 1][size - 1] = max_input_flow self.sink_index = size - 1 def find_maximum_flow(self): if self.maximum_flow_algorithm is None: raise Exception("You need to set maximum flow algorithm before.") if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def set_maximum_flow_algorithm(self, algorithm): self.maximum_flow_algorithm = algorithm(self) class FlowNetworkAlgorithmExecutor: def __init__(self, flow_network): self.flow_network = flow_network self.verticies_count = flow_network.verticesCount self.source_index = flow_network.sourceIndex self.sink_index = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that self.graph = flow_network.graph self.executed = False def execute(self): if not self.executed: self._algorithm() self.executed = True # You should override it def _algorithm(self): pass class MaximumFlowAlgorithmExecutor(FlowNetworkAlgorithmExecutor): def __init__(self, flow_network): super().__init__(flow_network) # use this to save your result self.maximum_flow = -1 def get_maximum_flow(self): if not self.executed: raise Exception("You should execute algorithm before using its result!") return self.maximum_flow class PushRelabelExecutor(MaximumFlowAlgorithmExecutor): def __init__(self, flow_network): super().__init__(flow_network) self.preflow = [[0] * self.verticies_count for i in range(self.verticies_count)] self.heights = [0] * self.verticies_count self.excesses = [0] * self.verticies_count def _algorithm(self): self.heights[self.source_index] = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index]): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule vertices_list = [ i for i in range(self.verticies_count) if i != self.source_index and i != self.sink_index ] # move through list i = 0 while i < len(vertices_list): vertex_index = vertices_list[i] previous_height = self.heights[vertex_index] self.process_vertex(vertex_index) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0, vertices_list.pop(i)) i = 0 else: i += 1 self.maximum_flow = sum(self.preflow[self.source_index]) def process_vertex(self, vertex_index): while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(vertex_index, neighbour_index) self.relabel(vertex_index) def push(self, from_index, to_index): preflow_delta = min( self.excesses[from_index], self.graph[from_index][to_index] - self.preflow[from_index][to_index], ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def relabel(self, vertex_index): min_height = None for to_index in range(self.verticies_count): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ): if min_height is None or self.heights[to_index] < min_height: min_height = self.heights[to_index] if min_height is not None: self.heights[vertex_index] = min_height + 1 if __name__ == "__main__": entrances = [0] exits = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] graph = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network flow_network = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate maximum_flow = flow_network.find_maximum_flow() print(f"maximum flow is {maximum_flow}")
class FlowNetwork: def __init__(self, graph, sources, sinks): self.source_index = None self.sink_index = None self.graph = graph self._normalize_graph(sources, sinks) self.vertices_count = len(graph) self.maximum_flow_algorithm = None # make only one source and one sink def _normalize_graph(self, sources, sinks): if sources is int: sources = [sources] if sinks is int: sinks = [sinks] if len(sources) == 0 or len(sinks) == 0: return self.source_index = sources[0] self.sink_index = sinks[0] # make fake vertex if there are more # than one source or sink if len(sources) > 1 or len(sinks) > 1: max_input_flow = 0 for i in sources: max_input_flow += sum(self.graph[i]) size = len(self.graph) + 1 for room in self.graph: room.insert(0, 0) self.graph.insert(0, [0] * size) for i in sources: self.graph[0][i + 1] = max_input_flow self.source_index = 0 size = len(self.graph) + 1 for room in self.graph: room.append(0) self.graph.append([0] * size) for i in sinks: self.graph[i + 1][size - 1] = max_input_flow self.sink_index = size - 1 def find_maximum_flow(self): if self.maximum_flow_algorithm is None: raise Exception("You need to set maximum flow algorithm before.") if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def set_maximum_flow_algorithm(self, algorithm): self.maximum_flow_algorithm = algorithm(self) class FlowNetworkAlgorithmExecutor: def __init__(self, flow_network): self.flow_network = flow_network self.verticies_count = flow_network.verticesCount self.source_index = flow_network.sourceIndex self.sink_index = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that self.graph = flow_network.graph self.executed = False def execute(self): if not self.executed: self._algorithm() self.executed = True # You should override it def _algorithm(self): pass class MaximumFlowAlgorithmExecutor(FlowNetworkAlgorithmExecutor): def __init__(self, flow_network): super().__init__(flow_network) # use this to save your result self.maximum_flow = -1 def get_maximum_flow(self): if not self.executed: raise Exception("You should execute algorithm before using its result!") return self.maximum_flow class PushRelabelExecutor(MaximumFlowAlgorithmExecutor): def __init__(self, flow_network): super().__init__(flow_network) self.preflow = [[0] * self.verticies_count for i in range(self.verticies_count)] self.heights = [0] * self.verticies_count self.excesses = [0] * self.verticies_count def _algorithm(self): self.heights[self.source_index] = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index]): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule vertices_list = [ i for i in range(self.verticies_count) if i != self.source_index and i != self.sink_index ] # move through list i = 0 while i < len(vertices_list): vertex_index = vertices_list[i] previous_height = self.heights[vertex_index] self.process_vertex(vertex_index) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0, vertices_list.pop(i)) i = 0 else: i += 1 self.maximum_flow = sum(self.preflow[self.source_index]) def process_vertex(self, vertex_index): while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(vertex_index, neighbour_index) self.relabel(vertex_index) def push(self, from_index, to_index): preflow_delta = min( self.excesses[from_index], self.graph[from_index][to_index] - self.preflow[from_index][to_index], ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def relabel(self, vertex_index): min_height = None for to_index in range(self.verticies_count): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ): if min_height is None or self.heights[to_index] < min_height: min_height = self.heights[to_index] if min_height is not None: self.heights[vertex_index] = min_height + 1 if __name__ == "__main__": entrances = [0] exits = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] graph = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network flow_network = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate maximum_flow = flow_network.find_maximum_flow() print(f"maximum flow is {maximum_flow}")
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
class Graph: def __init__(self, vertex): self.vertex = vertex self.graph = [[0] * vertex for i in range(vertex)] def add_edge(self, u, v): self.graph[u - 1][v - 1] = 1 self.graph[v - 1][u - 1] = 1 def show(self): for i in self.graph: for j in i: print(j, end=" ") print(" ") g = Graph(100) g.add_edge(1, 4) g.add_edge(4, 2) g.add_edge(4, 5) g.add_edge(2, 5) g.add_edge(5, 3) g.show()
class Graph: def __init__(self, vertex): self.vertex = vertex self.graph = [[0] * vertex for i in range(vertex)] def add_edge(self, u, v): self.graph[u - 1][v - 1] = 1 self.graph[v - 1][u - 1] = 1 def show(self): for i in self.graph: for j in i: print(j, end=" ") print(" ") g = Graph(100) g.add_edge(1, 4) g.add_edge(4, 2) g.add_edge(4, 5) g.add_edge(2, 5) g.add_edge(5, 3) g.show()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 115: https://projecteuler.net/problem=115 NOTE: This is a more difficult version of Problem 114 (https://projecteuler.net/problem=114). A row measuring n units in length has red blocks with a minimum length of m units placed on it, such that any two red blocks (which are allowed to be different lengths) are separated by at least one black square. Let the fill-count function, F(m, n), represent the number of ways that a row can be filled. For example, F(3, 29) = 673135 and F(3, 30) = 1089155. That is, for m = 3, it can be seen that n = 30 is the smallest value for which the fill-count function first exceeds one million. In the same way, for m = 10, it can be verified that F(10, 56) = 880711 and F(10, 57) = 1148904, so n = 57 is the least value for which the fill-count function first exceeds one million. For m = 50, find the least value of n for which the fill-count function first exceeds one million. """ from itertools import count def solution(min_block_length: int = 50) -> int: """ Returns for given minimum block length the least value of n for which the fill-count function first exceeds one million >>> solution(3) 30 >>> solution(10) 57 """ fill_count_functions = [1] * min_block_length for n in count(min_block_length): fill_count_functions.append(1) for block_length in range(min_block_length, n + 1): for block_start in range(n - block_length): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_000_000: break return n if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 115: https://projecteuler.net/problem=115 NOTE: This is a more difficult version of Problem 114 (https://projecteuler.net/problem=114). A row measuring n units in length has red blocks with a minimum length of m units placed on it, such that any two red blocks (which are allowed to be different lengths) are separated by at least one black square. Let the fill-count function, F(m, n), represent the number of ways that a row can be filled. For example, F(3, 29) = 673135 and F(3, 30) = 1089155. That is, for m = 3, it can be seen that n = 30 is the smallest value for which the fill-count function first exceeds one million. In the same way, for m = 10, it can be verified that F(10, 56) = 880711 and F(10, 57) = 1148904, so n = 57 is the least value for which the fill-count function first exceeds one million. For m = 50, find the least value of n for which the fill-count function first exceeds one million. """ from itertools import count def solution(min_block_length: int = 50) -> int: """ Returns for given minimum block length the least value of n for which the fill-count function first exceeds one million >>> solution(3) 30 >>> solution(10) 57 """ fill_count_functions = [1] * min_block_length for n in count(min_block_length): fill_count_functions.append(1) for block_length in range(min_block_length, n + 1): for block_start in range(n - block_length): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_000_000: break return n if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""Breath First Search (BFS) can be used when finding the shortest path from a given source node to a target node in an unweighted graph. """ from __future__ import annotations graph = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } class Graph: def __init__(self, graph: dict[str, list[str]], source_vertex: str) -> None: """ Graph is implemented as dictionary of adjacency lists. Also, Source vertex have to be defined upon initialization. """ self.graph = graph # mapping node to its parent in resulting breadth first tree self.parent: dict[str, str | None] = {} self.source_vertex = source_vertex def breath_first_search(self) -> None: """ This function is a helper for running breath first search on this graph. >>> g = Graph(graph, "G") >>> g.breath_first_search() >>> g.parent {'G': None, 'C': 'G', 'A': 'C', 'F': 'C', 'B': 'A', 'E': 'A', 'D': 'B'} """ visited = {self.source_vertex} self.parent[self.source_vertex] = None queue = [self.source_vertex] # first in first out queue while queue: vertex = queue.pop(0) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(adjacent_vertex) self.parent[adjacent_vertex] = vertex queue.append(adjacent_vertex) def shortest_path(self, target_vertex: str) -> str: """ This shortest path function returns a string, describing the result: 1.) No path is found. The string is a human readable message to indicate this. 2.) The shortest path is found. The string is in the form `v1(->v2->v3->...->vn)`, where v1 is the source vertex and vn is the target vertex, if it exists separately. >>> g = Graph(graph, "G") >>> g.breath_first_search() Case 1 - No path is found. >>> g.shortest_path("Foo") 'No path from vertex:G to vertex:Foo' Case 2 - The path is found. >>> g.shortest_path("D") 'G->C->A->B->D' >>> g.shortest_path("G") 'G' """ if target_vertex == self.source_vertex: return self.source_vertex target_vertex_parent = self.parent.get(target_vertex) if target_vertex_parent is None: return f"No path from vertex:{self.source_vertex} to vertex:{target_vertex}" return self.shortest_path(target_vertex_parent) + f"->{target_vertex}" if __name__ == "__main__": g = Graph(graph, "G") g.breath_first_search() print(g.shortest_path("D")) print(g.shortest_path("G")) print(g.shortest_path("Foo"))
"""Breath First Search (BFS) can be used when finding the shortest path from a given source node to a target node in an unweighted graph. """ from __future__ import annotations graph = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } class Graph: def __init__(self, graph: dict[str, list[str]], source_vertex: str) -> None: """ Graph is implemented as dictionary of adjacency lists. Also, Source vertex have to be defined upon initialization. """ self.graph = graph # mapping node to its parent in resulting breadth first tree self.parent: dict[str, str | None] = {} self.source_vertex = source_vertex def breath_first_search(self) -> None: """ This function is a helper for running breath first search on this graph. >>> g = Graph(graph, "G") >>> g.breath_first_search() >>> g.parent {'G': None, 'C': 'G', 'A': 'C', 'F': 'C', 'B': 'A', 'E': 'A', 'D': 'B'} """ visited = {self.source_vertex} self.parent[self.source_vertex] = None queue = [self.source_vertex] # first in first out queue while queue: vertex = queue.pop(0) for adjacent_vertex in self.graph[vertex]: if adjacent_vertex not in visited: visited.add(adjacent_vertex) self.parent[adjacent_vertex] = vertex queue.append(adjacent_vertex) def shortest_path(self, target_vertex: str) -> str: """ This shortest path function returns a string, describing the result: 1.) No path is found. The string is a human readable message to indicate this. 2.) The shortest path is found. The string is in the form `v1(->v2->v3->...->vn)`, where v1 is the source vertex and vn is the target vertex, if it exists separately. >>> g = Graph(graph, "G") >>> g.breath_first_search() Case 1 - No path is found. >>> g.shortest_path("Foo") 'No path from vertex:G to vertex:Foo' Case 2 - The path is found. >>> g.shortest_path("D") 'G->C->A->B->D' >>> g.shortest_path("G") 'G' """ if target_vertex == self.source_vertex: return self.source_vertex target_vertex_parent = self.parent.get(target_vertex) if target_vertex_parent is None: return f"No path from vertex:{self.source_vertex} to vertex:{target_vertex}" return self.shortest_path(target_vertex_parent) + f"->{target_vertex}" if __name__ == "__main__": g = Graph(graph, "G") g.breath_first_search() print(g.shortest_path("D")) print(g.shortest_path("G")) print(g.shortest_path("Foo"))
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 4: https://projecteuler.net/problem=4 Largest palindrome product A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. References: - https://en.wikipedia.org/wiki/Palindromic_number """ def solution(n: int = 998001) -> int: """ Returns the largest palindrome made from the product of two 3-digit numbers which is less than n. >>> solution(20000) 19591 >>> solution(30000) 29992 >>> solution(40000) 39893 >>> solution(10000) Traceback (most recent call last): ... ValueError: That number is larger than our acceptable range. """ # fetches the next number for number in range(n - 1, 9999, -1): str_number = str(number) # checks whether 'str_number' is a palindrome. if str_number == str_number[::-1]: divisor = 999 # if 'number' is a product of two 3-digit numbers # then number is the answer otherwise fetch next number. while divisor != 99: if (number % divisor == 0) and (len(str(number // divisor)) == 3.0): return number divisor -= 1 raise ValueError("That number is larger than our acceptable range.") if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 4: https://projecteuler.net/problem=4 Largest palindrome product A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. References: - https://en.wikipedia.org/wiki/Palindromic_number """ def solution(n: int = 998001) -> int: """ Returns the largest palindrome made from the product of two 3-digit numbers which is less than n. >>> solution(20000) 19591 >>> solution(30000) 29992 >>> solution(40000) 39893 >>> solution(10000) Traceback (most recent call last): ... ValueError: That number is larger than our acceptable range. """ # fetches the next number for number in range(n - 1, 9999, -1): str_number = str(number) # checks whether 'str_number' is a palindrome. if str_number == str_number[::-1]: divisor = 999 # if 'number' is a product of two 3-digit numbers # then number is the answer otherwise fetch next number. while divisor != 99: if (number % divisor == 0) and (len(str(number // divisor)) == 3.0): return number divisor -= 1 raise ValueError("That number is larger than our acceptable range.") if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 201 210 What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? """ from itertools import permutations def solution(): """Returns the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. >>> solution() '2783915460' """ result = list(map("".join, permutations("0123456789"))) return result[999999] if __name__ == "__main__": print(solution())
""" A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 201 210 What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? """ from itertools import permutations def solution(): """Returns the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. >>> solution() '2783915460' """ result = list(map("".join, permutations("0123456789"))) return result[999999] if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_xor(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, return a binary number that is the result of a binary xor operation on the integers provided. >>> binary_xor(25, 32) '0b111001' >>> binary_xor(37, 50) '0b010111' >>> binary_xor(21, 30) '0b01011' >>> binary_xor(58, 73) '0b1110011' >>> binary_xor(0, 255) '0b11111111' >>> binary_xor(256, 256) '0b000000000' >>> binary_xor(0, -1) Traceback (most recent call last): ... ValueError: the value of both inputs must be positive >>> binary_xor(0, 1.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binary_xor("0", "1") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive") a_binary = str(bin(a))[2:] # remove the leading "0b" b_binary = str(bin(b))[2:] # remove the leading "0b" max_len = max(len(a_binary), len(b_binary)) return "0b" + "".join( str(int(char_a != char_b)) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) ) if __name__ == "__main__": import doctest doctest.testmod()
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_xor(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, return a binary number that is the result of a binary xor operation on the integers provided. >>> binary_xor(25, 32) '0b111001' >>> binary_xor(37, 50) '0b010111' >>> binary_xor(21, 30) '0b01011' >>> binary_xor(58, 73) '0b1110011' >>> binary_xor(0, 255) '0b11111111' >>> binary_xor(256, 256) '0b000000000' >>> binary_xor(0, -1) Traceback (most recent call last): ... ValueError: the value of both inputs must be positive >>> binary_xor(0, 1.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binary_xor("0", "1") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive") a_binary = str(bin(a))[2:] # remove the leading "0b" b_binary = str(bin(b))[2:] # remove the leading "0b" max_len = max(len(a_binary), len(b_binary)) return "0b" + "".join( str(int(char_a != char_b)) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) ) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other 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,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Isolate the Decimal part of a Number https://stackoverflow.com/questions/3886402/how-to-get-numbers-after-decimal-point """ def decimal_isolate(number: float, digit_amount: int) -> float: """ Isolates the decimal part of a number. If digitAmount > 0 round to that decimal place, else print the entire decimal. >>> decimal_isolate(1.53, 0) 0.53 >>> decimal_isolate(35.345, 1) 0.3 >>> decimal_isolate(35.345, 2) 0.34 >>> decimal_isolate(35.345, 3) 0.345 >>> decimal_isolate(-14.789, 3) -0.789 >>> decimal_isolate(0, 2) 0 >>> decimal_isolate(-14.123, 1) -0.1 >>> decimal_isolate(-14.123, 2) -0.12 >>> decimal_isolate(-14.123, 3) -0.123 """ if digit_amount > 0: return round(number - int(number), digit_amount) return number - int(number) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
""" Isolate the Decimal part of a Number https://stackoverflow.com/questions/3886402/how-to-get-numbers-after-decimal-point """ def decimal_isolate(number: float, digit_amount: int) -> float: """ Isolates the decimal part of a number. If digitAmount > 0 round to that decimal place, else print the entire decimal. >>> decimal_isolate(1.53, 0) 0.53 >>> decimal_isolate(35.345, 1) 0.3 >>> decimal_isolate(35.345, 2) 0.34 >>> decimal_isolate(35.345, 3) 0.345 >>> decimal_isolate(-14.789, 3) -0.789 >>> decimal_isolate(0, 2) 0 >>> decimal_isolate(-14.123, 1) -0.1 >>> decimal_isolate(-14.123, 2) -0.12 >>> decimal_isolate(-14.123, 3) -0.123 """ if digit_amount > 0: return round(number - int(number), digit_amount) return number - int(number) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" wiki: https://en.wikipedia.org/wiki/Heterogram_(literature)#Isograms """ def is_isogram(string: str) -> bool: """ An isogram is a word in which no letter is repeated. Examples of isograms are uncopyrightable and ambidextrously. >>> is_isogram('Uncopyrightable') True >>> is_isogram('allowance') False >>> is_isogram('copy1') Traceback (most recent call last): ... ValueError: String must only contain alphabetic characters. """ if not all(x.isalpha() for x in string): raise ValueError("String must only contain alphabetic characters.") letters = sorted(string.lower()) return len(letters) == len(set(letters)) if __name__ == "__main__": input_str = input("Enter a string ").strip() isogram = is_isogram(input_str) print(f"{input_str} is {'an' if isogram else 'not an'} isogram.")
""" wiki: https://en.wikipedia.org/wiki/Heterogram_(literature)#Isograms """ def is_isogram(string: str) -> bool: """ An isogram is a word in which no letter is repeated. Examples of isograms are uncopyrightable and ambidextrously. >>> is_isogram('Uncopyrightable') True >>> is_isogram('allowance') False >>> is_isogram('copy1') Traceback (most recent call last): ... ValueError: String must only contain alphabetic characters. """ if not all(x.isalpha() for x in string): raise ValueError("String must only contain alphabetic characters.") letters = sorted(string.lower()) return len(letters) == len(set(letters)) if __name__ == "__main__": input_str = input("Enter a string ").strip() isogram = is_isogram(input_str) print(f"{input_str} is {'an' if isogram else 'not an'} isogram.")
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 """ This program calculates the nth Fibonacci number in O(log(n)). It's possible to calculate F(1_000_000) in less than a second. """ from __future__ import annotations import sys def fibonacci(n: int) -> int: """ return F(n) >>> [fibonacci(i) for i in range(13)] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] """ if n < 0: raise ValueError("Negative arguments are not supported") return _fib(n)[0] # returns (F(n), F(n-1)) def _fib(n: int) -> tuple[int, int]: if n == 0: # (F(0), F(1)) return (0, 1) # F(2n) = F(n)[2F(n+1) − F(n)] # F(2n+1) = F(n+1)^2+F(n)^2 a, b = _fib(n // 2) c = a * (b * 2 - a) d = a * a + b * b return (d, c + d) if n % 2 else (c, d) if __name__ == "__main__": n = int(sys.argv[1]) print(f"fibonacci({n}) is {fibonacci(n)}")
#!/usr/bin/env python3 """ This program calculates the nth Fibonacci number in O(log(n)). It's possible to calculate F(1_000_000) in less than a second. """ from __future__ import annotations import sys def fibonacci(n: int) -> int: """ return F(n) >>> [fibonacci(i) for i in range(13)] [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] """ if n < 0: raise ValueError("Negative arguments are not supported") return _fib(n)[0] # returns (F(n), F(n-1)) def _fib(n: int) -> tuple[int, int]: if n == 0: # (F(0), F(1)) return (0, 1) # F(2n) = F(n)[2F(n+1) − F(n)] # F(2n+1) = F(n+1)^2+F(n)^2 a, b = _fib(n // 2) c = a * (b * 2 - a) d = a * a + b * b return (d, c + d) if n % 2 else (c, d) if __name__ == "__main__": n = int(sys.argv[1]) print(f"fibonacci({n}) is {fibonacci(n)}")
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is a pure Python implementation of the P-Series algorithm https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#P-series For doctests run following command: python -m doctest -v p_series.py or python3 -m doctest -v p_series.py For manual testing run: python3 p_series.py """ from __future__ import annotations def p_series(nth_term: int | float | str, power: int | float | str) -> list[str]: """ Pure Python implementation of P-Series algorithm :return: The P-Series starting from 1 to last (nth) term Examples: >>> p_series(5, 2) ['1', '1 / 4', '1 / 9', '1 / 16', '1 / 25'] >>> p_series(-5, 2) [] >>> p_series(5, -2) ['1', '1 / 0.25', '1 / 0.1111111111111111', '1 / 0.0625', '1 / 0.04'] >>> p_series("", 1000) [''] >>> p_series(0, 0) [] >>> p_series(1, 1) ['1'] """ if nth_term == "": return [""] nth_term = int(nth_term) power = int(power) series: list[str] = [] for temp in range(int(nth_term)): series.append(f"1 / {pow(temp + 1, int(power))}" if series else "1") return series if __name__ == "__main__": import doctest doctest.testmod() nth_term = int(input("Enter the last number (nth term) of the P-Series")) power = int(input("Enter the power for P-Series")) print("Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p") print(p_series(nth_term, power))
""" This is a pure Python implementation of the P-Series algorithm https://en.wikipedia.org/wiki/Harmonic_series_(mathematics)#P-series For doctests run following command: python -m doctest -v p_series.py or python3 -m doctest -v p_series.py For manual testing run: python3 p_series.py """ from __future__ import annotations def p_series(nth_term: int | float | str, power: int | float | str) -> list[str]: """ Pure Python implementation of P-Series algorithm :return: The P-Series starting from 1 to last (nth) term Examples: >>> p_series(5, 2) ['1', '1 / 4', '1 / 9', '1 / 16', '1 / 25'] >>> p_series(-5, 2) [] >>> p_series(5, -2) ['1', '1 / 0.25', '1 / 0.1111111111111111', '1 / 0.0625', '1 / 0.04'] >>> p_series("", 1000) [''] >>> p_series(0, 0) [] >>> p_series(1, 1) ['1'] """ if nth_term == "": return [""] nth_term = int(nth_term) power = int(power) series: list[str] = [] for temp in range(int(nth_term)): series.append(f"1 / {pow(temp + 1, int(power))}" if series else "1") return series if __name__ == "__main__": import doctest doctest.testmod() nth_term = int(input("Enter the last number (nth term) of the P-Series")) power = int(input("Enter the power for P-Series")) print("Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p") print(p_series(nth_term, power))
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" README, Author - Jigyasa Gandhi(mailto:[email protected]) Requirements: - scikit-fuzzy - numpy - matplotlib Python: - 3.5 """ import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () X = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). abc1 = [0, 25, 50] abc2 = [25, 50, 75] young = fuzz.membership.trimf(X, abc1) middle_aged = fuzz.membership.trimf(X, abc2) # Compute the different operations using inbuilt functions. one = np.ones(75) zero = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) union = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) intersection = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) complement_a = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) difference = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] alg_sum = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) alg_product = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] bdd_sum = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] bdd_difference = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title("Young") plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title("Middle aged") plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title("union") plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title("intersection") plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title("complement_a") plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title("difference a/b") plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title("alg_sum") plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title("alg_product") plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title("bdd_sum") plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title("bdd_difference") plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
""" README, Author - Jigyasa Gandhi(mailto:[email protected]) Requirements: - scikit-fuzzy - numpy - matplotlib Python: - 3.5 """ import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () X = np.linspace(start=0, stop=75, num=75, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). abc1 = [0, 25, 50] abc2 = [25, 50, 75] young = fuzz.membership.trimf(X, abc1) middle_aged = fuzz.membership.trimf(X, abc2) # Compute the different operations using inbuilt functions. one = np.ones(75) zero = np.zeros((75,)) # 1. Union = max(µA(x), µB(x)) union = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) intersection = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) complement_a = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) difference = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] alg_sum = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) alg_product = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] bdd_sum = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] bdd_difference = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title("Young") plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title("Middle aged") plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title("union") plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title("intersection") plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title("complement_a") plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title("difference a/b") plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title("alg_sum") plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title("alg_product") plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title("bdd_sum") plt.grid(True) plt.subplot(4, 3, 10) plt.plot(X, bdd_difference) plt.title("bdd_difference") plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other 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 kmp(pattern: str, text: str) -> bool: """ The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text with complexity O(n + m) 1) Preprocess pattern to identify any suffixes that are identical to prefixes This tells us where to continue from if we get a mismatch between a character in our pattern and the text. 2) Step through the text one character at a time and compare it to a character in the pattern updating our location within the pattern if necessary """ # 1) Construct the failure array failure = get_failure_array(pattern) # 2) Step through text searching for pattern i, j = 0, 0 # index into text, pattern while i < len(text): if pattern[j] == text[i]: if j == (len(pattern) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: j = failure[j - 1] continue i += 1 return False def get_failure_array(pattern: str) -> list[int]: """ Calculates the new index we should go to if we fail a comparison :param pattern: :return: """ failure = [0] i = 0 j = 1 while j < len(pattern): if pattern[i] == pattern[j]: i += 1 elif i > 0: i = failure[i - 1] continue j += 1 failure.append(i) return failure if __name__ == "__main__": # Test 1) pattern = "abc1abc12" text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc" text2 = "alskfjaldsk23adsfabcabc" assert kmp(pattern, text1) and not kmp(pattern, text2) # Test 2) pattern = "ABABX" text = "ABABZABABYABABX" assert kmp(pattern, text) # Test 3) pattern = "AAAB" text = "ABAAAAAB" assert kmp(pattern, text) # Test 4) pattern = "abcdabcy" text = "abcxabcdabxabcdabcdabcy" assert kmp(pattern, text) # Test 5) pattern = "aabaabaaa" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
from __future__ import annotations def kmp(pattern: str, text: str) -> bool: """ The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text with complexity O(n + m) 1) Preprocess pattern to identify any suffixes that are identical to prefixes This tells us where to continue from if we get a mismatch between a character in our pattern and the text. 2) Step through the text one character at a time and compare it to a character in the pattern updating our location within the pattern if necessary """ # 1) Construct the failure array failure = get_failure_array(pattern) # 2) Step through text searching for pattern i, j = 0, 0 # index into text, pattern while i < len(text): if pattern[j] == text[i]: if j == (len(pattern) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: j = failure[j - 1] continue i += 1 return False def get_failure_array(pattern: str) -> list[int]: """ Calculates the new index we should go to if we fail a comparison :param pattern: :return: """ failure = [0] i = 0 j = 1 while j < len(pattern): if pattern[i] == pattern[j]: i += 1 elif i > 0: i = failure[i - 1] continue j += 1 failure.append(i) return failure if __name__ == "__main__": # Test 1) pattern = "abc1abc12" text1 = "alskfjaldsabc1abc1abc12k23adsfabcabc" text2 = "alskfjaldsk23adsfabcabc" assert kmp(pattern, text1) and not kmp(pattern, text2) # Test 2) pattern = "ABABX" text = "ABABZABABYABABX" assert kmp(pattern, text) # Test 3) pattern = "AAAB" text = "ABAAAAAB" assert kmp(pattern, text) # Test 4) pattern = "abcdabcy" text = "abcxabcdabxabcdabcdabcy" assert kmp(pattern, text) # Test 5) pattern = "aabaabaaa" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 58:https://projecteuler.net/problem=58 Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed. 37 36 35 34 33 32 31 38 17 16 15 14 13 30 39 18 5 4 3 12 29 40 19 6 1 2 11 28 41 20 7 8 9 10 27 42 21 22 23 24 25 26 43 44 45 46 47 48 49 It is interesting to note that the odd squares lie along the bottom right diagonal ,but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%. If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%? Solution: We have to find an odd length side for which square falls below 10%. With every layer we add 4 elements are being added to the diagonals ,lets say we have a square spiral of odd length with side length j, then if we move from j to j+2, we are adding j*j+j+1,j*j+2*(j+1),j*j+3*(j+1) j*j+4*(j+1). Out of these 4 only the first three can become prime because last one reduces to (j+2)*(j+2). So we check individually each one of these before incrementing our count of current primes. """ 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 solution(ratio: float = 0.1) -> int: """ Returns the side length of the square spiral of odd length greater than 1 for which the ratio of primes along both diagonals first falls below the given ratio. >>> solution(.5) 11 >>> solution(.2) 309 >>> solution(.111) 11317 """ j = 3 primes = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1, (j + 2) * (j + 2), j + 1): primes += is_prime(i) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
""" Project Euler Problem 58:https://projecteuler.net/problem=58 Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed. 37 36 35 34 33 32 31 38 17 16 15 14 13 30 39 18 5 4 3 12 29 40 19 6 1 2 11 28 41 20 7 8 9 10 27 42 21 22 23 24 25 26 43 44 45 46 47 48 49 It is interesting to note that the odd squares lie along the bottom right diagonal ,but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%. If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%? Solution: We have to find an odd length side for which square falls below 10%. With every layer we add 4 elements are being added to the diagonals ,lets say we have a square spiral of odd length with side length j, then if we move from j to j+2, we are adding j*j+j+1,j*j+2*(j+1),j*j+3*(j+1) j*j+4*(j+1). Out of these 4 only the first three can become prime because last one reduces to (j+2)*(j+2). So we check individually each one of these before incrementing our count of current primes. """ 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 solution(ratio: float = 0.1) -> int: """ Returns the side length of the square spiral of odd length greater than 1 for which the ratio of primes along both diagonals first falls below the given ratio. >>> solution(.5) 11 >>> solution(.2) 309 >>> solution(.111) 11317 """ j = 3 primes = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1, (j + 2) * (j + 2), j + 1): primes += is_prime(i) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 75: https://projecteuler.net/problem=75 It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, but there are many more examples. 12 cm: (3,4,5) 24 cm: (6,8,10) 30 cm: (5,12,13) 36 cm: (9,12,15) 40 cm: (8,15,17) 48 cm: (12,16,20) In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided right angle triangle, and other lengths allow more than one solution to be found; for example, using 120 cm it is possible to form exactly three different integer sided right angle triangles. 120 cm: (30,40,50), (20,48,52), (24,45,51) Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can exactly one integer sided right angle triangle be formed? Solution: we generate all pythagorean triples using Euclid's formula and keep track of the frequencies of the perimeters. Reference: https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple """ from collections import defaultdict from math import gcd from typing import DefaultDict def solution(limit: int = 1500000) -> int: """ Return the number of values of L <= limit such that a wire of length L can be formmed into an integer sided right angle triangle in exactly one way. >>> solution(50) 6 >>> solution(1000) 112 >>> solution(50000) 5502 """ frequencies: DefaultDict = defaultdict(int) euclid_m = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1, euclid_m, 2): if gcd(euclid_m, euclid_n) > 1: continue primitive_perimeter = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(primitive_perimeter, limit + 1, primitive_perimeter): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 75: https://projecteuler.net/problem=75 It turns out that 12 cm is the smallest length of wire that can be bent to form an integer sided right angle triangle in exactly one way, but there are many more examples. 12 cm: (3,4,5) 24 cm: (6,8,10) 30 cm: (5,12,13) 36 cm: (9,12,15) 40 cm: (8,15,17) 48 cm: (12,16,20) In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided right angle triangle, and other lengths allow more than one solution to be found; for example, using 120 cm it is possible to form exactly three different integer sided right angle triangles. 120 cm: (30,40,50), (20,48,52), (24,45,51) Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can exactly one integer sided right angle triangle be formed? Solution: we generate all pythagorean triples using Euclid's formula and keep track of the frequencies of the perimeters. Reference: https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple """ from collections import defaultdict from math import gcd from typing import DefaultDict def solution(limit: int = 1500000) -> int: """ Return the number of values of L <= limit such that a wire of length L can be formmed into an integer sided right angle triangle in exactly one way. >>> solution(50) 6 >>> solution(1000) 112 >>> solution(50000) 5502 """ frequencies: DefaultDict = defaultdict(int) euclid_m = 2 while 2 * euclid_m * (euclid_m + 1) <= limit: for euclid_n in range((euclid_m % 2) + 1, euclid_m, 2): if gcd(euclid_m, euclid_n) > 1: continue primitive_perimeter = 2 * euclid_m * (euclid_m + euclid_n) for perimeter in range(primitive_perimeter, limit + 1, primitive_perimeter): frequencies[perimeter] += 1 euclid_m += 1 return sum(1 for frequency in frequencies.values() if frequency == 1) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Source: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort This is a non-parallelized implementation of odd-even transposition sort. Normally the swaps in each set happen simultaneously, without that the algorithm is no better than bubble sort. """ def odd_even_transposition(arr: list) -> list: """ >>> odd_even_transposition([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> odd_even_transposition([13, 11, 18, 0, -1]) [-1, 0, 11, 13, 18] >>> odd_even_transposition([-.1, 1.1, .1, -2.9]) [-2.9, -0.1, 0.1, 1.1] """ arr_size = len(arr) for _ in range(arr_size): for i in range(_ % 2, arr_size - 1, 2): if arr[i + 1] < arr[i]: arr[i], arr[i + 1] = arr[i + 1], arr[i] return arr if __name__ == "__main__": arr = list(range(10, 0, -1)) print(f"Original: {arr}. Sorted: {odd_even_transposition(arr)}")
""" Source: https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort This is a non-parallelized implementation of odd-even transposition sort. Normally the swaps in each set happen simultaneously, without that the algorithm is no better than bubble sort. """ def odd_even_transposition(arr: list) -> list: """ >>> odd_even_transposition([5, 4, 3, 2, 1]) [1, 2, 3, 4, 5] >>> odd_even_transposition([13, 11, 18, 0, -1]) [-1, 0, 11, 13, 18] >>> odd_even_transposition([-.1, 1.1, .1, -2.9]) [-2.9, -0.1, 0.1, 1.1] """ arr_size = len(arr) for _ in range(arr_size): for i in range(_ % 2, arr_size - 1, 2): if arr[i + 1] < arr[i]: arr[i], arr[i + 1] = arr[i + 1], arr[i] return arr if __name__ == "__main__": arr = list(range(10, 0, -1)) print(f"Original: {arr}. Sorted: {odd_even_transposition(arr)}")
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Implementation of Bilateral filter Inputs: img: A 2d image with values in between 0 and 1 varS: variance in space dimension. varI: variance in Intensity. N: Kernel size(Must be an odd number) Output: img:A 2d zero padded image with values in between 0 and 1 """ import math import sys import cv2 import numpy as np def vec_gaussian(img: np.ndarray, variance: float) -> np.ndarray: # For applying gaussian function for each element in matrix. sigma = math.sqrt(variance) cons = 1 / (sigma * math.sqrt(2 * math.pi)) return cons * np.exp(-((img / sigma) ** 2) * 0.5) def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray: half = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray: # Creates a gaussian kernel of given dimension. arr = np.zeros((kernel_size, kernel_size)) for i in range(0, kernel_size): for j in range(0, kernel_size): arr[i, j] = math.sqrt( abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2 ) return vec_gaussian(arr, spatial_variance) def bilateral_filter( img: np.ndarray, spatial_variance: float, intensity_variance: float, kernel_size: int, ) -> np.ndarray: img2 = np.zeros(img.shape) gauss_ker = get_gauss_kernel(kernel_size, spatial_variance) size_x, size_y = img.shape for i in range(kernel_size // 2, size_x - kernel_size // 2): for j in range(kernel_size // 2, size_y - kernel_size // 2): img_s = get_slice(img, i, j, kernel_size) img_i = img_s - img_s[kernel_size // 2, kernel_size // 2] img_ig = vec_gaussian(img_i, intensity_variance) weights = np.multiply(gauss_ker, img_ig) vals = np.multiply(img_s, weights) val = np.sum(vals) / np.sum(weights) img2[i, j] = val return img2 def parse_args(args: list) -> tuple: filename = args[1] if args[1:] else "../image_data/lena.jpg" spatial_variance = float(args[2]) if args[2:] else 1.0 intensity_variance = float(args[3]) if args[3:] else 1.0 if args[4:]: kernel_size = int(args[4]) kernel_size = kernel_size + abs(kernel_size % 2 - 1) else: kernel_size = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": filename, spatial_variance, intensity_variance, kernel_size = parse_args(sys.argv) img = cv2.imread(filename, 0) cv2.imshow("input image", img) out = img / 255 out = out.astype("float32") out = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) out = out * 255 out = np.uint8(out) cv2.imshow("output image", out) cv2.waitKey(0) cv2.destroyAllWindows()
""" Implementation of Bilateral filter Inputs: img: A 2d image with values in between 0 and 1 varS: variance in space dimension. varI: variance in Intensity. N: Kernel size(Must be an odd number) Output: img:A 2d zero padded image with values in between 0 and 1 """ import math import sys import cv2 import numpy as np def vec_gaussian(img: np.ndarray, variance: float) -> np.ndarray: # For applying gaussian function for each element in matrix. sigma = math.sqrt(variance) cons = 1 / (sigma * math.sqrt(2 * math.pi)) return cons * np.exp(-((img / sigma) ** 2) * 0.5) def get_slice(img: np.ndarray, x: int, y: int, kernel_size: int) -> np.ndarray: half = kernel_size // 2 return img[x - half : x + half + 1, y - half : y + half + 1] def get_gauss_kernel(kernel_size: int, spatial_variance: float) -> np.ndarray: # Creates a gaussian kernel of given dimension. arr = np.zeros((kernel_size, kernel_size)) for i in range(0, kernel_size): for j in range(0, kernel_size): arr[i, j] = math.sqrt( abs(i - kernel_size // 2) ** 2 + abs(j - kernel_size // 2) ** 2 ) return vec_gaussian(arr, spatial_variance) def bilateral_filter( img: np.ndarray, spatial_variance: float, intensity_variance: float, kernel_size: int, ) -> np.ndarray: img2 = np.zeros(img.shape) gauss_ker = get_gauss_kernel(kernel_size, spatial_variance) size_x, size_y = img.shape for i in range(kernel_size // 2, size_x - kernel_size // 2): for j in range(kernel_size // 2, size_y - kernel_size // 2): img_s = get_slice(img, i, j, kernel_size) img_i = img_s - img_s[kernel_size // 2, kernel_size // 2] img_ig = vec_gaussian(img_i, intensity_variance) weights = np.multiply(gauss_ker, img_ig) vals = np.multiply(img_s, weights) val = np.sum(vals) / np.sum(weights) img2[i, j] = val return img2 def parse_args(args: list) -> tuple: filename = args[1] if args[1:] else "../image_data/lena.jpg" spatial_variance = float(args[2]) if args[2:] else 1.0 intensity_variance = float(args[3]) if args[3:] else 1.0 if args[4:]: kernel_size = int(args[4]) kernel_size = kernel_size + abs(kernel_size % 2 - 1) else: kernel_size = 5 return filename, spatial_variance, intensity_variance, kernel_size if __name__ == "__main__": filename, spatial_variance, intensity_variance, kernel_size = parse_args(sys.argv) img = cv2.imread(filename, 0) cv2.imshow("input image", img) out = img / 255 out = out.astype("float32") out = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size) out = out * 255 out = np.uint8(out) cv2.imshow("output image", out) cv2.waitKey(0) cv2.destroyAllWindows()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other 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 Python lists) class CircularQueue: """Circular FIFO queue with a fixed capacity""" def __init__(self, n: int): self.n = n self.array = [None] * self.n self.front = 0 # index of the first element self.rear = 0 self.size = 0 def __len__(self) -> int: """ >>> cq = CircularQueue(5) >>> len(cq) 0 >>> cq.enqueue("A") # doctest: +ELLIPSIS <data_structures.queue.circular_queue.CircularQueue object at ... >>> len(cq) 1 """ return self.size def is_empty(self) -> bool: """ >>> cq = CircularQueue(5) >>> cq.is_empty() True >>> cq.enqueue("A").is_empty() False """ return self.size == 0 def first(self): """ >>> cq = CircularQueue(5) >>> cq.first() False >>> cq.enqueue("A").first() 'A' """ return False if self.is_empty() else self.array[self.front] def enqueue(self, data): """ This function insert an element in the queue using self.rear value as an index >>> cq = CircularQueue(5) >>> cq.enqueue("A") # doctest: +ELLIPSIS <data_structures.queue.circular_queue.CircularQueue object at ... >>> (cq.size, cq.first()) (1, 'A') >>> cq.enqueue("B") # doctest: +ELLIPSIS <data_structures.queue.circular_queue.CircularQueue object at ... >>> (cq.size, cq.first()) (2, 'A') """ if self.size >= self.n: raise Exception("QUEUE IS FULL") self.array[self.rear] = data self.rear = (self.rear + 1) % self.n self.size += 1 return self def dequeue(self): """ This function removes an element from the queue using on self.front value as an index >>> cq = CircularQueue(5) >>> cq.dequeue() Traceback (most recent call last): ... Exception: UNDERFLOW >>> cq.enqueue("A").enqueue("B").dequeue() 'A' >>> (cq.size, cq.first()) (1, 'B') >>> cq.dequeue() 'B' >>> cq.dequeue() Traceback (most recent call last): ... Exception: UNDERFLOW """ if self.size == 0: raise Exception("UNDERFLOW") temp = self.array[self.front] self.array[self.front] = None self.front = (self.front + 1) % self.n self.size -= 1 return temp
# Implementation of Circular Queue (using Python lists) class CircularQueue: """Circular FIFO queue with a fixed capacity""" def __init__(self, n: int): self.n = n self.array = [None] * self.n self.front = 0 # index of the first element self.rear = 0 self.size = 0 def __len__(self) -> int: """ >>> cq = CircularQueue(5) >>> len(cq) 0 >>> cq.enqueue("A") # doctest: +ELLIPSIS <data_structures.queue.circular_queue.CircularQueue object at ... >>> len(cq) 1 """ return self.size def is_empty(self) -> bool: """ >>> cq = CircularQueue(5) >>> cq.is_empty() True >>> cq.enqueue("A").is_empty() False """ return self.size == 0 def first(self): """ >>> cq = CircularQueue(5) >>> cq.first() False >>> cq.enqueue("A").first() 'A' """ return False if self.is_empty() else self.array[self.front] def enqueue(self, data): """ This function insert an element in the queue using self.rear value as an index >>> cq = CircularQueue(5) >>> cq.enqueue("A") # doctest: +ELLIPSIS <data_structures.queue.circular_queue.CircularQueue object at ... >>> (cq.size, cq.first()) (1, 'A') >>> cq.enqueue("B") # doctest: +ELLIPSIS <data_structures.queue.circular_queue.CircularQueue object at ... >>> (cq.size, cq.first()) (2, 'A') """ if self.size >= self.n: raise Exception("QUEUE IS FULL") self.array[self.rear] = data self.rear = (self.rear + 1) % self.n self.size += 1 return self def dequeue(self): """ This function removes an element from the queue using on self.front value as an index >>> cq = CircularQueue(5) >>> cq.dequeue() Traceback (most recent call last): ... Exception: UNDERFLOW >>> cq.enqueue("A").enqueue("B").dequeue() 'A' >>> (cq.size, cq.first()) (1, 'B') >>> cq.dequeue() 'B' >>> cq.dequeue() Traceback (most recent call last): ... Exception: UNDERFLOW """ if self.size == 0: raise Exception("UNDERFLOW") temp = self.array[self.front] self.array[self.front] = None self.front = (self.front + 1) % self.n self.size -= 1 return temp
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" * Author: Manuel Di Lullo (https://github.com/manueldilullo) * Description: Random graphs generator. Uses graphs represented with an adjacency list. URL: https://en.wikipedia.org/wiki/Random_graph """ import random def random_graph( vertices_number: int, probability: float, directed: bool = False ) -> dict: """ Generate a random graph @input: vertices_number (number of vertices), probability (probability that a generic edge (u,v) exists), directed (if True: graph will be a directed graph, otherwise it will be an undirected graph) @examples: >>> random.seed(1) >>> random_graph(4, 0.5) {0: [1], 1: [0, 2, 3], 2: [1, 3], 3: [1, 2]} >>> random.seed(1) >>> random_graph(4, 0.5, True) {0: [1], 1: [2, 3], 2: [3], 3: []} """ graph: dict = {i: [] for i in range(vertices_number)} # if probability is greater or equal than 1, then generate a complete graph if probability >= 1: return complete_graph(vertices_number) # if probability is lower or equal than 0, then return a graph without edges if probability <= 0: return graph # for each couple of nodes, add an edge from u to v # if the number randomly generated is greater than probability probability for i in range(vertices_number): for j in range(i + 1, vertices_number): if random.random() < probability: graph[i].append(j) if not directed: # if the graph is undirected, add an edge in from j to i, either graph[j].append(i) return graph def complete_graph(vertices_number: int) -> dict: """ Generate a complete graph with vertices_number vertices. @input: vertices_number (number of vertices), directed (False if the graph is undirected, True otherwise) @example: >>> complete_graph(3) {0: [1, 2], 1: [0, 2], 2: [0, 1]} """ return { i: [j for j in range(vertices_number) if i != j] for i in range(vertices_number) } if __name__ == "__main__": import doctest doctest.testmod()
""" * Author: Manuel Di Lullo (https://github.com/manueldilullo) * Description: Random graphs generator. Uses graphs represented with an adjacency list. URL: https://en.wikipedia.org/wiki/Random_graph """ import random def random_graph( vertices_number: int, probability: float, directed: bool = False ) -> dict: """ Generate a random graph @input: vertices_number (number of vertices), probability (probability that a generic edge (u,v) exists), directed (if True: graph will be a directed graph, otherwise it will be an undirected graph) @examples: >>> random.seed(1) >>> random_graph(4, 0.5) {0: [1], 1: [0, 2, 3], 2: [1, 3], 3: [1, 2]} >>> random.seed(1) >>> random_graph(4, 0.5, True) {0: [1], 1: [2, 3], 2: [3], 3: []} """ graph: dict = {i: [] for i in range(vertices_number)} # if probability is greater or equal than 1, then generate a complete graph if probability >= 1: return complete_graph(vertices_number) # if probability is lower or equal than 0, then return a graph without edges if probability <= 0: return graph # for each couple of nodes, add an edge from u to v # if the number randomly generated is greater than probability probability for i in range(vertices_number): for j in range(i + 1, vertices_number): if random.random() < probability: graph[i].append(j) if not directed: # if the graph is undirected, add an edge in from j to i, either graph[j].append(i) return graph def complete_graph(vertices_number: int) -> dict: """ Generate a complete graph with vertices_number vertices. @input: vertices_number (number of vertices), directed (False if the graph is undirected, True otherwise) @example: >>> complete_graph(3) {0: [1, 2], 1: [0, 2], 2: [0, 1]} """ return { i: [j for j in range(vertices_number) if i != j] for i in range(vertices_number) } if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations arr = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] expect = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def next_greatest_element_slow(arr: list[float]) -> list[float]: """ Get the Next Greatest Element (NGE) for all elements in a list. Maximum element present after the current one which is also greater than the current one. >>> next_greatest_element_slow(arr) == expect True """ result = [] arr_size = len(arr) for i in range(arr_size): next_element: float = -1 for j in range(i + 1, arr_size): if arr[i] < arr[j]: next_element = arr[j] break result.append(next_element) return result def next_greatest_element_fast(arr: list[float]) -> list[float]: """ Like next_greatest_element_slow() but changes the loops to use enumerate() instead of range(len()) for the outer loop and for in a slice of arr for the inner loop. >>> next_greatest_element_fast(arr) == expect True """ result = [] for i, outer in enumerate(arr): next_item: float = -1 for inner in arr[i + 1 :]: if outer < inner: next_item = inner break result.append(next_item) return result def next_greatest_element(arr: list[float]) -> list[float]: """ Get the Next Greatest Element (NGE) for all elements in a list. Maximum element present after the current one which is also greater than the current one. A naive way to solve this is to take two loops and check for the next bigger number but that will make the time complexity as O(n^2). The better way to solve this would be to use a stack to keep track of maximum number giving a linear time solution. >>> next_greatest_element(arr) == expect True """ arr_size = len(arr) stack: list[float] = [] result: list[float] = [-1] * arr_size for index in reversed(range(arr_size)): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: result[index] = stack[-1] stack.append(arr[index]) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) setup = ( "from __main__ import arr, next_greatest_element_slow, " "next_greatest_element_fast, next_greatest_element" ) print( "next_greatest_element_slow():", timeit("next_greatest_element_slow(arr)", setup=setup), ) print( "next_greatest_element_fast():", timeit("next_greatest_element_fast(arr)", setup=setup), ) print( " next_greatest_element():", timeit("next_greatest_element(arr)", setup=setup), )
from __future__ import annotations arr = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] expect = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def next_greatest_element_slow(arr: list[float]) -> list[float]: """ Get the Next Greatest Element (NGE) for all elements in a list. Maximum element present after the current one which is also greater than the current one. >>> next_greatest_element_slow(arr) == expect True """ result = [] arr_size = len(arr) for i in range(arr_size): next_element: float = -1 for j in range(i + 1, arr_size): if arr[i] < arr[j]: next_element = arr[j] break result.append(next_element) return result def next_greatest_element_fast(arr: list[float]) -> list[float]: """ Like next_greatest_element_slow() but changes the loops to use enumerate() instead of range(len()) for the outer loop and for in a slice of arr for the inner loop. >>> next_greatest_element_fast(arr) == expect True """ result = [] for i, outer in enumerate(arr): next_item: float = -1 for inner in arr[i + 1 :]: if outer < inner: next_item = inner break result.append(next_item) return result def next_greatest_element(arr: list[float]) -> list[float]: """ Get the Next Greatest Element (NGE) for all elements in a list. Maximum element present after the current one which is also greater than the current one. A naive way to solve this is to take two loops and check for the next bigger number but that will make the time complexity as O(n^2). The better way to solve this would be to use a stack to keep track of maximum number giving a linear time solution. >>> next_greatest_element(arr) == expect True """ arr_size = len(arr) stack: list[float] = [] result: list[float] = [-1] * arr_size for index in reversed(range(arr_size)): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: result[index] = stack[-1] stack.append(arr[index]) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) setup = ( "from __main__ import arr, next_greatest_element_slow, " "next_greatest_element_fast, next_greatest_element" ) print( "next_greatest_element_slow():", timeit("next_greatest_element_slow(arr)", setup=setup), ) print( "next_greatest_element_fast():", timeit("next_greatest_element_fast(arr)", setup=setup), ) print( " next_greatest_element():", timeit("next_greatest_element(arr)", setup=setup), )
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 def climb_stairs(n: int) -> int: """ LeetCdoe No.70: Climbing Stairs Distinct ways to climb a n step staircase where each time you can either climb 1 or 2 steps. Args: n: number of steps of staircase Returns: Distinct ways to climb a n step staircase Raises: AssertionError: n not positive integer >>> climb_stairs(3) 3 >>> climb_stairs(1) 1 >>> climb_stairs(-7) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: n needs to be positive integer, your input -7 """ assert ( isinstance(n, int) and n > 0 ), f"n needs to be positive integer, your input {n}" if n == 1: return 1 dp = [0] * (n + 1) dp[0], dp[1] = (1, 1) for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n] if __name__ == "__main__": import doctest doctest.testmod()
#!/usr/bin/env python3 def climb_stairs(n: int) -> int: """ LeetCdoe No.70: Climbing Stairs Distinct ways to climb a n step staircase where each time you can either climb 1 or 2 steps. Args: n: number of steps of staircase Returns: Distinct ways to climb a n step staircase Raises: AssertionError: n not positive integer >>> climb_stairs(3) 3 >>> climb_stairs(1) 1 >>> climb_stairs(-7) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: n needs to be positive integer, your input -7 """ assert ( isinstance(n, int) and n > 0 ), f"n needs to be positive integer, your input {n}" if n == 1: return 1 dp = [0] * (n + 1) dp[0], dp[1] = (1, 1) for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import sys from collections import defaultdict def prisms_algorithm(l): # noqa: E741 node_position = [] def get_position(vertex): return node_position[vertex] def set_position(vertex, pos): node_position[vertex] = pos def top_to_bottom(heap, start, size, positions): if start > size // 2 - 1: return else: if 2 * start + 2 >= size: m = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: m = 2 * start + 1 else: m = 2 * start + 2 if heap[m] < heap[start]: temp, temp1 = heap[m], positions[m] heap[m], positions[m] = heap[start], positions[start] heap[start], positions[start] = temp, temp1 temp = get_position(positions[m]) set_position(positions[m], get_position(positions[start])) set_position(positions[start], temp) top_to_bottom(heap, m, size, positions) # Update function if value of any node in min-heap decreases def bottom_to_top(val, index, heap, position): temp = position[index] while index != 0: if index % 2 == 0: parent = int((index - 2) / 2) else: parent = int((index - 1) / 2) if val < heap[parent]: heap[index] = heap[parent] position[index] = position[parent] set_position(position[parent], index) else: heap[index] = val position[index] = temp set_position(temp, index) break index = parent else: heap[0] = val position[0] = temp set_position(temp, 0) def heapify(heap, positions): start = len(heap) // 2 - 1 for i in range(start, -1, -1): top_to_bottom(heap, i, len(heap), positions) def delete_minimum(heap, positions): temp = positions[0] heap[0] = sys.maxsize top_to_bottom(heap, 0, len(heap), positions) return temp visited = [0 for i in range(len(l))] nbr_tv = [-1 for i in range(len(l))] # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph distance_tv = [] # Heap of Distance of vertices from their neighboring vertex positions = [] for x in range(len(l)): p = sys.maxsize distance_tv.append(p) positions.append(x) node_position.append(x) tree_edges = [] visited[0] = 1 distance_tv[0] = sys.maxsize for x in l[0]: nbr_tv[x[0]] = 0 distance_tv[x[0]] = x[1] heapify(distance_tv, positions) for _ in range(1, len(l)): vertex = delete_minimum(distance_tv, positions) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex)) visited[vertex] = 1 for v in l[vertex]: if visited[v[0]] == 0 and v[1] < distance_tv[get_position(v[0])]: distance_tv[get_position(v[0])] = v[1] bottom_to_top(v[1], get_position(v[0]), distance_tv, positions) nbr_tv[v[0]] = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > n = int(input("Enter number of vertices: ").strip()) e = int(input("Enter number of edges: ").strip()) adjlist = defaultdict(list) for x in range(e): l = [int(x) for x in input().strip().split()] # noqa: E741 adjlist[l[0]].append([l[1], l[2]]) adjlist[l[1]].append([l[0], l[2]]) print(prisms_algorithm(adjlist))
import sys from collections import defaultdict def prisms_algorithm(l): # noqa: E741 node_position = [] def get_position(vertex): return node_position[vertex] def set_position(vertex, pos): node_position[vertex] = pos def top_to_bottom(heap, start, size, positions): if start > size // 2 - 1: return else: if 2 * start + 2 >= size: m = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: m = 2 * start + 1 else: m = 2 * start + 2 if heap[m] < heap[start]: temp, temp1 = heap[m], positions[m] heap[m], positions[m] = heap[start], positions[start] heap[start], positions[start] = temp, temp1 temp = get_position(positions[m]) set_position(positions[m], get_position(positions[start])) set_position(positions[start], temp) top_to_bottom(heap, m, size, positions) # Update function if value of any node in min-heap decreases def bottom_to_top(val, index, heap, position): temp = position[index] while index != 0: if index % 2 == 0: parent = int((index - 2) / 2) else: parent = int((index - 1) / 2) if val < heap[parent]: heap[index] = heap[parent] position[index] = position[parent] set_position(position[parent], index) else: heap[index] = val position[index] = temp set_position(temp, index) break index = parent else: heap[0] = val position[0] = temp set_position(temp, 0) def heapify(heap, positions): start = len(heap) // 2 - 1 for i in range(start, -1, -1): top_to_bottom(heap, i, len(heap), positions) def delete_minimum(heap, positions): temp = positions[0] heap[0] = sys.maxsize top_to_bottom(heap, 0, len(heap), positions) return temp visited = [0 for i in range(len(l))] nbr_tv = [-1 for i in range(len(l))] # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph distance_tv = [] # Heap of Distance of vertices from their neighboring vertex positions = [] for x in range(len(l)): p = sys.maxsize distance_tv.append(p) positions.append(x) node_position.append(x) tree_edges = [] visited[0] = 1 distance_tv[0] = sys.maxsize for x in l[0]: nbr_tv[x[0]] = 0 distance_tv[x[0]] = x[1] heapify(distance_tv, positions) for _ in range(1, len(l)): vertex = delete_minimum(distance_tv, positions) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex)) visited[vertex] = 1 for v in l[vertex]: if visited[v[0]] == 0 and v[1] < distance_tv[get_position(v[0])]: distance_tv[get_position(v[0])] = v[1] bottom_to_top(v[1], get_position(v[0]), distance_tv, positions) nbr_tv[v[0]] = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > n = int(input("Enter number of vertices: ").strip()) e = int(input("Enter number of edges: ").strip()) adjlist = defaultdict(list) for x in range(e): l = [int(x) for x in input().strip().split()] # noqa: E741 adjlist[l[0]].append([l[1], l[2]]) adjlist[l[1]].append([l[0], l[2]]) print(prisms_algorithm(adjlist))
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" == Perfect Number == In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For example: 6 ==> divisors[1, 2, 3, 6] Excluding 6, the sum(divisors) is 1 + 2 + 3 = 6 So, 6 is a Perfect Number Other examples of Perfect Numbers: 28, 486, ... https://en.wikipedia.org/wiki/Perfect_number """ def perfect(number: int) -> bool: """ >>> perfect(27) False >>> perfect(28) True >>> perfect(29) False Start from 1 because dividing by 0 will raise ZeroDivisionError. A number at most can be divisible by the half of the number except the number itself. For example, 6 is at most can be divisible by 3 except by 6 itself. """ return sum(i for i in range(1, number // 2 + 1) if number % i == 0) == number if __name__ == "__main__": print("Program to check whether a number is a Perfect number or not...") number = int(input("Enter number: ").strip()) print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
""" == Perfect Number == In number theory, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For example: 6 ==> divisors[1, 2, 3, 6] Excluding 6, the sum(divisors) is 1 + 2 + 3 = 6 So, 6 is a Perfect Number Other examples of Perfect Numbers: 28, 486, ... https://en.wikipedia.org/wiki/Perfect_number """ def perfect(number: int) -> bool: """ >>> perfect(27) False >>> perfect(28) True >>> perfect(29) False Start from 1 because dividing by 0 will raise ZeroDivisionError. A number at most can be divisible by the half of the number except the number itself. For example, 6 is at most can be divisible by 3 except by 6 itself. """ return sum(i for i in range(1, number // 2 + 1) if number % i == 0) == number if __name__ == "__main__": print("Program to check whether a number is a Perfect number or not...") number = int(input("Enter number: ").strip()) print(f"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Created on Thu Oct 5 16:44:23 2017 @author: Christian Bender This Python library contains some useful functions to deal with prime numbers and whole numbers. Overview: is_prime(number) sieve_er(N) get_prime_numbers(N) prime_factorization(number) greatest_prime_factor(number) smallest_prime_factor(number) get_prime(n) get_primes_between(pNumber1, pNumber2) ---- is_even(number) is_odd(number) gcd(number1, number2) // greatest common divisor kg_v(number1, number2) // least common multiple get_divisors(number) // all divisors of 'number' inclusive 1, number is_perfect_number(number) NEW-FUNCTIONS simplify_fraction(numerator, denominator) factorial (n) // n! fib (n) // calculate the n-th fibonacci term. ----- goldbach(number) // Goldbach's assumption """ from math import sqrt def is_prime(number: int) -> bool: """ input: positive integer 'number' returns true if 'number' is prime otherwise false. """ # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' must been an int and positive" status = True # 0 and 1 are none primes. if number <= 1: status = False for divisor in range(2, int(round(sqrt(number))) + 1): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: status = False break # precondition assert isinstance(status, bool), "'status' must been from type bool" return status # ------------------------------------------ def sieve_er(n): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N. This function implements the algorithm called sieve of erathostenes. """ # precondition assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N begin_list = list(range(2, n + 1)) ans = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(begin_list)): for j in range(i + 1, len(begin_list)): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): begin_list[j] = 0 # filters actual prime numbers. ans = [x for x in begin_list if x != 0] # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # -------------------------------- def get_prime_numbers(n): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N (inclusive) This function is more efficient as function 'sieveEr(...)' """ # precondition assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2" ans = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2, n + 1): if is_prime(number): ans.append(number) # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # ----------------------------------------- def prime_factorization(number): """ input: positive integer 'number' returns a list of the prime number factors of 'number' """ # precondition assert isinstance(number, int) and number >= 0, "'number' must been an int and >= 0" ans = [] # this list will be returns of the function. # potential prime number factors. factor = 2 quotient = number if number == 0 or number == 1: ans.append(number) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(number): while quotient != 1: if is_prime(factor) and (quotient % factor == 0): ans.append(factor) quotient /= factor else: factor += 1 else: ans.append(number) # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # ----------------------------------------- def greatest_prime_factor(number): """ input: positive integer 'number' >= 0 returns the greatest prime number factor of 'number' """ # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' bust been an int and >= 0" ans = 0 # prime factorization of 'number' prime_factors = prime_factorization(number) ans = max(prime_factors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans # ---------------------------------------------- def smallest_prime_factor(number): """ input: integer 'number' >= 0 returns the smallest prime number factor of 'number' """ # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' bust been an int and >= 0" ans = 0 # prime factorization of 'number' prime_factors = prime_factorization(number) ans = min(prime_factors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans # ---------------------- def is_even(number): """ input: integer 'number' returns true if 'number' is even, otherwise false. """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 == 0, bool), "compare bust been from type bool" return number % 2 == 0 # ------------------------ def is_odd(number): """ input: integer 'number' returns true if 'number' is odd, otherwise false. """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 != 0, bool), "compare bust been from type bool" return number % 2 != 0 # ------------------------ def goldbach(number): """ Goldbach's assumption input: a even positive integer 'number' > 2 returns a list of two prime numbers whose sum is equal to 'number' """ # precondition assert ( isinstance(number, int) and (number > 2) and is_even(number) ), "'number' must been an int, even and > 2" ans = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' prime_numbers = get_prime_numbers(number) len_pn = len(prime_numbers) # run variable for while-loops. i = 0 j = None # exit variable. for break up the loops loop = True while i < len_pn and loop: j = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: loop = False ans.append(prime_numbers[i]) ans.append(prime_numbers[j]) j += 1 i += 1 # precondition assert ( isinstance(ans, list) and (len(ans) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0]) and is_prime(ans[1]) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans # ---------------------------------------------- def gcd(number1, number2): """ Greatest common divisor input: two positive integer 'number1' and 'number2' returns the greatest common divisor of 'number1' and 'number2' """ # precondition assert ( isinstance(number1, int) and isinstance(number2, int) and (number1 >= 0) and (number2 >= 0) ), "'number1' and 'number2' must been positive integer." rest = 0 while number2 != 0: rest = number1 % number2 number1 = number2 number2 = rest # precondition assert isinstance(number1, int) and ( number1 >= 0 ), "'number' must been from type int and positive" return number1 # ---------------------------------------------------- def kg_v(number1, number2): """ Least common multiple input: two positive integer 'number1' and 'number2' returns the least common multiple of 'number1' and 'number2' """ # precondition assert ( isinstance(number1, int) and isinstance(number2, int) and (number1 >= 1) and (number2 >= 1) ), "'number1' and 'number2' must been positive integer." ans = 1 # actual answer that will be return. # for kgV (x,1) if number1 > 1 and number2 > 1: # builds the prime factorization of 'number1' and 'number2' prime_fac_1 = prime_factorization(number1) prime_fac_2 = prime_factorization(number2) elif number1 == 1 or number2 == 1: prime_fac_1 = [] prime_fac_2 = [] ans = max(number1, number2) count1 = 0 count2 = 0 done = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_1: if n not in done: if n in prime_fac_2: count1 = prime_fac_1.count(n) count2 = prime_fac_2.count(n) for _ in range(max(count1, count2)): ans *= n else: count1 = prime_fac_1.count(n) for _ in range(count1): ans *= n done.append(n) # iterates through primeFac2 for n in prime_fac_2: if n not in done: count2 = prime_fac_2.count(n) for _ in range(count2): ans *= n done.append(n) # precondition assert isinstance(ans, int) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans # ---------------------------------- def get_prime(n): """ Gets the n-th prime number. input: positive integer 'n' >= 0 returns the n-th prime number, beginning at index 0 """ # precondition assert isinstance(n, int) and (n >= 0), "'number' must been a positive int" index = 0 ans = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(ans): ans += 1 # precondition assert isinstance(ans, int) and is_prime( ans ), "'ans' must been a prime number and from type int" return ans # --------------------------------------------------- def get_primes_between(p_number_1, p_number_2): """ input: prime numbers 'pNumber1' and 'pNumber2' pNumber1 < pNumber2 returns a list of all prime numbers between 'pNumber1' (exclusive) and 'pNumber2' (exclusive) """ # precondition assert ( is_prime(p_number_1) and is_prime(p_number_2) and (p_number_1 < p_number_2) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" number = p_number_1 + 1 # jump to the next number ans = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(number): number += 1 while number < p_number_2: ans.append(number) number += 1 # fetch the next prime number. while not is_prime(number): number += 1 # precondition assert ( isinstance(ans, list) and ans[0] != p_number_1 and ans[len(ans) - 1] != p_number_2 ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans # ---------------------------------------------------- def get_divisors(n): """ input: positive integer 'n' >= 1 returns all divisors of n (inclusive 1 and 'n') """ # precondition assert isinstance(n, int) and (n >= 1), "'n' must been int and >= 1" ans = [] # will be returned. for divisor in range(1, n + 1): if n % divisor == 0: ans.append(divisor) # precondition assert ans[0] == 1 and ans[len(ans) - 1] == n, "Error in function getDivisiors(...)" return ans # ---------------------------------------------------- def is_perfect_number(number): """ input: positive integer 'number' > 1 returns true if 'number' is a perfect number otherwise false. """ # precondition assert isinstance(number, int) and ( number > 1 ), "'number' must been an int and >= 1" divisors = get_divisors(number) # precondition assert ( isinstance(divisors, list) and (divisors[0] == 1) and (divisors[len(divisors) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1]) == number # ------------------------------------------------------------ def simplify_fraction(numerator, denominator): """ input: two integer 'numerator' and 'denominator' assumes: 'denominator' != 0 returns: a tuple with simplify numerator and denominator. """ # precondition assert ( isinstance(numerator, int) and isinstance(denominator, int) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. gcd_of_fraction = gcd(abs(numerator), abs(denominator)) # precondition assert ( isinstance(gcd_of_fraction, int) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) # ----------------------------------------------------------------- def factorial(n): """ input: positive integer 'n' returns the factorial of 'n' (n!) """ # precondition assert isinstance(n, int) and (n >= 0), "'n' must been a int and >= 0" ans = 1 # this will be return. for factor in range(1, n + 1): ans *= factor return ans # ------------------------------------------------------------------- def fib(n): """ input: positive integer 'n' returns the n-th fibonacci term , indexing by 0 """ # precondition assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0" tmp = 0 fib1 = 1 ans = 1 # this will be return for _ in range(n - 1): tmp = ans ans += fib1 fib1 = tmp return ans
""" Created on Thu Oct 5 16:44:23 2017 @author: Christian Bender This Python library contains some useful functions to deal with prime numbers and whole numbers. Overview: is_prime(number) sieve_er(N) get_prime_numbers(N) prime_factorization(number) greatest_prime_factor(number) smallest_prime_factor(number) get_prime(n) get_primes_between(pNumber1, pNumber2) ---- is_even(number) is_odd(number) gcd(number1, number2) // greatest common divisor kg_v(number1, number2) // least common multiple get_divisors(number) // all divisors of 'number' inclusive 1, number is_perfect_number(number) NEW-FUNCTIONS simplify_fraction(numerator, denominator) factorial (n) // n! fib (n) // calculate the n-th fibonacci term. ----- goldbach(number) // Goldbach's assumption """ from math import sqrt def is_prime(number: int) -> bool: """ input: positive integer 'number' returns true if 'number' is prime otherwise false. """ # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' must been an int and positive" status = True # 0 and 1 are none primes. if number <= 1: status = False for divisor in range(2, int(round(sqrt(number))) + 1): # if 'number' divisible by 'divisor' then sets 'status' # of false and break up the loop. if number % divisor == 0: status = False break # precondition assert isinstance(status, bool), "'status' must been from type bool" return status # ------------------------------------------ def sieve_er(n): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N. This function implements the algorithm called sieve of erathostenes. """ # precondition assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2" # beginList: contains all natural numbers from 2 up to N begin_list = list(range(2, n + 1)) ans = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(begin_list)): for j in range(i + 1, len(begin_list)): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): begin_list[j] = 0 # filters actual prime numbers. ans = [x for x in begin_list if x != 0] # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # -------------------------------- def get_prime_numbers(n): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N (inclusive) This function is more efficient as function 'sieveEr(...)' """ # precondition assert isinstance(n, int) and (n > 2), "'N' must been an int and > 2" ans = [] # iterates over all numbers between 2 up to N+1 # if a number is prime then appends to list 'ans' for number in range(2, n + 1): if is_prime(number): ans.append(number) # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # ----------------------------------------- def prime_factorization(number): """ input: positive integer 'number' returns a list of the prime number factors of 'number' """ # precondition assert isinstance(number, int) and number >= 0, "'number' must been an int and >= 0" ans = [] # this list will be returns of the function. # potential prime number factors. factor = 2 quotient = number if number == 0 or number == 1: ans.append(number) # if 'number' not prime then builds the prime factorization of 'number' elif not is_prime(number): while quotient != 1: if is_prime(factor) and (quotient % factor == 0): ans.append(factor) quotient /= factor else: factor += 1 else: ans.append(number) # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # ----------------------------------------- def greatest_prime_factor(number): """ input: positive integer 'number' >= 0 returns the greatest prime number factor of 'number' """ # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' bust been an int and >= 0" ans = 0 # prime factorization of 'number' prime_factors = prime_factorization(number) ans = max(prime_factors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans # ---------------------------------------------- def smallest_prime_factor(number): """ input: integer 'number' >= 0 returns the smallest prime number factor of 'number' """ # precondition assert isinstance(number, int) and ( number >= 0 ), "'number' bust been an int and >= 0" ans = 0 # prime factorization of 'number' prime_factors = prime_factorization(number) ans = min(prime_factors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans # ---------------------- def is_even(number): """ input: integer 'number' returns true if 'number' is even, otherwise false. """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 == 0, bool), "compare bust been from type bool" return number % 2 == 0 # ------------------------ def is_odd(number): """ input: integer 'number' returns true if 'number' is odd, otherwise false. """ # precondition assert isinstance(number, int), "'number' must been an int" assert isinstance(number % 2 != 0, bool), "compare bust been from type bool" return number % 2 != 0 # ------------------------ def goldbach(number): """ Goldbach's assumption input: a even positive integer 'number' > 2 returns a list of two prime numbers whose sum is equal to 'number' """ # precondition assert ( isinstance(number, int) and (number > 2) and is_even(number) ), "'number' must been an int, even and > 2" ans = [] # this list will returned # creates a list of prime numbers between 2 up to 'number' prime_numbers = get_prime_numbers(number) len_pn = len(prime_numbers) # run variable for while-loops. i = 0 j = None # exit variable. for break up the loops loop = True while i < len_pn and loop: j = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: loop = False ans.append(prime_numbers[i]) ans.append(prime_numbers[j]) j += 1 i += 1 # precondition assert ( isinstance(ans, list) and (len(ans) == 2) and (ans[0] + ans[1] == number) and is_prime(ans[0]) and is_prime(ans[1]) ), "'ans' must contains two primes. And sum of elements must been eq 'number'" return ans # ---------------------------------------------- def gcd(number1, number2): """ Greatest common divisor input: two positive integer 'number1' and 'number2' returns the greatest common divisor of 'number1' and 'number2' """ # precondition assert ( isinstance(number1, int) and isinstance(number2, int) and (number1 >= 0) and (number2 >= 0) ), "'number1' and 'number2' must been positive integer." rest = 0 while number2 != 0: rest = number1 % number2 number1 = number2 number2 = rest # precondition assert isinstance(number1, int) and ( number1 >= 0 ), "'number' must been from type int and positive" return number1 # ---------------------------------------------------- def kg_v(number1, number2): """ Least common multiple input: two positive integer 'number1' and 'number2' returns the least common multiple of 'number1' and 'number2' """ # precondition assert ( isinstance(number1, int) and isinstance(number2, int) and (number1 >= 1) and (number2 >= 1) ), "'number1' and 'number2' must been positive integer." ans = 1 # actual answer that will be return. # for kgV (x,1) if number1 > 1 and number2 > 1: # builds the prime factorization of 'number1' and 'number2' prime_fac_1 = prime_factorization(number1) prime_fac_2 = prime_factorization(number2) elif number1 == 1 or number2 == 1: prime_fac_1 = [] prime_fac_2 = [] ans = max(number1, number2) count1 = 0 count2 = 0 done = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_1: if n not in done: if n in prime_fac_2: count1 = prime_fac_1.count(n) count2 = prime_fac_2.count(n) for _ in range(max(count1, count2)): ans *= n else: count1 = prime_fac_1.count(n) for _ in range(count1): ans *= n done.append(n) # iterates through primeFac2 for n in prime_fac_2: if n not in done: count2 = prime_fac_2.count(n) for _ in range(count2): ans *= n done.append(n) # precondition assert isinstance(ans, int) and ( ans >= 0 ), "'ans' must been from type int and positive" return ans # ---------------------------------- def get_prime(n): """ Gets the n-th prime number. input: positive integer 'n' >= 0 returns the n-th prime number, beginning at index 0 """ # precondition assert isinstance(n, int) and (n >= 0), "'number' must been a positive int" index = 0 ans = 2 # this variable holds the answer while index < n: index += 1 ans += 1 # counts to the next number # if ans not prime then # runs to the next prime number. while not is_prime(ans): ans += 1 # precondition assert isinstance(ans, int) and is_prime( ans ), "'ans' must been a prime number and from type int" return ans # --------------------------------------------------- def get_primes_between(p_number_1, p_number_2): """ input: prime numbers 'pNumber1' and 'pNumber2' pNumber1 < pNumber2 returns a list of all prime numbers between 'pNumber1' (exclusive) and 'pNumber2' (exclusive) """ # precondition assert ( is_prime(p_number_1) and is_prime(p_number_2) and (p_number_1 < p_number_2) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" number = p_number_1 + 1 # jump to the next number ans = [] # this list will be returns. # if number is not prime then # fetch the next prime number. while not is_prime(number): number += 1 while number < p_number_2: ans.append(number) number += 1 # fetch the next prime number. while not is_prime(number): number += 1 # precondition assert ( isinstance(ans, list) and ans[0] != p_number_1 and ans[len(ans) - 1] != p_number_2 ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans # ---------------------------------------------------- def get_divisors(n): """ input: positive integer 'n' >= 1 returns all divisors of n (inclusive 1 and 'n') """ # precondition assert isinstance(n, int) and (n >= 1), "'n' must been int and >= 1" ans = [] # will be returned. for divisor in range(1, n + 1): if n % divisor == 0: ans.append(divisor) # precondition assert ans[0] == 1 and ans[len(ans) - 1] == n, "Error in function getDivisiors(...)" return ans # ---------------------------------------------------- def is_perfect_number(number): """ input: positive integer 'number' > 1 returns true if 'number' is a perfect number otherwise false. """ # precondition assert isinstance(number, int) and ( number > 1 ), "'number' must been an int and >= 1" divisors = get_divisors(number) # precondition assert ( isinstance(divisors, list) and (divisors[0] == 1) and (divisors[len(divisors) - 1] == number) ), "Error in help-function getDivisiors(...)" # summed all divisors up to 'number' (exclusive), hence [:-1] return sum(divisors[:-1]) == number # ------------------------------------------------------------ def simplify_fraction(numerator, denominator): """ input: two integer 'numerator' and 'denominator' assumes: 'denominator' != 0 returns: a tuple with simplify numerator and denominator. """ # precondition assert ( isinstance(numerator, int) and isinstance(denominator, int) and (denominator != 0) ), "The arguments must been from type int and 'denominator' != 0" # build the greatest common divisor of numerator and denominator. gcd_of_fraction = gcd(abs(numerator), abs(denominator)) # precondition assert ( isinstance(gcd_of_fraction, int) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) # ----------------------------------------------------------------- def factorial(n): """ input: positive integer 'n' returns the factorial of 'n' (n!) """ # precondition assert isinstance(n, int) and (n >= 0), "'n' must been a int and >= 0" ans = 1 # this will be return. for factor in range(1, n + 1): ans *= factor return ans # ------------------------------------------------------------------- def fib(n): """ input: positive integer 'n' returns the n-th fibonacci term , indexing by 0 """ # precondition assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0" tmp = 0 fib1 = 1 ans = 1 # this will be return for _ in range(n - 1): tmp = ans ans += fib1 fib1 = tmp return ans
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#
#
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The convex hull problem is problem of finding all the vertices of convex polygon, P of a set of points in a plane such that all the points are either on the vertices of P or inside P. TH convex hull problem has several applications in geometrical problems, computer graphics and game development. Two algorithms have been implemented for the convex hull problem here. 1. A brute-force algorithm which runs in O(n^3) 2. A divide-and-conquer algorithm which runs in O(n log(n)) There are other several other algorithms for the convex hull problem which have not been implemented here, yet. """ from __future__ import annotations from collections.abc import Iterable class Point: """ Defines a 2-d point for use by all convex-hull algorithms. Parameters ---------- x: an int or a float, the x-coordinate of the 2-d point y: an int or a float, the y-coordinate of the 2-d point Examples -------- >>> Point(1, 2) (1.0, 2.0) >>> Point("1", "2") (1.0, 2.0) >>> Point(1, 2) > Point(0, 1) True >>> Point(1, 1) == Point(1, 1) True >>> Point(-0.5, 1) == Point(0.5, 1) False >>> Point("pi", "e") Traceback (most recent call last): ... ValueError: could not convert string to float: 'pi' """ def __init__(self, x, y): self.x, self.y = float(x), float(y) def __eq__(self, other): return self.x == other.x and self.y == other.y def __ne__(self, other): return not self == other def __gt__(self, other): if self.x > other.x: return True elif self.x == other.x: return self.y > other.y return False def __lt__(self, other): return not self > other def __ge__(self, other): if self.x > other.x: return True elif self.x == other.x: return self.y >= other.y return False def __le__(self, other): if self.x < other.x: return True elif self.x == other.x: return self.y <= other.y return False def __repr__(self): return f"({self.x}, {self.y})" def __hash__(self): return hash(self.x) def _construct_points( list_of_tuples: list[Point] | list[list[float]] | Iterable[list[float]], ) -> list[Point]: """ constructs a list of points from an array-like object of numbers Arguments --------- list_of_tuples: array-like object of type numbers. Acceptable types so far are lists, tuples and sets. Returns -------- points: a list where each item is of type Point. This contains only objects which can be converted into a Point. Examples ------- >>> _construct_points([[1, 1], [2, -1], [0.3, 4]]) [(1.0, 1.0), (2.0, -1.0), (0.3, 4.0)] >>> _construct_points([1, 2]) Ignoring deformed point 1. All points must have at least 2 coordinates. Ignoring deformed point 2. All points must have at least 2 coordinates. [] >>> _construct_points([]) [] >>> _construct_points(None) [] """ points: list[Point] = [] if list_of_tuples: for p in list_of_tuples: if isinstance(p, Point): points.append(p) else: try: points.append(Point(p[0], p[1])) except (IndexError, TypeError): print( f"Ignoring deformed point {p}. All points" " must have at least 2 coordinates." ) return points def _validate_input(points: list[Point] | list[list[float]]) -> list[Point]: """ validates an input instance before a convex-hull algorithms uses it Parameters --------- points: array-like, the 2d points to validate before using with a convex-hull algorithm. The elements of points must be either lists, tuples or Points. Returns ------- points: array_like, an iterable of all well-defined Points constructed passed in. Exception --------- ValueError: if points is empty or None, or if a wrong data structure like a scalar is passed TypeError: if an iterable but non-indexable object (eg. dictionary) is passed. The exception to this a set which we'll convert to a list before using Examples ------- >>> _validate_input([[1, 2]]) [(1.0, 2.0)] >>> _validate_input([(1, 2)]) [(1.0, 2.0)] >>> _validate_input([Point(2, 1), Point(-1, 2)]) [(2.0, 1.0), (-1.0, 2.0)] >>> _validate_input([]) Traceback (most recent call last): ... ValueError: Expecting a list of points but got [] >>> _validate_input(1) Traceback (most recent call last): ... ValueError: Expecting an iterable object but got an non-iterable type 1 """ if not hasattr(points, "__iter__"): raise ValueError( f"Expecting an iterable object but got an non-iterable type {points}" ) if not points: raise ValueError(f"Expecting a list of points but got {points}") return _construct_points(points) def _det(a: Point, b: Point, c: Point) -> float: """ Computes the sign perpendicular distance of a 2d point c from a line segment ab. The sign indicates the direction of c relative to ab. A Positive value means c is above ab (to the left), while a negative value means c is below ab (to the right). 0 means all three points are on a straight line. As a side note, 0.5 * abs|det| is the area of triangle abc Parameters ---------- a: point, the point on the left end of line segment ab b: point, the point on the right end of line segment ab c: point, the point for which the direction and location is desired. Returns -------- det: float, abs(det) is the distance of c from ab. The sign indicates which side of line segment ab c is. det is computed as (a_xb_y + c_xa_y + b_xc_y) - (a_yb_x + c_ya_x + b_yc_x) Examples ---------- >>> _det(Point(1, 1), Point(1, 2), Point(1, 5)) 0.0 >>> _det(Point(0, 0), Point(10, 0), Point(0, 10)) 100.0 >>> _det(Point(0, 0), Point(10, 0), Point(0, -10)) -100.0 """ det = (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x) return det def convex_hull_bf(points: list[Point]) -> list[Point]: """ Constructs the convex hull of a set of 2D points using a brute force algorithm. The algorithm basically considers all combinations of points (i, j) and uses the definition of convexity to determine whether (i, j) is part of the convex hull or not. (i, j) is part of the convex hull if and only iff there are no points on both sides of the line segment connecting the ij, and there is no point k such that k is on either end of the ij. Runtime: O(n^3) - definitely horrible Parameters --------- points: array-like of object of Points, lists or tuples. The set of 2d points for which the convex-hull is needed Returns ------ convex_set: list, the convex-hull of points sorted in non-decreasing order. See Also -------- convex_hull_recursive, Examples --------- >>> convex_hull_bf([[0, 0], [1, 0], [10, 1]]) [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] >>> convex_hull_bf([[0, 0], [1, 0], [10, 0]]) [(0.0, 0.0), (10.0, 0.0)] >>> convex_hull_bf([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], ... [-0.75, 1]]) [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] >>> convex_hull_bf([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), ... (2, -1), (2, -4), (1, -3)]) [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] """ points = sorted(_validate_input(points)) n = len(points) convex_set = set() for i in range(n - 1): for j in range(i + 1, n): points_left_of_ij = points_right_of_ij = False ij_part_of_convex_hull = True for k in range(n): if k != i and k != j: det_k = _det(points[i], points[j], points[k]) if det_k > 0: points_left_of_ij = True elif det_k < 0: points_right_of_ij = True else: # point[i], point[j], point[k] all lie on a straight line # if point[k] is to the left of point[i] or it's to the # right of point[j], then point[i], point[j] cannot be # part of the convex hull of A if points[k] < points[i] or points[k] > points[j]: ij_part_of_convex_hull = False break if points_left_of_ij and points_right_of_ij: ij_part_of_convex_hull = False break if ij_part_of_convex_hull: convex_set.update([points[i], points[j]]) return sorted(convex_set) def convex_hull_recursive(points: list[Point]) -> list[Point]: """ Constructs the convex hull of a set of 2D points using a divide-and-conquer strategy The algorithm exploits the geometric properties of the problem by repeatedly partitioning the set of points into smaller hulls, and finding the convex hull of these smaller hulls. The union of the convex hull from smaller hulls is the solution to the convex hull of the larger problem. Parameter --------- points: array-like of object of Points, lists or tuples. The set of 2d points for which the convex-hull is needed Runtime: O(n log n) Returns ------- convex_set: list, the convex-hull of points sorted in non-decreasing order. Examples --------- >>> convex_hull_recursive([[0, 0], [1, 0], [10, 1]]) [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] >>> convex_hull_recursive([[0, 0], [1, 0], [10, 0]]) [(0.0, 0.0), (10.0, 0.0)] >>> convex_hull_recursive([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], ... [-0.75, 1]]) [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] >>> convex_hull_recursive([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), ... (2, -1), (2, -4), (1, -3)]) [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] """ points = sorted(_validate_input(points)) n = len(points) # divide all the points into an upper hull and a lower hull # the left most point and the right most point are definitely # members of the convex hull by definition. # use these two anchors to divide all the points into two hulls, # an upper hull and a lower hull. # all points to the left (above) the line joining the extreme points belong to the # upper hull # all points to the right (below) the line joining the extreme points below to the # lower hull # ignore all points on the line joining the extreme points since they cannot be # part of the convex hull left_most_point = points[0] right_most_point = points[n - 1] convex_set = {left_most_point, right_most_point} upper_hull = [] lower_hull = [] for i in range(1, n - 1): det = _det(left_most_point, right_most_point, points[i]) if det > 0: upper_hull.append(points[i]) elif det < 0: lower_hull.append(points[i]) _construct_hull(upper_hull, left_most_point, right_most_point, convex_set) _construct_hull(lower_hull, right_most_point, left_most_point, convex_set) return sorted(convex_set) def _construct_hull( points: list[Point], left: Point, right: Point, convex_set: set[Point] ) -> None: """ Parameters --------- points: list or None, the hull of points from which to choose the next convex-hull point left: Point, the point to the left of line segment joining left and right right: The point to the right of the line segment joining left and right convex_set: set, the current convex-hull. The state of convex-set gets updated by this function Note ---- For the line segment 'ab', 'a' is on the left and 'b' on the right. but the reverse is true for the line segment 'ba'. Returns ------- Nothing, only updates the state of convex-set """ if points: extreme_point = None extreme_point_distance = float("-inf") candidate_points = [] for p in points: det = _det(left, right, p) if det > 0: candidate_points.append(p) if det > extreme_point_distance: extreme_point_distance = det extreme_point = p if extreme_point: _construct_hull(candidate_points, left, extreme_point, convex_set) convex_set.add(extreme_point) _construct_hull(candidate_points, extreme_point, right, convex_set) def convex_hull_melkman(points: list[Point]) -> list[Point]: """ Constructs the convex hull of a set of 2D points using the melkman algorithm. The algorithm works by iteratively inserting points of a simple polygonal chain (meaning that no line segments between two consecutive points cross each other). Sorting the points yields such a polygonal chain. For a detailed description, see http://cgm.cs.mcgill.ca/~athens/cs601/Melkman.html Runtime: O(n log n) - O(n) if points are already sorted in the input Parameters --------- points: array-like of object of Points, lists or tuples. The set of 2d points for which the convex-hull is needed Returns ------ convex_set: list, the convex-hull of points sorted in non-decreasing order. See Also -------- Examples --------- >>> convex_hull_melkman([[0, 0], [1, 0], [10, 1]]) [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] >>> convex_hull_melkman([[0, 0], [1, 0], [10, 0]]) [(0.0, 0.0), (10.0, 0.0)] >>> convex_hull_melkman([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], ... [-0.75, 1]]) [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] >>> convex_hull_melkman([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), ... (2, -1), (2, -4), (1, -3)]) [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] """ points = sorted(_validate_input(points)) n = len(points) convex_hull = points[:2] for i in range(2, n): det = _det(convex_hull[1], convex_hull[0], points[i]) if det > 0: convex_hull.insert(0, points[i]) break elif det < 0: convex_hull.append(points[i]) break else: convex_hull[1] = points[i] i += 1 for j in range(i, n): if ( _det(convex_hull[0], convex_hull[-1], points[j]) > 0 and _det(convex_hull[-1], convex_hull[0], points[1]) < 0 ): # The point lies within the convex hull continue convex_hull.insert(0, points[j]) convex_hull.append(points[j]) while _det(convex_hull[0], convex_hull[1], convex_hull[2]) >= 0: del convex_hull[1] while _det(convex_hull[-1], convex_hull[-2], convex_hull[-3]) <= 0: del convex_hull[-2] # `convex_hull` is contains the convex hull in circular order return sorted(convex_hull[1:] if len(convex_hull) > 3 else convex_hull) def main(): points = [ (0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), (2, -1), (2, -4), (1, -3), ] # the convex set of points is # [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)] results_bf = convex_hull_bf(points) results_recursive = convex_hull_recursive(points) assert results_bf == results_recursive results_melkman = convex_hull_melkman(points) assert results_bf == results_melkman print(results_bf) if __name__ == "__main__": main()
""" The convex hull problem is problem of finding all the vertices of convex polygon, P of a set of points in a plane such that all the points are either on the vertices of P or inside P. TH convex hull problem has several applications in geometrical problems, computer graphics and game development. Two algorithms have been implemented for the convex hull problem here. 1. A brute-force algorithm which runs in O(n^3) 2. A divide-and-conquer algorithm which runs in O(n log(n)) There are other several other algorithms for the convex hull problem which have not been implemented here, yet. """ from __future__ import annotations from collections.abc import Iterable class Point: """ Defines a 2-d point for use by all convex-hull algorithms. Parameters ---------- x: an int or a float, the x-coordinate of the 2-d point y: an int or a float, the y-coordinate of the 2-d point Examples -------- >>> Point(1, 2) (1.0, 2.0) >>> Point("1", "2") (1.0, 2.0) >>> Point(1, 2) > Point(0, 1) True >>> Point(1, 1) == Point(1, 1) True >>> Point(-0.5, 1) == Point(0.5, 1) False >>> Point("pi", "e") Traceback (most recent call last): ... ValueError: could not convert string to float: 'pi' """ def __init__(self, x, y): self.x, self.y = float(x), float(y) def __eq__(self, other): return self.x == other.x and self.y == other.y def __ne__(self, other): return not self == other def __gt__(self, other): if self.x > other.x: return True elif self.x == other.x: return self.y > other.y return False def __lt__(self, other): return not self > other def __ge__(self, other): if self.x > other.x: return True elif self.x == other.x: return self.y >= other.y return False def __le__(self, other): if self.x < other.x: return True elif self.x == other.x: return self.y <= other.y return False def __repr__(self): return f"({self.x}, {self.y})" def __hash__(self): return hash(self.x) def _construct_points( list_of_tuples: list[Point] | list[list[float]] | Iterable[list[float]], ) -> list[Point]: """ constructs a list of points from an array-like object of numbers Arguments --------- list_of_tuples: array-like object of type numbers. Acceptable types so far are lists, tuples and sets. Returns -------- points: a list where each item is of type Point. This contains only objects which can be converted into a Point. Examples ------- >>> _construct_points([[1, 1], [2, -1], [0.3, 4]]) [(1.0, 1.0), (2.0, -1.0), (0.3, 4.0)] >>> _construct_points([1, 2]) Ignoring deformed point 1. All points must have at least 2 coordinates. Ignoring deformed point 2. All points must have at least 2 coordinates. [] >>> _construct_points([]) [] >>> _construct_points(None) [] """ points: list[Point] = [] if list_of_tuples: for p in list_of_tuples: if isinstance(p, Point): points.append(p) else: try: points.append(Point(p[0], p[1])) except (IndexError, TypeError): print( f"Ignoring deformed point {p}. All points" " must have at least 2 coordinates." ) return points def _validate_input(points: list[Point] | list[list[float]]) -> list[Point]: """ validates an input instance before a convex-hull algorithms uses it Parameters --------- points: array-like, the 2d points to validate before using with a convex-hull algorithm. The elements of points must be either lists, tuples or Points. Returns ------- points: array_like, an iterable of all well-defined Points constructed passed in. Exception --------- ValueError: if points is empty or None, or if a wrong data structure like a scalar is passed TypeError: if an iterable but non-indexable object (eg. dictionary) is passed. The exception to this a set which we'll convert to a list before using Examples ------- >>> _validate_input([[1, 2]]) [(1.0, 2.0)] >>> _validate_input([(1, 2)]) [(1.0, 2.0)] >>> _validate_input([Point(2, 1), Point(-1, 2)]) [(2.0, 1.0), (-1.0, 2.0)] >>> _validate_input([]) Traceback (most recent call last): ... ValueError: Expecting a list of points but got [] >>> _validate_input(1) Traceback (most recent call last): ... ValueError: Expecting an iterable object but got an non-iterable type 1 """ if not hasattr(points, "__iter__"): raise ValueError( f"Expecting an iterable object but got an non-iterable type {points}" ) if not points: raise ValueError(f"Expecting a list of points but got {points}") return _construct_points(points) def _det(a: Point, b: Point, c: Point) -> float: """ Computes the sign perpendicular distance of a 2d point c from a line segment ab. The sign indicates the direction of c relative to ab. A Positive value means c is above ab (to the left), while a negative value means c is below ab (to the right). 0 means all three points are on a straight line. As a side note, 0.5 * abs|det| is the area of triangle abc Parameters ---------- a: point, the point on the left end of line segment ab b: point, the point on the right end of line segment ab c: point, the point for which the direction and location is desired. Returns -------- det: float, abs(det) is the distance of c from ab. The sign indicates which side of line segment ab c is. det is computed as (a_xb_y + c_xa_y + b_xc_y) - (a_yb_x + c_ya_x + b_yc_x) Examples ---------- >>> _det(Point(1, 1), Point(1, 2), Point(1, 5)) 0.0 >>> _det(Point(0, 0), Point(10, 0), Point(0, 10)) 100.0 >>> _det(Point(0, 0), Point(10, 0), Point(0, -10)) -100.0 """ det = (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x) return det def convex_hull_bf(points: list[Point]) -> list[Point]: """ Constructs the convex hull of a set of 2D points using a brute force algorithm. The algorithm basically considers all combinations of points (i, j) and uses the definition of convexity to determine whether (i, j) is part of the convex hull or not. (i, j) is part of the convex hull if and only iff there are no points on both sides of the line segment connecting the ij, and there is no point k such that k is on either end of the ij. Runtime: O(n^3) - definitely horrible Parameters --------- points: array-like of object of Points, lists or tuples. The set of 2d points for which the convex-hull is needed Returns ------ convex_set: list, the convex-hull of points sorted in non-decreasing order. See Also -------- convex_hull_recursive, Examples --------- >>> convex_hull_bf([[0, 0], [1, 0], [10, 1]]) [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] >>> convex_hull_bf([[0, 0], [1, 0], [10, 0]]) [(0.0, 0.0), (10.0, 0.0)] >>> convex_hull_bf([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], ... [-0.75, 1]]) [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] >>> convex_hull_bf([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), ... (2, -1), (2, -4), (1, -3)]) [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] """ points = sorted(_validate_input(points)) n = len(points) convex_set = set() for i in range(n - 1): for j in range(i + 1, n): points_left_of_ij = points_right_of_ij = False ij_part_of_convex_hull = True for k in range(n): if k != i and k != j: det_k = _det(points[i], points[j], points[k]) if det_k > 0: points_left_of_ij = True elif det_k < 0: points_right_of_ij = True else: # point[i], point[j], point[k] all lie on a straight line # if point[k] is to the left of point[i] or it's to the # right of point[j], then point[i], point[j] cannot be # part of the convex hull of A if points[k] < points[i] or points[k] > points[j]: ij_part_of_convex_hull = False break if points_left_of_ij and points_right_of_ij: ij_part_of_convex_hull = False break if ij_part_of_convex_hull: convex_set.update([points[i], points[j]]) return sorted(convex_set) def convex_hull_recursive(points: list[Point]) -> list[Point]: """ Constructs the convex hull of a set of 2D points using a divide-and-conquer strategy The algorithm exploits the geometric properties of the problem by repeatedly partitioning the set of points into smaller hulls, and finding the convex hull of these smaller hulls. The union of the convex hull from smaller hulls is the solution to the convex hull of the larger problem. Parameter --------- points: array-like of object of Points, lists or tuples. The set of 2d points for which the convex-hull is needed Runtime: O(n log n) Returns ------- convex_set: list, the convex-hull of points sorted in non-decreasing order. Examples --------- >>> convex_hull_recursive([[0, 0], [1, 0], [10, 1]]) [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] >>> convex_hull_recursive([[0, 0], [1, 0], [10, 0]]) [(0.0, 0.0), (10.0, 0.0)] >>> convex_hull_recursive([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], ... [-0.75, 1]]) [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] >>> convex_hull_recursive([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), ... (2, -1), (2, -4), (1, -3)]) [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] """ points = sorted(_validate_input(points)) n = len(points) # divide all the points into an upper hull and a lower hull # the left most point and the right most point are definitely # members of the convex hull by definition. # use these two anchors to divide all the points into two hulls, # an upper hull and a lower hull. # all points to the left (above) the line joining the extreme points belong to the # upper hull # all points to the right (below) the line joining the extreme points below to the # lower hull # ignore all points on the line joining the extreme points since they cannot be # part of the convex hull left_most_point = points[0] right_most_point = points[n - 1] convex_set = {left_most_point, right_most_point} upper_hull = [] lower_hull = [] for i in range(1, n - 1): det = _det(left_most_point, right_most_point, points[i]) if det > 0: upper_hull.append(points[i]) elif det < 0: lower_hull.append(points[i]) _construct_hull(upper_hull, left_most_point, right_most_point, convex_set) _construct_hull(lower_hull, right_most_point, left_most_point, convex_set) return sorted(convex_set) def _construct_hull( points: list[Point], left: Point, right: Point, convex_set: set[Point] ) -> None: """ Parameters --------- points: list or None, the hull of points from which to choose the next convex-hull point left: Point, the point to the left of line segment joining left and right right: The point to the right of the line segment joining left and right convex_set: set, the current convex-hull. The state of convex-set gets updated by this function Note ---- For the line segment 'ab', 'a' is on the left and 'b' on the right. but the reverse is true for the line segment 'ba'. Returns ------- Nothing, only updates the state of convex-set """ if points: extreme_point = None extreme_point_distance = float("-inf") candidate_points = [] for p in points: det = _det(left, right, p) if det > 0: candidate_points.append(p) if det > extreme_point_distance: extreme_point_distance = det extreme_point = p if extreme_point: _construct_hull(candidate_points, left, extreme_point, convex_set) convex_set.add(extreme_point) _construct_hull(candidate_points, extreme_point, right, convex_set) def convex_hull_melkman(points: list[Point]) -> list[Point]: """ Constructs the convex hull of a set of 2D points using the melkman algorithm. The algorithm works by iteratively inserting points of a simple polygonal chain (meaning that no line segments between two consecutive points cross each other). Sorting the points yields such a polygonal chain. For a detailed description, see http://cgm.cs.mcgill.ca/~athens/cs601/Melkman.html Runtime: O(n log n) - O(n) if points are already sorted in the input Parameters --------- points: array-like of object of Points, lists or tuples. The set of 2d points for which the convex-hull is needed Returns ------ convex_set: list, the convex-hull of points sorted in non-decreasing order. See Also -------- Examples --------- >>> convex_hull_melkman([[0, 0], [1, 0], [10, 1]]) [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] >>> convex_hull_melkman([[0, 0], [1, 0], [10, 0]]) [(0.0, 0.0), (10.0, 0.0)] >>> convex_hull_melkman([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], ... [-0.75, 1]]) [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] >>> convex_hull_melkman([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), ... (2, -1), (2, -4), (1, -3)]) [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] """ points = sorted(_validate_input(points)) n = len(points) convex_hull = points[:2] for i in range(2, n): det = _det(convex_hull[1], convex_hull[0], points[i]) if det > 0: convex_hull.insert(0, points[i]) break elif det < 0: convex_hull.append(points[i]) break else: convex_hull[1] = points[i] i += 1 for j in range(i, n): if ( _det(convex_hull[0], convex_hull[-1], points[j]) > 0 and _det(convex_hull[-1], convex_hull[0], points[1]) < 0 ): # The point lies within the convex hull continue convex_hull.insert(0, points[j]) convex_hull.append(points[j]) while _det(convex_hull[0], convex_hull[1], convex_hull[2]) >= 0: del convex_hull[1] while _det(convex_hull[-1], convex_hull[-2], convex_hull[-3]) <= 0: del convex_hull[-2] # `convex_hull` is contains the convex hull in circular order return sorted(convex_hull[1:] if len(convex_hull) > 3 else convex_hull) def main(): points = [ (0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), (2, -1), (2, -4), (1, -3), ] # the convex set of points is # [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)] results_bf = convex_hull_bf(points) results_recursive = convex_hull_recursive(points) assert results_bf == results_recursive results_melkman = convex_hull_melkman(points) assert results_bf == results_melkman print(results_bf) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other 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,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Longest Common Substring Problem Statement: Given two sequences, find the longest common substring present in both of them. A substring is necessarily continuous. Example: "abcdef" and "xabded" have two longest common substrings, "ab" or "de". Therefore, algorithm should return any one of them. """ def longest_common_substring(text1: str, text2: str) -> str: """ Finds the longest common substring between two strings. >>> longest_common_substring("", "") '' >>> longest_common_substring("a","") '' >>> longest_common_substring("", "a") '' >>> longest_common_substring("a", "a") 'a' >>> longest_common_substring("abcdef", "bcd") 'bcd' >>> longest_common_substring("abcdef", "xabded") 'ab' >>> longest_common_substring("GeeksforGeeks", "GeeksQuiz") 'Geeks' >>> longest_common_substring("abcdxyz", "xyzabcd") 'abcd' >>> longest_common_substring("zxabcdezy", "yzabcdezx") 'abcdez' >>> longest_common_substring("OldSite:GeeksforGeeks.org", "NewSite:GeeksQuiz.com") 'Site:Geeks' >>> longest_common_substring(1, 1) Traceback (most recent call last): ... ValueError: longest_common_substring() takes two strings for inputs """ if not (isinstance(text1, str) and isinstance(text2, str)): raise ValueError("longest_common_substring() takes two strings for inputs") text1_length = len(text1) text2_length = len(text2) dp = [[0] * (text2_length + 1) for _ in range(text1_length + 1)] ans_index = 0 ans_length = 0 for i in range(1, text1_length + 1): for j in range(1, text2_length + 1): if text1[i - 1] == text2[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] if dp[i][j] > ans_length: ans_index = i ans_length = dp[i][j] return text1[ans_index - ans_length : ans_index] if __name__ == "__main__": import doctest doctest.testmod()
""" Longest Common Substring Problem Statement: Given two sequences, find the longest common substring present in both of them. A substring is necessarily continuous. Example: "abcdef" and "xabded" have two longest common substrings, "ab" or "de". Therefore, algorithm should return any one of them. """ def longest_common_substring(text1: str, text2: str) -> str: """ Finds the longest common substring between two strings. >>> longest_common_substring("", "") '' >>> longest_common_substring("a","") '' >>> longest_common_substring("", "a") '' >>> longest_common_substring("a", "a") 'a' >>> longest_common_substring("abcdef", "bcd") 'bcd' >>> longest_common_substring("abcdef", "xabded") 'ab' >>> longest_common_substring("GeeksforGeeks", "GeeksQuiz") 'Geeks' >>> longest_common_substring("abcdxyz", "xyzabcd") 'abcd' >>> longest_common_substring("zxabcdezy", "yzabcdezx") 'abcdez' >>> longest_common_substring("OldSite:GeeksforGeeks.org", "NewSite:GeeksQuiz.com") 'Site:Geeks' >>> longest_common_substring(1, 1) Traceback (most recent call last): ... ValueError: longest_common_substring() takes two strings for inputs """ if not (isinstance(text1, str) and isinstance(text2, str)): raise ValueError("longest_common_substring() takes two strings for inputs") text1_length = len(text1) text2_length = len(text2) dp = [[0] * (text2_length + 1) for _ in range(text1_length + 1)] ans_index = 0 ans_length = 0 for i in range(1, text1_length + 1): for j in range(1, text2_length + 1): if text1[i - 1] == text2[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] if dp[i][j] > ans_length: ans_index = i ans_length = dp[i][j] return text1[ans_index - ans_length : ans_index] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" An OR Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are 0, and 1 (True) otherwise. Following is the truth table of an AND Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 0 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 1 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def or_gate(input_1: int, input_2: int) -> int: """ Calculate OR of the input values >>> or_gate(0, 0) 0 >>> or_gate(0, 1) 1 >>> or_gate(1, 0) 1 >>> or_gate(1, 1) 1 """ return int((input_1, input_2).count(1) != 0) def test_or_gate() -> None: """ Tests the or_gate function """ assert or_gate(0, 0) == 0 assert or_gate(0, 1) == 1 assert or_gate(1, 0) == 1 assert or_gate(1, 1) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
""" An OR Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are 0, and 1 (True) otherwise. Following is the truth table of an AND Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 0 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 1 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def or_gate(input_1: int, input_2: int) -> int: """ Calculate OR of the input values >>> or_gate(0, 0) 0 >>> or_gate(0, 1) 1 >>> or_gate(1, 0) 1 >>> or_gate(1, 1) 1 """ return int((input_1, input_2).count(1) != 0) def test_or_gate() -> None: """ Tests the or_gate function """ assert or_gate(0, 0) == 0 assert or_gate(0, 1) == 1 assert or_gate(1, 0) == 1 assert or_gate(1, 1) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Modular Exponential. Modular exponentiation is a type of exponentiation performed over a modulus. For more explanation, please check https://en.wikipedia.org/wiki/Modular_exponentiation """ """Calculate Modular Exponential.""" def modular_exponential(base: int, power: int, mod: int): """ >>> modular_exponential(5, 0, 10) 1 >>> modular_exponential(2, 8, 7) 4 >>> modular_exponential(3, -2, 9) -1 """ if power < 0: return -1 base %= mod result = 1 while power > 0: if power & 1: result = (result * base) % mod power = power >> 1 base = (base * base) % mod return result def main(): """Call Modular Exponential Function.""" print(modular_exponential(3, 200, 13)) if __name__ == "__main__": import doctest doctest.testmod() main()
""" Modular Exponential. Modular exponentiation is a type of exponentiation performed over a modulus. For more explanation, please check https://en.wikipedia.org/wiki/Modular_exponentiation """ """Calculate Modular Exponential.""" def modular_exponential(base: int, power: int, mod: int): """ >>> modular_exponential(5, 0, 10) 1 >>> modular_exponential(2, 8, 7) 4 >>> modular_exponential(3, -2, 9) -1 """ if power < 0: return -1 base %= mod result = 1 while power > 0: if power & 1: result = (result * base) % mod power = power >> 1 base = (base * base) % mod return result def main(): """Call Modular Exponential Function.""" print(modular_exponential(3, 200, 13)) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Arithmetic analysis Arithmetic analysis is a branch of mathematics that deals with solving linear equations. * <https://en.wikipedia.org/wiki/System_of_linear_equations> * <https://en.wikipedia.org/wiki/Gaussian_elimination> * <https://en.wikipedia.org/wiki/Root-finding_algorithms>
# Arithmetic analysis Arithmetic analysis is a branch of mathematics that deals with solving linear equations. * <https://en.wikipedia.org/wiki/System_of_linear_equations> * <https://en.wikipedia.org/wiki/Gaussian_elimination> * <https://en.wikipedia.org/wiki/Root-finding_algorithms>
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Algorithms to determine if a string is palindrome test_data = { "MALAYALAM": True, "String": False, "rotor": True, "level": True, "A": True, "BB": True, "ABC": False, "amanaplanacanalpanama": True, # "a man a plan a canal panama" } # Ensure our test data is valid assert all((key == key[::-1]) is value for key, value in test_data.items()) def is_palindrome(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome(key) is value for key, value in test_data.items()) True """ start_i = 0 end_i = len(s) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True def is_palindrome_recursive(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_recursive(key) is value for key, value in test_data.items()) True """ if len(s) <= 1: return True if s[0] == s[len(s) - 1]: return is_palindrome_recursive(s[1:-1]) else: return False def is_palindrome_slice(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_slice(key) is value for key, value in test_data.items()) True """ return s == s[::-1] if __name__ == "__main__": for key, value in test_data.items(): assert is_palindrome(key) is is_palindrome_recursive(key) assert is_palindrome(key) is is_palindrome_slice(key) print(f"{key:21} {value}") print("a man a plan a canal panama")
# Algorithms to determine if a string is palindrome test_data = { "MALAYALAM": True, "String": False, "rotor": True, "level": True, "A": True, "BB": True, "ABC": False, "amanaplanacanalpanama": True, # "a man a plan a canal panama" } # Ensure our test data is valid assert all((key == key[::-1]) is value for key, value in test_data.items()) def is_palindrome(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome(key) is value for key, value in test_data.items()) True """ start_i = 0 end_i = len(s) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True def is_palindrome_recursive(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_recursive(key) is value for key, value in test_data.items()) True """ if len(s) <= 1: return True if s[0] == s[len(s) - 1]: return is_palindrome_recursive(s[1:-1]) else: return False def is_palindrome_slice(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_slice(key) is value for key, value in test_data.items()) True """ return s == s[::-1] if __name__ == "__main__": for key, value in test_data.items(): assert is_palindrome(key) is is_palindrome_recursive(key) assert is_palindrome(key) is is_palindrome_slice(key) print(f"{key:21} {value}") print("a man a plan a canal panama")
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def binary_search(lst, item, start, end): if start == end: return start if lst[start] > item else start + 1 if start > end: return start mid = (start + end) // 2 if lst[mid] < item: return binary_search(lst, item, mid + 1, end) elif lst[mid] > item: return binary_search(lst, item, start, mid - 1) else: return mid def insertion_sort(lst): length = len(lst) for index in range(1, length): value = lst[index] pos = binary_search(lst, value, 0, index - 1) lst = lst[:pos] + [value] + lst[pos:index] + lst[index + 1 :] return lst def merge(left, right): if not left: return right if not right: return left if left[0] < right[0]: return [left[0]] + merge(left[1:], right) return [right[0]] + merge(left, right[1:]) def tim_sort(lst): """ >>> tim_sort("Python") ['P', 'h', 'n', 'o', 't', 'y'] >>> tim_sort((1.1, 1, 0, -1, -1.1)) [-1.1, -1, 0, 1, 1.1] >>> tim_sort(list(reversed(list(range(7))))) [0, 1, 2, 3, 4, 5, 6] >>> tim_sort([3, 2, 1]) == insertion_sort([3, 2, 1]) True >>> tim_sort([3, 2, 1]) == sorted([3, 2, 1]) True """ length = len(lst) runs, sorted_runs = [], [] new_run = [lst[0]] sorted_array = [] i = 1 while i < length: if lst[i] < lst[i - 1]: runs.append(new_run) new_run = [lst[i]] else: new_run.append(lst[i]) i += 1 runs.append(new_run) for run in runs: sorted_runs.append(insertion_sort(run)) for run in sorted_runs: sorted_array = merge(sorted_array, run) return sorted_array def main(): lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] sorted_lst = tim_sort(lst) print(sorted_lst) if __name__ == "__main__": main()
def binary_search(lst, item, start, end): if start == end: return start if lst[start] > item else start + 1 if start > end: return start mid = (start + end) // 2 if lst[mid] < item: return binary_search(lst, item, mid + 1, end) elif lst[mid] > item: return binary_search(lst, item, start, mid - 1) else: return mid def insertion_sort(lst): length = len(lst) for index in range(1, length): value = lst[index] pos = binary_search(lst, value, 0, index - 1) lst = lst[:pos] + [value] + lst[pos:index] + lst[index + 1 :] return lst def merge(left, right): if not left: return right if not right: return left if left[0] < right[0]: return [left[0]] + merge(left[1:], right) return [right[0]] + merge(left, right[1:]) def tim_sort(lst): """ >>> tim_sort("Python") ['P', 'h', 'n', 'o', 't', 'y'] >>> tim_sort((1.1, 1, 0, -1, -1.1)) [-1.1, -1, 0, 1, 1.1] >>> tim_sort(list(reversed(list(range(7))))) [0, 1, 2, 3, 4, 5, 6] >>> tim_sort([3, 2, 1]) == insertion_sort([3, 2, 1]) True >>> tim_sort([3, 2, 1]) == sorted([3, 2, 1]) True """ length = len(lst) runs, sorted_runs = [], [] new_run = [lst[0]] sorted_array = [] i = 1 while i < length: if lst[i] < lst[i - 1]: runs.append(new_run) new_run = [lst[i]] else: new_run.append(lst[i]) i += 1 runs.append(new_run) for run in runs: sorted_runs.append(insertion_sort(run)) for run in sorted_runs: sorted_array = merge(sorted_array, run) return sorted_array def main(): lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7] sorted_lst = tim_sort(lst) print(sorted_lst) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Chinese Remainder Theorem: GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) If GCD(a,b) = 1, then for any remainder ra modulo a and any remainder rb modulo b there exists integer n, such that n = ra (mod a) and n = ra(mod b). If n1 and n2 are two such integers, then n1=n2(mod ab) Algorithm : 1. Use extended euclid algorithm to find x,y such that a*x + b*y = 1 2. Take n = ra*by + rb*ax """ from __future__ import annotations # Extended Euclid def extended_euclid(a: int, b: int) -> tuple[int, int]: """ >>> 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) # Uses ExtendedEuclid to find inverses def chinese_remainder_theorem(n1: int, r1: int, n2: int, r2: int) -> int: """ >>> chinese_remainder_theorem(5,1,7,3) 31 Explanation : 31 is the smallest number such that (i) When we divide it by 5, we get remainder 1 (ii) When we divide it by 7, we get remainder 3 >>> chinese_remainder_theorem(6,1,4,3) 14 """ (x, y) = extended_euclid(n1, n2) m = n1 * n2 n = r2 * x * n1 + r1 * y * n2 return (n % m + m) % m # ----------SAME SOLUTION USING InvertModulo instead ExtendedEuclid---------------- # This function find the inverses of a i.e., a^(-1) def invert_modulo(a: int, n: int) -> int: """ >>> invert_modulo(2, 5) 3 >>> invert_modulo(8,7) 1 """ (b, x) = extended_euclid(a, n) if b < 0: b = (b % n + n) % n return b # Same a above using InvertingModulo def chinese_remainder_theorem2(n1: int, r1: int, n2: int, r2: int) -> int: """ >>> chinese_remainder_theorem2(5,1,7,3) 31 >>> chinese_remainder_theorem2(6,1,4,3) 14 """ x, y = invert_modulo(n1, n2), invert_modulo(n2, n1) m = n1 * n2 n = r2 * x * n1 + r1 * y * n2 return (n % m + m) % m if __name__ == "__main__": from doctest import testmod testmod(name="chinese_remainder_theorem", verbose=True) testmod(name="chinese_remainder_theorem2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_euclid", verbose=True)
""" Chinese Remainder Theorem: GCD ( Greatest Common Divisor ) or HCF ( Highest Common Factor ) If GCD(a,b) = 1, then for any remainder ra modulo a and any remainder rb modulo b there exists integer n, such that n = ra (mod a) and n = ra(mod b). If n1 and n2 are two such integers, then n1=n2(mod ab) Algorithm : 1. Use extended euclid algorithm to find x,y such that a*x + b*y = 1 2. Take n = ra*by + rb*ax """ from __future__ import annotations # Extended Euclid def extended_euclid(a: int, b: int) -> tuple[int, int]: """ >>> 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) # Uses ExtendedEuclid to find inverses def chinese_remainder_theorem(n1: int, r1: int, n2: int, r2: int) -> int: """ >>> chinese_remainder_theorem(5,1,7,3) 31 Explanation : 31 is the smallest number such that (i) When we divide it by 5, we get remainder 1 (ii) When we divide it by 7, we get remainder 3 >>> chinese_remainder_theorem(6,1,4,3) 14 """ (x, y) = extended_euclid(n1, n2) m = n1 * n2 n = r2 * x * n1 + r1 * y * n2 return (n % m + m) % m # ----------SAME SOLUTION USING InvertModulo instead ExtendedEuclid---------------- # This function find the inverses of a i.e., a^(-1) def invert_modulo(a: int, n: int) -> int: """ >>> invert_modulo(2, 5) 3 >>> invert_modulo(8,7) 1 """ (b, x) = extended_euclid(a, n) if b < 0: b = (b % n + n) % n return b # Same a above using InvertingModulo def chinese_remainder_theorem2(n1: int, r1: int, n2: int, r2: int) -> int: """ >>> chinese_remainder_theorem2(5,1,7,3) 31 >>> chinese_remainder_theorem2(6,1,4,3) 14 """ x, y = invert_modulo(n1, n2), invert_modulo(n2, n1) m = n1 * n2 n = r2 * x * n1 + r1 * y * n2 return (n % m + m) % m if __name__ == "__main__": from doctest import testmod testmod(name="chinese_remainder_theorem", verbose=True) testmod(name="chinese_remainder_theorem2", verbose=True) testmod(name="invert_modulo", verbose=True) testmod(name="extended_euclid", verbose=True)
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" This is pure Python implementation of sentinel linear search algorithm For doctests run following command: python -m doctest -v sentinel_linear_search.py or python3 -m doctest -v sentinel_linear_search.py For manual testing run: python sentinel_linear_search.py """ def sentinel_linear_search(sequence, target): """Pure implementation of sentinel linear search algorithm in Python :param sequence: some sequence with comparable items :param target: item value to search :return: index of found item or None if item is not found Examples: >>> sentinel_linear_search([0, 5, 7, 10, 15], 0) 0 >>> sentinel_linear_search([0, 5, 7, 10, 15], 15) 4 >>> sentinel_linear_search([0, 5, 7, 10, 15], 5) 1 >>> sentinel_linear_search([0, 5, 7, 10, 15], 6) """ sequence.append(target) index = 0 while sequence[index] != target: index += 1 sequence.pop() if index == len(sequence): return None return index if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() sequence = [int(item) for item in user_input.split(",")] target_input = input("Enter a single number to be found in the list:\n") target = int(target_input) result = sentinel_linear_search(sequence, target) if result is not None: print(f"{target} found at positions: {result}") else: print("Not found")
""" This is pure Python implementation of sentinel linear search algorithm For doctests run following command: python -m doctest -v sentinel_linear_search.py or python3 -m doctest -v sentinel_linear_search.py For manual testing run: python sentinel_linear_search.py """ def sentinel_linear_search(sequence, target): """Pure implementation of sentinel linear search algorithm in Python :param sequence: some sequence with comparable items :param target: item value to search :return: index of found item or None if item is not found Examples: >>> sentinel_linear_search([0, 5, 7, 10, 15], 0) 0 >>> sentinel_linear_search([0, 5, 7, 10, 15], 15) 4 >>> sentinel_linear_search([0, 5, 7, 10, 15], 5) 1 >>> sentinel_linear_search([0, 5, 7, 10, 15], 6) """ sequence.append(target) index = 0 while sequence[index] != target: index += 1 sequence.pop() if index == len(sequence): return None return index if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() sequence = [int(item) for item in user_input.split(",")] target_input = input("Enter a single number to be found in the list:\n") target = int(target_input) result = sentinel_linear_search(sequence, target) if result is not None: print(f"{target} found at positions: {result}") else: print("Not found")
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other 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 1: "extended trapezoidal rule" """ def method_1(boundary, steps): # "extended trapezoidal rule" # int(f) = dx/2 * (f1 + 2f2 + ... + 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 / 2.0) * f(a) for i in x_i: # print(i) y += h * f(i) y += (h / 2.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_1(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 1: "extended trapezoidal rule" """ def method_1(boundary, steps): # "extended trapezoidal rule" # int(f) = dx/2 * (f1 + 2f2 + ... + 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 / 2.0) * f(a) for i in x_i: # print(i) y += h * f(i) y += (h / 2.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_1(boundary, steps) print(f"y = {y}") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Youtube Explanation: https://www.youtube.com/watch?v=lBRtnuxg-gU from __future__ import annotations def minimum_cost_path(matrix: list[list[int]]) -> int: """ Find the minimum cost traced by all possible paths from top left to bottom right in a given matrix >>> minimum_cost_path([[2, 1], [3, 1], [4, 2]]) 6 >>> minimum_cost_path([[2, 1, 4], [2, 1, 3], [3, 2, 1]]) 7 """ # preprocessing the first row for i in range(1, len(matrix[0])): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1, len(matrix)): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1]) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
# Youtube Explanation: https://www.youtube.com/watch?v=lBRtnuxg-gU from __future__ import annotations def minimum_cost_path(matrix: list[list[int]]) -> int: """ Find the minimum cost traced by all possible paths from top left to bottom right in a given matrix >>> minimum_cost_path([[2, 1], [3, 1], [4, 2]]) 6 >>> minimum_cost_path([[2, 1, 4], [2, 1, 3], [3, 2, 1]]) 7 """ # preprocessing the first row for i in range(1, len(matrix[0])): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1, len(matrix)): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1]) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 234: https://projecteuler.net/problem=234 For any integer n, consider the three functions f1,n(x,y,z) = x^(n+1) + y^(n+1) - z^(n+1) f2,n(x,y,z) = (xy + yz + zx)*(x^(n-1) + y^(n-1) - z^(n-1)) f3,n(x,y,z) = xyz*(xn-2 + yn-2 - zn-2) and their combination fn(x,y,z) = f1,n(x,y,z) + f2,n(x,y,z) - f3,n(x,y,z) We call (x,y,z) a golden triple of order k if x, y, and z are all rational numbers of the form a / b with 0 < a < b ≤ k and there is (at least) one integer n, so that fn(x,y,z) = 0. Let s(x,y,z) = x + y + z. Let t = u / v be the sum of all distinct s(x,y,z) for all golden triples (x,y,z) of order 35. All the s(x,y,z) and t must be in reduced form. Find u + v. Solution: By expanding the brackets it is easy to show that fn(x, y, z) = (x + y + z) * (x^n + y^n - z^n). Since x,y,z are positive, the requirement fn(x, y, z) = 0 is fulfilled if and only if x^n + y^n = z^n. By Fermat's Last Theorem, this means that the absolute value of n can not exceed 2, i.e. n is in {-2, -1, 0, 1, 2}. We can eliminate n = 0 since then the equation would reduce to 1 + 1 = 1, for which there are no solutions. So all we have to do is iterate through the possible numerators and denominators of x and y, calculate the corresponding z, and check if the corresponding numerator and denominator are integer and satisfy 0 < z_num < z_den <= 0. We use a set "uniquq_s" to make sure there are no duplicates, and the fractions.Fraction class to make sure we get the right numerator and denominator. Reference: https://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem """ from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def is_sq(number: int) -> bool: """ Check if number is a perfect square. >>> is_sq(1) True >>> is_sq(1000001) False >>> is_sq(1000000) True """ sq: int = int(number**0.5) return number == sq * sq def add_three( x_num: int, x_den: int, y_num: int, y_den: int, z_num: int, z_den: int ) -> tuple[int, int]: """ Given the numerators and denominators of three fractions, return the numerator and denominator of their sum in lowest form. >>> add_three(1, 3, 1, 3, 1, 3) (1, 1) >>> add_three(2, 5, 4, 11, 12, 3) (262, 55) """ top: int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den bottom: int = x_den * y_den * z_den hcf: int = gcd(top, bottom) top //= hcf bottom //= hcf return top, bottom def solution(order: int = 35) -> int: """ Find the sum of the numerator and denominator of the sum of all s(x,y,z) for golden triples (x,y,z) of the given order. >>> solution(5) 296 >>> solution(10) 12519 >>> solution(20) 19408891927 """ unique_s: set = set() hcf: int total: Fraction = Fraction(0) fraction_sum: tuple[int, int] for x_num in range(1, order + 1): for x_den in range(x_num + 1, order + 1): for y_num in range(1, order + 1): for y_den in range(y_num + 1, order + 1): # n=1 z_num = x_num * y_den + x_den * y_num z_den = x_den * y_den hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=2 z_num = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) z_den = x_den * x_den * y_den * y_den if is_sq(z_num) and is_sq(z_den): z_num = int(sqrt(z_num)) z_den = int(sqrt(z_den)) hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=-1 z_num = x_num * y_num z_den = x_den * y_num + x_num * y_den hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=2 z_num = x_num * x_num * y_num * y_num z_den = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(z_num) and is_sq(z_den): z_num = int(sqrt(z_num)) z_den = int(sqrt(z_den)) hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) for num, den in unique_s: total += Fraction(num, den) return total.denominator + total.numerator if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 234: https://projecteuler.net/problem=234 For any integer n, consider the three functions f1,n(x,y,z) = x^(n+1) + y^(n+1) - z^(n+1) f2,n(x,y,z) = (xy + yz + zx)*(x^(n-1) + y^(n-1) - z^(n-1)) f3,n(x,y,z) = xyz*(xn-2 + yn-2 - zn-2) and their combination fn(x,y,z) = f1,n(x,y,z) + f2,n(x,y,z) - f3,n(x,y,z) We call (x,y,z) a golden triple of order k if x, y, and z are all rational numbers of the form a / b with 0 < a < b ≤ k and there is (at least) one integer n, so that fn(x,y,z) = 0. Let s(x,y,z) = x + y + z. Let t = u / v be the sum of all distinct s(x,y,z) for all golden triples (x,y,z) of order 35. All the s(x,y,z) and t must be in reduced form. Find u + v. Solution: By expanding the brackets it is easy to show that fn(x, y, z) = (x + y + z) * (x^n + y^n - z^n). Since x,y,z are positive, the requirement fn(x, y, z) = 0 is fulfilled if and only if x^n + y^n = z^n. By Fermat's Last Theorem, this means that the absolute value of n can not exceed 2, i.e. n is in {-2, -1, 0, 1, 2}. We can eliminate n = 0 since then the equation would reduce to 1 + 1 = 1, for which there are no solutions. So all we have to do is iterate through the possible numerators and denominators of x and y, calculate the corresponding z, and check if the corresponding numerator and denominator are integer and satisfy 0 < z_num < z_den <= 0. We use a set "uniquq_s" to make sure there are no duplicates, and the fractions.Fraction class to make sure we get the right numerator and denominator. Reference: https://en.wikipedia.org/wiki/Fermat%27s_Last_Theorem """ from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def is_sq(number: int) -> bool: """ Check if number is a perfect square. >>> is_sq(1) True >>> is_sq(1000001) False >>> is_sq(1000000) True """ sq: int = int(number**0.5) return number == sq * sq def add_three( x_num: int, x_den: int, y_num: int, y_den: int, z_num: int, z_den: int ) -> tuple[int, int]: """ Given the numerators and denominators of three fractions, return the numerator and denominator of their sum in lowest form. >>> add_three(1, 3, 1, 3, 1, 3) (1, 1) >>> add_three(2, 5, 4, 11, 12, 3) (262, 55) """ top: int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den bottom: int = x_den * y_den * z_den hcf: int = gcd(top, bottom) top //= hcf bottom //= hcf return top, bottom def solution(order: int = 35) -> int: """ Find the sum of the numerator and denominator of the sum of all s(x,y,z) for golden triples (x,y,z) of the given order. >>> solution(5) 296 >>> solution(10) 12519 >>> solution(20) 19408891927 """ unique_s: set = set() hcf: int total: Fraction = Fraction(0) fraction_sum: tuple[int, int] for x_num in range(1, order + 1): for x_den in range(x_num + 1, order + 1): for y_num in range(1, order + 1): for y_den in range(y_num + 1, order + 1): # n=1 z_num = x_num * y_den + x_den * y_num z_den = x_den * y_den hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=2 z_num = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) z_den = x_den * x_den * y_den * y_den if is_sq(z_num) and is_sq(z_den): z_num = int(sqrt(z_num)) z_den = int(sqrt(z_den)) hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=-1 z_num = x_num * y_num z_den = x_den * y_num + x_num * y_den hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) # n=2 z_num = x_num * x_num * y_num * y_num z_den = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(z_num) and is_sq(z_den): z_num = int(sqrt(z_num)) z_den = int(sqrt(z_den)) hcf = gcd(z_num, z_den) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: fraction_sum = add_three( x_num, x_den, y_num, y_den, z_num, z_den ) unique_s.add(fraction_sum) for num, den in unique_s: total += Fraction(num, den) return total.denominator + total.numerator if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" this is code for forecasting but i modified it and used it for safety checker of data for ex: you have an online shop and for some reason some data are missing (the amount of data that u expected are not supposed to be) then we can use it *ps : 1. ofc we can use normal statistic method but in this case the data is quite absurd and only a little^^ 2. ofc u can use this and modified it for forecasting purpose for the next 3 months sales or something, u can just adjust it for ur own purpose """ import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def linear_regression_prediction( train_dt: list, train_usr: list, train_mtch: list, test_dt: list, test_mtch: list ) -> float: """ First method: linear regression input : training data (date, total_user, total_event) in list of float output : list of total user prediction in float >>> n = linear_regression_prediction([2,3,4,5], [5,3,4,6], [3,1,2,4], [2,1], [2,2]) >>> abs(n - 5.0) < 1e-6 # Checking precision because of floating point errors True """ x = np.array([[1, item, train_mtch[i]] for i, item in enumerate(train_dt)]) y = np.array(train_usr) beta = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose(), x)), x.transpose()), y) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2]) def sarimax_predictor(train_user: list, train_match: list, test_match: list) -> float: """ second method: Sarimax sarimax is a statistic method which using previous input and learn its pattern to predict future data input : training data (total_user, with exog data = total_event) in list of float output : list of total user prediction in float >>> sarimax_predictor([4,2,6,8], [3,1,2,4], [2]) 6.6666671111109626 """ order = (1, 2, 1) seasonal_order = (1, 1, 0, 7) model = SARIMAX( train_user, exog=train_match, order=order, seasonal_order=seasonal_order ) model_fit = model.fit(disp=False, maxiter=600, method="nm") result = model_fit.predict(1, len(test_match), exog=[test_match]) return result[0] def support_vector_regressor(x_train: list, x_test: list, train_user: list) -> float: """ Third method: Support vector regressor svr is quite the same with svm(support vector machine) it uses the same principles as the SVM for classification, with only a few minor differences and the only different is that it suits better for regression purpose input : training data (date, total_user, total_event) in list of float where x = list of set (date and total event) output : list of total user prediction in float >>> support_vector_regressor([[5,2],[1,5],[6,2]], [[3,2]], [2,1,4]) 1.634932078116079 """ regressor = SVR(kernel="rbf", C=1, gamma=0.1, epsilon=0.1) regressor.fit(x_train, train_user) y_pred = regressor.predict(x_test) return y_pred[0] def interquartile_range_checker(train_user: list) -> float: """ Optional method: interquatile range input : list of total user in float output : low limit of input in float this method can be used to check whether some data is outlier or not >>> interquartile_range_checker([1,2,3,4,5,6,7,8,9,10]) 2.8 """ train_user.sort() q1 = np.percentile(train_user, 25) q3 = np.percentile(train_user, 75) iqr = q3 - q1 low_lim = q1 - (iqr * 0.1) return low_lim def data_safety_checker(list_vote: list, actual_result: float) -> bool: """ Used to review all the votes (list result prediction) and compare it to the actual result. input : list of predictions output : print whether it's safe or not >>> data_safety_checker([2, 3, 4], 5.0) False """ safe = 0 not_safe = 0 for i in list_vote: if i > actual_result: safe = not_safe + 1 else: if abs(abs(i) - abs(actual_result)) <= 0.1: safe += 1 else: not_safe += 1 return safe > not_safe if __name__ == "__main__": # data_input_df = pd.read_csv("ex_data.csv", header=None) data_input = [[18231, 0.0, 1], [22621, 1.0, 2], [15675, 0.0, 3], [23583, 1.0, 4]] data_input_df = pd.DataFrame( data_input, columns=["total_user", "total_even", "days"] ) """ data column = total user in a day, how much online event held in one day, what day is that(sunday-saturday) """ # start normalization normalize_df = Normalizer().fit_transform(data_input_df.values) # split data total_date = normalize_df[:, 2].tolist() total_user = normalize_df[:, 0].tolist() total_match = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) x = normalize_df[:, [1, 2]].tolist() x_train = x[: len(x) - 1] x_test = x[len(x) - 1 :] # for linear regression & sarimax trn_date = total_date[: len(total_date) - 1] trn_user = total_user[: len(total_user) - 1] trn_match = total_match[: len(total_match) - 1] tst_date = total_date[len(total_date) - 1 :] tst_user = total_user[len(total_user) - 1 :] tst_match = total_match[len(total_match) - 1 :] # voting system with forecasting res_vote = [ linear_regression_prediction( trn_date, trn_user, trn_match, tst_date, tst_match ), sarimax_predictor(trn_user, trn_match, tst_match), support_vector_regressor(x_train, x_test, trn_user), ] # check the safety of today's data not_str = "" if data_safety_checker(res_vote, tst_user) else "not " print("Today's data is {not_str}safe.")
""" this is code for forecasting but i modified it and used it for safety checker of data for ex: you have an online shop and for some reason some data are missing (the amount of data that u expected are not supposed to be) then we can use it *ps : 1. ofc we can use normal statistic method but in this case the data is quite absurd and only a little^^ 2. ofc u can use this and modified it for forecasting purpose for the next 3 months sales or something, u can just adjust it for ur own purpose """ import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def linear_regression_prediction( train_dt: list, train_usr: list, train_mtch: list, test_dt: list, test_mtch: list ) -> float: """ First method: linear regression input : training data (date, total_user, total_event) in list of float output : list of total user prediction in float >>> n = linear_regression_prediction([2,3,4,5], [5,3,4,6], [3,1,2,4], [2,1], [2,2]) >>> abs(n - 5.0) < 1e-6 # Checking precision because of floating point errors True """ x = np.array([[1, item, train_mtch[i]] for i, item in enumerate(train_dt)]) y = np.array(train_usr) beta = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose(), x)), x.transpose()), y) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2]) def sarimax_predictor(train_user: list, train_match: list, test_match: list) -> float: """ second method: Sarimax sarimax is a statistic method which using previous input and learn its pattern to predict future data input : training data (total_user, with exog data = total_event) in list of float output : list of total user prediction in float >>> sarimax_predictor([4,2,6,8], [3,1,2,4], [2]) 6.6666671111109626 """ order = (1, 2, 1) seasonal_order = (1, 1, 0, 7) model = SARIMAX( train_user, exog=train_match, order=order, seasonal_order=seasonal_order ) model_fit = model.fit(disp=False, maxiter=600, method="nm") result = model_fit.predict(1, len(test_match), exog=[test_match]) return result[0] def support_vector_regressor(x_train: list, x_test: list, train_user: list) -> float: """ Third method: Support vector regressor svr is quite the same with svm(support vector machine) it uses the same principles as the SVM for classification, with only a few minor differences and the only different is that it suits better for regression purpose input : training data (date, total_user, total_event) in list of float where x = list of set (date and total event) output : list of total user prediction in float >>> support_vector_regressor([[5,2],[1,5],[6,2]], [[3,2]], [2,1,4]) 1.634932078116079 """ regressor = SVR(kernel="rbf", C=1, gamma=0.1, epsilon=0.1) regressor.fit(x_train, train_user) y_pred = regressor.predict(x_test) return y_pred[0] def interquartile_range_checker(train_user: list) -> float: """ Optional method: interquatile range input : list of total user in float output : low limit of input in float this method can be used to check whether some data is outlier or not >>> interquartile_range_checker([1,2,3,4,5,6,7,8,9,10]) 2.8 """ train_user.sort() q1 = np.percentile(train_user, 25) q3 = np.percentile(train_user, 75) iqr = q3 - q1 low_lim = q1 - (iqr * 0.1) return low_lim def data_safety_checker(list_vote: list, actual_result: float) -> bool: """ Used to review all the votes (list result prediction) and compare it to the actual result. input : list of predictions output : print whether it's safe or not >>> data_safety_checker([2, 3, 4], 5.0) False """ safe = 0 not_safe = 0 for i in list_vote: if i > actual_result: safe = not_safe + 1 else: if abs(abs(i) - abs(actual_result)) <= 0.1: safe += 1 else: not_safe += 1 return safe > not_safe if __name__ == "__main__": # data_input_df = pd.read_csv("ex_data.csv", header=None) data_input = [[18231, 0.0, 1], [22621, 1.0, 2], [15675, 0.0, 3], [23583, 1.0, 4]] data_input_df = pd.DataFrame( data_input, columns=["total_user", "total_even", "days"] ) """ data column = total user in a day, how much online event held in one day, what day is that(sunday-saturday) """ # start normalization normalize_df = Normalizer().fit_transform(data_input_df.values) # split data total_date = normalize_df[:, 2].tolist() total_user = normalize_df[:, 0].tolist() total_match = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) x = normalize_df[:, [1, 2]].tolist() x_train = x[: len(x) - 1] x_test = x[len(x) - 1 :] # for linear regression & sarimax trn_date = total_date[: len(total_date) - 1] trn_user = total_user[: len(total_user) - 1] trn_match = total_match[: len(total_match) - 1] tst_date = total_date[len(total_date) - 1 :] tst_user = total_user[len(total_user) - 1 :] tst_match = total_match[len(total_match) - 1 :] # voting system with forecasting res_vote = [ linear_regression_prediction( trn_date, trn_user, trn_match, tst_date, tst_match ), sarimax_predictor(trn_user, trn_match, tst_match), support_vector_regressor(x_train, x_test, trn_user), ] # check the safety of today's data not_str = "" if data_safety_checker(res_vote, tst_user) else "not " print("Today's data is {not_str}safe.")
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other 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,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other 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 """ import math from collections.abc import Iterator from itertools import takewhile 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. Returns boolean representing primality of given number num (i.e., if the result is true, then the number is indeed prime else it is not). >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True >>> is_prime(0) False >>> is_prime(1) 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 prime_generator() -> Iterator[int]: """ Generate a list sequence of prime numbers """ num = 2 while True: if is_prime(num): yield num num += 1 def solution(n: int = 2000000) -> int: """ Returns the sum of all the primes below n. >>> solution(1000) 76127 >>> solution(5000) 1548136 >>> solution(10000) 5736396 >>> solution(7) 10 """ return sum(takewhile(lambda x: x < n, prime_generator())) 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 """ import math from collections.abc import Iterator from itertools import takewhile 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. Returns boolean representing primality of given number num (i.e., if the result is true, then the number is indeed prime else it is not). >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True >>> is_prime(0) False >>> is_prime(1) 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 prime_generator() -> Iterator[int]: """ Generate a list sequence of prime numbers """ num = 2 while True: if is_prime(num): yield num num += 1 def solution(n: int = 2000000) -> int: """ Returns the sum of all the primes below n. >>> solution(1000) 76127 >>> solution(5000) 1548136 >>> solution(10000) 5736396 >>> solution(7) 10 """ return sum(takewhile(lambda x: x < n, prime_generator())) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import math def fx(x: float, a: float) -> float: return math.pow(x, 2) - a def fx_derivative(x: float) -> float: return 2 * x def get_initial_point(a: float) -> float: start = 2.0 while start <= a: start = math.pow(start, 2) return start def square_root_iterative( a: float, max_iter: int = 9999, tolerance: float = 0.00000000000001 ) -> float: """ Square root is aproximated using Newtons method. https://en.wikipedia.org/wiki/Newton%27s_method >>> all(abs(square_root_iterative(i)-math.sqrt(i)) <= .00000000000001 ... for i in range(500)) True >>> square_root_iterative(-1) Traceback (most recent call last): ... ValueError: math domain error >>> square_root_iterative(4) 2.0 >>> square_root_iterative(3.2) 1.788854381999832 >>> square_root_iterative(140) 11.832159566199232 """ if a < 0: raise ValueError("math domain error") value = get_initial_point(a) for _ in range(max_iter): prev_value = value value = value - fx(value, a) / fx_derivative(value) if abs(prev_value - value) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
import math def fx(x: float, a: float) -> float: return math.pow(x, 2) - a def fx_derivative(x: float) -> float: return 2 * x def get_initial_point(a: float) -> float: start = 2.0 while start <= a: start = math.pow(start, 2) return start def square_root_iterative( a: float, max_iter: int = 9999, tolerance: float = 0.00000000000001 ) -> float: """ Square root is aproximated using Newtons method. https://en.wikipedia.org/wiki/Newton%27s_method >>> all(abs(square_root_iterative(i)-math.sqrt(i)) <= .00000000000001 ... for i in range(500)) True >>> square_root_iterative(-1) Traceback (most recent call last): ... ValueError: math domain error >>> square_root_iterative(4) 2.0 >>> square_root_iterative(3.2) 1.788854381999832 >>> square_root_iterative(140) 11.832159566199232 """ if a < 0: raise ValueError("math domain error") value = get_initial_point(a) for _ in range(max_iter): prev_value = value value = value - fx(value, a) / fx_derivative(value) if abs(prev_value - value) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other 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/Component_(graph_theory) Finding connected components in graph """ test_graph_1 = {0: [1, 2], 1: [0, 3], 2: [0], 3: [1], 4: [5, 6], 5: [4, 6], 6: [4, 5]} test_graph_2 = {0: [1, 2, 3], 1: [0, 3], 2: [0], 3: [0, 1], 4: [], 5: []} def dfs(graph: dict, vert: int, visited: list) -> list: """ Use depth first search to find all vertices being in the same component as initial vertex >>> dfs(test_graph_1, 0, 5 * [False]) [0, 1, 3, 2] >>> dfs(test_graph_2, 0, 6 * [False]) [0, 1, 3, 2] """ visited[vert] = True connected_verts = [] for neighbour in graph[vert]: if not visited[neighbour]: connected_verts += dfs(graph, neighbour, visited) return [vert] + connected_verts def connected_components(graph: dict) -> list: """ This function takes graph as a parameter and then returns the list of connected components >>> connected_components(test_graph_1) [[0, 1, 3, 2], [4, 5, 6]] >>> connected_components(test_graph_2) [[0, 1, 3, 2], [4], [5]] """ graph_size = len(graph) visited = graph_size * [False] components_list = [] for i in range(graph_size): if not visited[i]: i_connected = dfs(graph, i, visited) components_list.append(i_connected) return components_list if __name__ == "__main__": import doctest doctest.testmod()
""" https://en.wikipedia.org/wiki/Component_(graph_theory) Finding connected components in graph """ test_graph_1 = {0: [1, 2], 1: [0, 3], 2: [0], 3: [1], 4: [5, 6], 5: [4, 6], 6: [4, 5]} test_graph_2 = {0: [1, 2, 3], 1: [0, 3], 2: [0], 3: [0, 1], 4: [], 5: []} def dfs(graph: dict, vert: int, visited: list) -> list: """ Use depth first search to find all vertices being in the same component as initial vertex >>> dfs(test_graph_1, 0, 5 * [False]) [0, 1, 3, 2] >>> dfs(test_graph_2, 0, 6 * [False]) [0, 1, 3, 2] """ visited[vert] = True connected_verts = [] for neighbour in graph[vert]: if not visited[neighbour]: connected_verts += dfs(graph, neighbour, visited) return [vert] + connected_verts def connected_components(graph: dict) -> list: """ This function takes graph as a parameter and then returns the list of connected components >>> connected_components(test_graph_1) [[0, 1, 3, 2], [4, 5, 6]] >>> connected_components(test_graph_2) [[0, 1, 3, 2], [4], [5]] """ graph_size = len(graph) visited = graph_size * [False] components_list = [] for i in range(graph_size): if not visited[i]: i_connected = dfs(graph, i, visited) components_list.append(i_connected) return components_list if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,737
Adopt Python >= 3.8 assignment expressions using auto-walrus
### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-10-27T14:00:42Z"
"2022-10-28T13:54:54Z"
15c93e5f4bc5b03cecc000506bdf45c100b8f0b3
19bff003aa1c365bec86d3f4a13a9c3d6c36d230
Adopt Python >= 3.8 assignment expressions using auto-walrus. ### Describe your change: Adopt Python >= 3.8 [assignment expressions](https://docs.python.org/3/whatsnew/3.8.html) using https://pypi.org/project/auto-walrus/ * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Fix continuous integration tests ### 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. * [x] 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 have a URL in its comments that points to Wikipedia or other similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 73: https://projecteuler.net/problem=73 Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that there are 3 fractions between 1/3 and 1/2. How many fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d ≤ 12,000? """ from math import gcd def solution(max_d: int = 12_000) -> int: """ Returns number of fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d ≤ max_d >>> solution(4) 0 >>> solution(5) 1 >>> solution(8) 3 """ fractions_number = 0 for d in range(max_d + 1): for n in range(d // 3 + 1, (d + 1) // 2): if gcd(n, d) == 1: fractions_number += 1 return fractions_number if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 73: https://projecteuler.net/problem=73 Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that there are 3 fractions between 1/3 and 1/2. How many fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d ≤ 12,000? """ from math import gcd def solution(max_d: int = 12_000) -> int: """ Returns number of fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d ≤ max_d >>> solution(4) 0 >>> solution(5) 1 >>> solution(8) 3 """ fractions_number = 0 for d in range(max_d + 1): for n in range(d // 3 + 1, (d + 1) // 2): if gcd(n, d) == 1: fractions_number += 1 return fractions_number if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Conversion of pressure units. Available Units:- Pascal,Bar,Kilopascal,Megapascal,psi(pound per square inch), inHg(in mercury column),torr,atm USAGE : -> Import this file into their respective project. -> Use the function pressure_conversion() for conversion of pressure units. -> Parameters : -> value : The number of from units you want to convert -> from_type : From which type you want to convert -> to_type : To which type you want to convert REFERENCES : -> Wikipedia reference: https://en.wikipedia.org/wiki/Pascal_(unit) -> Wikipedia reference: https://en.wikipedia.org/wiki/Pound_per_square_inch -> Wikipedia reference: https://en.wikipedia.org/wiki/Inch_of_mercury -> Wikipedia reference: https://en.wikipedia.org/wiki/Torr -> https://en.wikipedia.org/wiki/Standard_atmosphere_(unit) -> https://msestudent.com/what-are-the-units-of-pressure/ -> https://www.unitconverters.net/pressure-converter.html """ from collections import namedtuple from_to = namedtuple("from_to", "from_ to") PRESSURE_CONVERSION = { "atm": from_to(1, 1), "pascal": from_to(0.0000098, 101325), "bar": from_to(0.986923, 1.01325), "kilopascal": from_to(0.00986923, 101.325), "megapascal": from_to(9.86923, 0.101325), "psi": from_to(0.068046, 14.6959), "inHg": from_to(0.0334211, 29.9213), "torr": from_to(0.00131579, 760), } def pressure_conversion(value: float, from_type: str, to_type: str) -> float: """ Conversion between pressure units. >>> pressure_conversion(4, "atm", "pascal") 405300 >>> pressure_conversion(1, "pascal", "psi") 0.00014401981999999998 >>> pressure_conversion(1, "bar", "atm") 0.986923 >>> pressure_conversion(3, "kilopascal", "bar") 0.029999991892499998 >>> pressure_conversion(2, "megapascal", "psi") 290.074434314 >>> pressure_conversion(4, "psi", "torr") 206.85984 >>> pressure_conversion(1, "inHg", "atm") 0.0334211 >>> pressure_conversion(1, "torr", "psi") 0.019336718261000002 >>> pressure_conversion(4, "wrongUnit", "atm") Traceback (most recent call last): File "/usr/lib/python3.8/doctest.py", line 1336, in __run exec(compile(example.source, filename, "single", File "<doctest __main__.pressure_conversion[8]>", line 1, in <module> pressure_conversion(4, "wrongUnit", "atm") File "<string>", line 67, in pressure_conversion ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are: atm, pascal, bar, kilopascal, megapascal, psi, inHg, torr """ if from_type not in PRESSURE_CONVERSION: raise ValueError( f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + ", ".join(PRESSURE_CONVERSION) ) if to_type not in PRESSURE_CONVERSION: raise ValueError( f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + ", ".join(PRESSURE_CONVERSION) ) return ( value * PRESSURE_CONVERSION[from_type].from_ * PRESSURE_CONVERSION[to_type].to ) if __name__ == "__main__": import doctest doctest.testmod()
""" Conversion of pressure units. Available Units:- Pascal,Bar,Kilopascal,Megapascal,psi(pound per square inch), inHg(in mercury column),torr,atm USAGE : -> Import this file into their respective project. -> Use the function pressure_conversion() for conversion of pressure units. -> Parameters : -> value : The number of from units you want to convert -> from_type : From which type you want to convert -> to_type : To which type you want to convert REFERENCES : -> Wikipedia reference: https://en.wikipedia.org/wiki/Pascal_(unit) -> Wikipedia reference: https://en.wikipedia.org/wiki/Pound_per_square_inch -> Wikipedia reference: https://en.wikipedia.org/wiki/Inch_of_mercury -> Wikipedia reference: https://en.wikipedia.org/wiki/Torr -> https://en.wikipedia.org/wiki/Standard_atmosphere_(unit) -> https://msestudent.com/what-are-the-units-of-pressure/ -> https://www.unitconverters.net/pressure-converter.html """ from collections import namedtuple from_to = namedtuple("from_to", "from_ to") PRESSURE_CONVERSION = { "atm": from_to(1, 1), "pascal": from_to(0.0000098, 101325), "bar": from_to(0.986923, 1.01325), "kilopascal": from_to(0.00986923, 101.325), "megapascal": from_to(9.86923, 0.101325), "psi": from_to(0.068046, 14.6959), "inHg": from_to(0.0334211, 29.9213), "torr": from_to(0.00131579, 760), } def pressure_conversion(value: float, from_type: str, to_type: str) -> float: """ Conversion between pressure units. >>> pressure_conversion(4, "atm", "pascal") 405300 >>> pressure_conversion(1, "pascal", "psi") 0.00014401981999999998 >>> pressure_conversion(1, "bar", "atm") 0.986923 >>> pressure_conversion(3, "kilopascal", "bar") 0.029999991892499998 >>> pressure_conversion(2, "megapascal", "psi") 290.074434314 >>> pressure_conversion(4, "psi", "torr") 206.85984 >>> pressure_conversion(1, "inHg", "atm") 0.0334211 >>> pressure_conversion(1, "torr", "psi") 0.019336718261000002 >>> pressure_conversion(4, "wrongUnit", "atm") Traceback (most recent call last): ... ValueError: Invalid 'from_type' value: 'wrongUnit' Supported values are: atm, pascal, bar, kilopascal, megapascal, psi, inHg, torr """ if from_type not in PRESSURE_CONVERSION: raise ValueError( f"Invalid 'from_type' value: {from_type!r} Supported values are:\n" + ", ".join(PRESSURE_CONVERSION) ) if to_type not in PRESSURE_CONVERSION: raise ValueError( f"Invalid 'to_type' value: {to_type!r}. Supported values are:\n" + ", ".join(PRESSURE_CONVERSION) ) return ( value * PRESSURE_CONVERSION[from_type].from_ * PRESSURE_CONVERSION[to_type].to ) if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# https://en.wikipedia.org/wiki/Charge_carrier_density # https://www.pveducation.org/pvcdrom/pn-junctions/equilibrium-carrier-concentration # http://www.ece.utep.edu/courses/ee3329/ee3329/Studyguide/ToC/Fundamentals/Carriers/concentrations.html from __future__ import annotations def carrier_concentration( electron_conc: float, hole_conc: float, intrinsic_conc: float, ) -> tuple: """ This function can calculate any one of the three - 1. Electron Concentration 2, Hole Concentration 3. Intrinsic Concentration given the other two. Examples - >>> carrier_concentration(electron_conc=25, hole_conc=100, intrinsic_conc=0) ('intrinsic_conc', 50.0) >>> carrier_concentration(electron_conc=0, hole_conc=1600, intrinsic_conc=200) ('electron_conc', 25.0) >>> carrier_concentration(electron_conc=1000, hole_conc=0, intrinsic_conc=1200) ('hole_conc', 1440.0) >>> carrier_concentration(electron_conc=1000, hole_conc=400, intrinsic_conc=1200) Traceback (most recent call last): File "<stdin>", line 37, in <module> ValueError: You cannot supply more or less than 2 values >>> carrier_concentration(electron_conc=-1000, hole_conc=0, intrinsic_conc=1200) Traceback (most recent call last): File "<stdin>", line 40, in <module> ValueError: Electron concentration cannot be negative in a semiconductor >>> carrier_concentration(electron_conc=0, hole_conc=-400, intrinsic_conc=1200) Traceback (most recent call last): File "<stdin>", line 44, in <module> ValueError: Hole concentration cannot be negative in a semiconductor >>> carrier_concentration(electron_conc=0, hole_conc=400, intrinsic_conc=-1200) Traceback (most recent call last): File "<stdin>", line 48, in <module> ValueError: Intrinsic concentration cannot be negative in a semiconductor """ if (electron_conc, hole_conc, intrinsic_conc).count(0) != 1: raise ValueError("You cannot supply more or less than 2 values") elif electron_conc < 0: raise ValueError("Electron concentration cannot be negative in a semiconductor") elif hole_conc < 0: raise ValueError("Hole concentration cannot be negative in a semiconductor") elif intrinsic_conc < 0: raise ValueError( "Intrinsic concentration cannot be negative in a semiconductor" ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
# https://en.wikipedia.org/wiki/Charge_carrier_density # https://www.pveducation.org/pvcdrom/pn-junctions/equilibrium-carrier-concentration # http://www.ece.utep.edu/courses/ee3329/ee3329/Studyguide/ToC/Fundamentals/Carriers/concentrations.html from __future__ import annotations def carrier_concentration( electron_conc: float, hole_conc: float, intrinsic_conc: float, ) -> tuple: """ This function can calculate any one of the three - 1. Electron Concentration 2, Hole Concentration 3. Intrinsic Concentration given the other two. Examples - >>> carrier_concentration(electron_conc=25, hole_conc=100, intrinsic_conc=0) ('intrinsic_conc', 50.0) >>> carrier_concentration(electron_conc=0, hole_conc=1600, intrinsic_conc=200) ('electron_conc', 25.0) >>> carrier_concentration(electron_conc=1000, hole_conc=0, intrinsic_conc=1200) ('hole_conc', 1440.0) >>> carrier_concentration(electron_conc=1000, hole_conc=400, intrinsic_conc=1200) Traceback (most recent call last): ... ValueError: You cannot supply more or less than 2 values >>> carrier_concentration(electron_conc=-1000, hole_conc=0, intrinsic_conc=1200) Traceback (most recent call last): ... ValueError: Electron concentration cannot be negative in a semiconductor >>> carrier_concentration(electron_conc=0, hole_conc=-400, intrinsic_conc=1200) Traceback (most recent call last): ... ValueError: Hole concentration cannot be negative in a semiconductor >>> carrier_concentration(electron_conc=0, hole_conc=400, intrinsic_conc=-1200) Traceback (most recent call last): ... ValueError: Intrinsic concentration cannot be negative in a semiconductor """ if (electron_conc, hole_conc, intrinsic_conc).count(0) != 1: raise ValueError("You cannot supply more or less than 2 values") elif electron_conc < 0: raise ValueError("Electron concentration cannot be negative in a semiconductor") elif hole_conc < 0: raise ValueError("Hole concentration cannot be negative in a semiconductor") elif intrinsic_conc < 0: raise ValueError( "Intrinsic concentration cannot be negative in a semiconductor" ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# https://en.m.wikipedia.org/wiki/Electric_power from __future__ import annotations from collections import namedtuple def electric_power(voltage: float, current: float, power: float) -> tuple: """ This function can calculate any one of the three (voltage, current, power), fundamental value of electrical system. examples are below: >>> electric_power(voltage=0, current=2, power=5) result(name='voltage', value=2.5) >>> electric_power(voltage=2, current=2, power=0) result(name='power', value=4.0) >>> electric_power(voltage=-2, current=3, power=0) result(name='power', value=6.0) >>> electric_power(voltage=2, current=4, power=2) Traceback (most recent call last): File "<stdin>", line 15, in <module> ValueError: Only one argument must be 0 >>> electric_power(voltage=0, current=0, power=2) Traceback (most recent call last): File "<stdin>", line 19, in <module> ValueError: Only one argument must be 0 >>> electric_power(voltage=0, current=2, power=-4) Traceback (most recent call last): File "<stdin>", line 23, in <modulei ValueError: Power cannot be negative in any electrical/electronics system >>> electric_power(voltage=2.2, current=2.2, power=0) result(name='power', value=4.84) """ result = namedtuple("result", "name value") if (voltage, current, power).count(0) != 1: raise ValueError("Only one argument must be 0") elif power < 0: raise ValueError( "Power cannot be negative in any electrical/electronics system" ) elif voltage == 0: return result("voltage", power / current) elif current == 0: return result("current", power / voltage) elif power == 0: return result("power", float(round(abs(voltage * current), 2))) else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
# https://en.m.wikipedia.org/wiki/Electric_power from __future__ import annotations from collections import namedtuple def electric_power(voltage: float, current: float, power: float) -> tuple: """ This function can calculate any one of the three (voltage, current, power), fundamental value of electrical system. examples are below: >>> electric_power(voltage=0, current=2, power=5) result(name='voltage', value=2.5) >>> electric_power(voltage=2, current=2, power=0) result(name='power', value=4.0) >>> electric_power(voltage=-2, current=3, power=0) result(name='power', value=6.0) >>> electric_power(voltage=2, current=4, power=2) Traceback (most recent call last): ... ValueError: Only one argument must be 0 >>> electric_power(voltage=0, current=0, power=2) Traceback (most recent call last): ... ValueError: Only one argument must be 0 >>> electric_power(voltage=0, current=2, power=-4) Traceback (most recent call last): ... ValueError: Power cannot be negative in any electrical/electronics system >>> electric_power(voltage=2.2, current=2.2, power=0) result(name='power', value=4.84) """ result = namedtuple("result", "name value") if (voltage, current, power).count(0) != 1: raise ValueError("Only one argument must be 0") elif power < 0: raise ValueError( "Power cannot be negative in any electrical/electronics system" ) elif voltage == 0: return result("voltage", power / current) elif current == 0: return result("current", power / voltage) elif power == 0: return result("power", float(round(abs(voltage * current), 2))) else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Python program to show how to interpolate and evaluate a polynomial using Neville's method. Neville’s method evaluates a polynomial that passes through a given set of x and y points for a particular x value (x0) using the Newton polynomial form. Reference: https://rpubs.com/aaronsc32/nevilles-method-polynomial-interpolation """ def neville_interpolate(x_points: list, y_points: list, x0: int) -> list: """ Interpolate and evaluate a polynomial using Neville's method. Arguments: x_points, y_points: Iterables of x and corresponding y points through which the polynomial passes. x0: The value of x to evaluate the polynomial for. Return Value: A list of the approximated value and the Neville iterations table respectively. >>> import pprint >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 5)[0] 10.0 >>> pprint.pprint(neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 99)[1]) [[0, 6, 0, 0, 0], [0, 7, 0, 0, 0], [0, 8, 104.0, 0, 0], [0, 9, 104.0, 104.0, 0], [0, 11, 104.0, 104.0, 104.0]] >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 99)[0] 104.0 >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), '') Traceback (most recent call last): File "<stdin>", line 1, in <module> ... TypeError: unsupported operand type(s) for -: 'str' and 'int' """ n = len(x_points) q = [[0] * n for i in range(n)] for i in range(n): q[i][1] = y_points[i] for i in range(2, n): for j in range(i, n): q[j][i] = ( (x0 - x_points[j - i + 1]) * q[j][i - 1] - (x0 - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
""" Python program to show how to interpolate and evaluate a polynomial using Neville's method. Neville’s method evaluates a polynomial that passes through a given set of x and y points for a particular x value (x0) using the Newton polynomial form. Reference: https://rpubs.com/aaronsc32/nevilles-method-polynomial-interpolation """ def neville_interpolate(x_points: list, y_points: list, x0: int) -> list: """ Interpolate and evaluate a polynomial using Neville's method. Arguments: x_points, y_points: Iterables of x and corresponding y points through which the polynomial passes. x0: The value of x to evaluate the polynomial for. Return Value: A list of the approximated value and the Neville iterations table respectively. >>> import pprint >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 5)[0] 10.0 >>> pprint.pprint(neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 99)[1]) [[0, 6, 0, 0, 0], [0, 7, 0, 0, 0], [0, 8, 104.0, 0, 0], [0, 9, 104.0, 104.0, 0], [0, 11, 104.0, 104.0, 104.0]] >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), 99)[0] 104.0 >>> neville_interpolate((1,2,3,4,6), (6,7,8,9,11), '') Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'str' and 'int' """ n = len(x_points) q = [[0] * n for i in range(n)] for i in range(n): q[i][1] = y_points[i] for i in range(2, n): for j in range(i, n): q[j][i] = ( (x0 - x_points[j - i + 1]) * q[j][i - 1] - (x0 - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def excel_title_to_column(column_title: str) -> int: """ Given a string column_title that represents the column title in an Excel sheet, return its corresponding column number. >>> excel_title_to_column("A") 1 >>> excel_title_to_column("B") 2 >>> excel_title_to_column("AB") 28 >>> excel_title_to_column("Z") 26 """ assert column_title.isupper() answer = 0 index = len(column_title) - 1 power = 0 while index >= 0: value = (ord(column_title[index]) - 64) * pow(26, power) answer += value power += 1 index -= 1 return answer if __name__ == "__main__": from doctest import testmod testmod()
def excel_title_to_column(column_title: str) -> int: """ Given a string column_title that represents the column title in an Excel sheet, return its corresponding column number. >>> excel_title_to_column("A") 1 >>> excel_title_to_column("B") 2 >>> excel_title_to_column("AB") 28 >>> excel_title_to_column("Z") 26 """ assert column_title.isupper() answer = 0 index = len(column_title) - 1 power = 0 while index >= 0: value = (ord(column_title[index]) - 64) * pow(26, power) answer += value power += 1 index -= 1 return answer if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] 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 1: "extended trapezoidal rule" """ def method_1(boundary, steps): # "extended trapezoidal rule" # int(f) = dx/2 * (f1 + 2f2 + ... + 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 / 2.0) * f(a) for i in x_i: # print(i) y += h * f(i) y += (h / 2.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_1(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 1: "extended trapezoidal rule" """ def method_1(boundary, steps): # "extended trapezoidal rule" # int(f) = dx/2 * (f1 + 2f2 + ... + 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 / 2.0) * f(a) for i in x_i: # print(i) y += h * f(i) y += (h / 2.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_1(boundary, steps) print(f"y = {y}") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 """ Build a half-adder quantum circuit that takes two bits as input, encodes them into qubits, then runs the half-adder circuit calculating the sum and carry qubits, observed over 1000 runs of the experiment . References: https://en.wikipedia.org/wiki/Adder_(electronics) https://qiskit.org/textbook/ch-states/atoms-computation.html#4.2-Remembering-how-to-add- """ import qiskit def half_adder(bit0: int, bit1: int) -> qiskit.result.counts.Counts: """ >>> half_adder(0, 0) {'00': 1000} >>> half_adder(0, 1) {'01': 1000} >>> half_adder(1, 0) {'01': 1000} >>> half_adder(1, 1) {'10': 1000} """ # Use Aer's simulator simulator = qiskit.Aer.get_backend("aer_simulator") qc_ha = qiskit.QuantumCircuit(4, 2) # encode inputs in qubits 0 and 1 if bit0 == 1: qc_ha.x(0) if bit1 == 1: qc_ha.x(1) qc_ha.barrier() # use cnots to write XOR of the inputs on qubit2 qc_ha.cx(0, 2) qc_ha.cx(1, 2) # use ccx / toffoli gate to write AND of the inputs on qubit3 qc_ha.ccx(0, 1, 3) qc_ha.barrier() # extract outputs qc_ha.measure(2, 0) # extract XOR value qc_ha.measure(3, 1) # extract AND value # Execute the circuit on the qasm simulator job = qiskit.execute(qc_ha, simulator, shots=1000) # Return the histogram data of the results of the experiment return job.result().get_counts(qc_ha) if __name__ == "__main__": counts = half_adder(1, 1) print(f"Half Adder Output Qubit Counts: {counts}")
#!/usr/bin/env python3 """ Build a half-adder quantum circuit that takes two bits as input, encodes them into qubits, then runs the half-adder circuit calculating the sum and carry qubits, observed over 1000 runs of the experiment . References: https://en.wikipedia.org/wiki/Adder_(electronics) https://qiskit.org/textbook/ch-states/atoms-computation.html#4.2-Remembering-how-to-add- """ import qiskit def half_adder(bit0: int, bit1: int) -> qiskit.result.counts.Counts: """ >>> half_adder(0, 0) {'00': 1000} >>> half_adder(0, 1) {'01': 1000} >>> half_adder(1, 0) {'01': 1000} >>> half_adder(1, 1) {'10': 1000} """ # Use Aer's simulator simulator = qiskit.Aer.get_backend("aer_simulator") qc_ha = qiskit.QuantumCircuit(4, 2) # encode inputs in qubits 0 and 1 if bit0 == 1: qc_ha.x(0) if bit1 == 1: qc_ha.x(1) qc_ha.barrier() # use cnots to write XOR of the inputs on qubit2 qc_ha.cx(0, 2) qc_ha.cx(1, 2) # use ccx / toffoli gate to write AND of the inputs on qubit3 qc_ha.ccx(0, 1, 3) qc_ha.barrier() # extract outputs qc_ha.measure(2, 0) # extract XOR value qc_ha.measure(3, 1) # extract AND value # Execute the circuit on the qasm simulator job = qiskit.execute(qc_ha, simulator, shots=1000) # Return the histogram data of the results of the experiment return job.result().get_counts(qc_ha) if __name__ == "__main__": counts = half_adder(1, 1) print(f"Half Adder Output Qubit Counts: {counts}")
-1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import math """ In cryptography, the TRANSPOSITION cipher is a method of encryption where the positions of plaintext are shifted a certain number(determined by the key) that follows a regular system that results in the permuted text, known as the encrypted text. The type of transposition cipher demonstrated under is the ROUTE cipher. """ def main() -> None: message = input("Enter message: ") key = int(input(f"Enter key [2-{len(message) - 1}]: ")) mode = input("Encryption/Decryption [e/d]: ") if mode.lower().startswith("e"): text = encrypt_message(key, message) elif mode.lower().startswith("d"): text = decrypt_message(key, message) # Append pipe symbol (vertical bar) to identify spaces at the end. print(f"Output:\n{text + '|'}") def encrypt_message(key: int, message: str) -> str: """ >>> encrypt_message(6, 'Harshil Darji') 'Hlia rDsahrij' """ cipher_text = [""] * key for col in range(key): pointer = col while pointer < len(message): cipher_text[col] += message[pointer] pointer += key return "".join(cipher_text) def decrypt_message(key: int, message: str) -> str: """ >>> decrypt_message(6, 'Hlia rDsahrij') 'Harshil Darji' """ num_cols = math.ceil(len(message) / key) num_rows = key num_shaded_boxes = (num_cols * num_rows) - len(message) plain_text = [""] * num_cols col = 0 row = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): col = 0 row += 1 return "".join(plain_text) if __name__ == "__main__": import doctest doctest.testmod() main()
import math """ In cryptography, the TRANSPOSITION cipher is a method of encryption where the positions of plaintext are shifted a certain number(determined by the key) that follows a regular system that results in the permuted text, known as the encrypted text. The type of transposition cipher demonstrated under is the ROUTE cipher. """ def main() -> None: message = input("Enter message: ") key = int(input(f"Enter key [2-{len(message) - 1}]: ")) mode = input("Encryption/Decryption [e/d]: ") if mode.lower().startswith("e"): text = encrypt_message(key, message) elif mode.lower().startswith("d"): text = decrypt_message(key, message) # Append pipe symbol (vertical bar) to identify spaces at the end. print(f"Output:\n{text + '|'}") def encrypt_message(key: int, message: str) -> str: """ >>> encrypt_message(6, 'Harshil Darji') 'Hlia rDsahrij' """ cipher_text = [""] * key for col in range(key): pointer = col while pointer < len(message): cipher_text[col] += message[pointer] pointer += key return "".join(cipher_text) def decrypt_message(key: int, message: str) -> str: """ >>> decrypt_message(6, 'Hlia rDsahrij') 'Harshil Darji' """ num_cols = math.ceil(len(message) / key) num_rows = key num_shaded_boxes = (num_cols * num_rows) - len(message) plain_text = [""] * num_cols col = 0 row = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): col = 0 row += 1 return "".join(plain_text) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/usr/bin/env python3 """ Created by sarathkaul on 14/11/19 Updated by lawric1 on 24/11/20 Authentication will be made via access token. To generate your personal access token visit https://github.com/settings/tokens. NOTE: Never hardcode any credential information in the code. Always use an environment file to store the private information and use the `os` module to get the information during runtime. Create a ".env" file in the root directory and write these two lines in that file with your token:: #!/usr/bin/env bash export USER_TOKEN="" """ from __future__ import annotations import os from typing import Any import requests BASE_URL = "https://api.github.com" # https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user AUTHENTICATED_USER_ENDPOINT = BASE_URL + "/user" # https://github.com/settings/tokens USER_TOKEN = os.environ.get("USER_TOKEN", "") def fetch_github_info(auth_token: str) -> dict[Any, Any]: """ Fetch GitHub info of a user using the requests module """ headers = { "Authorization": f"token {auth_token}", "Accept": "application/vnd.github.v3+json", } return requests.get(AUTHENTICATED_USER_ENDPOINT, headers=headers).json() if __name__ == "__main__": # pragma: no cover if USER_TOKEN: for key, value in fetch_github_info(USER_TOKEN).items(): print(f"{key}: {value}") else: raise ValueError("'USER_TOKEN' field cannot be empty.")
#!/usr/bin/env python3 """ Created by sarathkaul on 14/11/19 Updated by lawric1 on 24/11/20 Authentication will be made via access token. To generate your personal access token visit https://github.com/settings/tokens. NOTE: Never hardcode any credential information in the code. Always use an environment file to store the private information and use the `os` module to get the information during runtime. Create a ".env" file in the root directory and write these two lines in that file with your token:: #!/usr/bin/env bash export USER_TOKEN="" """ from __future__ import annotations import os from typing import Any import requests BASE_URL = "https://api.github.com" # https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user AUTHENTICATED_USER_ENDPOINT = BASE_URL + "/user" # https://github.com/settings/tokens USER_TOKEN = os.environ.get("USER_TOKEN", "") def fetch_github_info(auth_token: str) -> dict[Any, Any]: """ Fetch GitHub info of a user using the requests module """ headers = { "Authorization": f"token {auth_token}", "Accept": "application/vnd.github.v3+json", } return requests.get(AUTHENTICATED_USER_ENDPOINT, headers=headers).json() if __name__ == "__main__": # pragma: no cover if USER_TOKEN: for key, value in fetch_github_info(USER_TOKEN).items(): print(f"{key}: {value}") else: raise ValueError("'USER_TOKEN' field cannot be empty.")
-1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" The A* algorithm combines features of uniform-cost search and pure heuristic search to efficiently compute optimal solutions. The A* algorithm is a best-first search algorithm in which the cost associated with a node is f(n) = g(n) + h(n), where g(n) is the cost of the path from the initial state to node n and h(n) is the heuristic estimate or the cost or a path from node n to a goal. The A* algorithm introduces a heuristic into a regular graph-searching algorithm, essentially planning ahead at each step so a more optimal decision is made. For this reason, A* is known as an algorithm with brains. https://en.wikipedia.org/wiki/A*_search_algorithm """ import numpy as np class Cell: """ Class cell represents a cell in the world which have the properties: position: represented by tuple of x and y coordinates initially set to (0,0). parent: Contains the parent cell object visited before we arrived at this cell. g, h, f: Parameters used when calling our heuristic function. """ def __init__(self): self.position = (0, 0) self.parent = None self.g = 0 self.h = 0 self.f = 0 """ Overrides equals method because otherwise cell assign will give wrong results. """ def __eq__(self, cell): return self.position == cell.position def showcell(self): print(self.position) class Gridworld: """ Gridworld class represents the external world here a grid M*M matrix. world_size: create a numpy array with the given world_size default is 5. """ def __init__(self, world_size=(5, 5)): self.w = np.zeros(world_size) self.world_x_limit = world_size[0] self.world_y_limit = world_size[1] def show(self): print(self.w) def get_neigbours(self, cell): """ Return the neighbours of cell """ neughbour_cord = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] current_x = cell.position[0] current_y = cell.position[1] neighbours = [] for n in neughbour_cord: x = current_x + n[0] y = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: c = Cell() c.position = (x, y) c.parent = cell neighbours.append(c) return neighbours def astar(world, start, goal): """ Implementation of a start algorithm. world : Object of the world object. start : Object of the cell as start position. stop : Object of the cell as goal position. >>> p = Gridworld() >>> start = Cell() >>> start.position = (0,0) >>> goal = Cell() >>> goal.position = (4,4) >>> astar(p, start, goal) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] """ _open = [] _closed = [] _open.append(start) while _open: min_f = np.argmin([n.f for n in _open]) current = _open[min_f] _closed.append(_open.pop(min_f)) if current == goal: break for n in world.get_neigbours(current): for c in _closed: if c == n: continue n.g = current.g + 1 x1, y1 = n.position x2, y2 = goal.position n.h = (y2 - y1) ** 2 + (x2 - x1) ** 2 n.f = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(n) path = [] while current.parent is not None: path.append(current.position) current = current.parent path.append(current.position) return path[::-1] if __name__ == "__main__": world = Gridworld() # Start position and goal start = Cell() start.position = (0, 0) goal = Cell() goal.position = (4, 4) print(f"path from {start.position} to {goal.position}") s = astar(world, start, goal) # Just for visual reasons. for i in s: world.w[i] = 1 print(world.w)
""" The A* algorithm combines features of uniform-cost search and pure heuristic search to efficiently compute optimal solutions. The A* algorithm is a best-first search algorithm in which the cost associated with a node is f(n) = g(n) + h(n), where g(n) is the cost of the path from the initial state to node n and h(n) is the heuristic estimate or the cost or a path from node n to a goal. The A* algorithm introduces a heuristic into a regular graph-searching algorithm, essentially planning ahead at each step so a more optimal decision is made. For this reason, A* is known as an algorithm with brains. https://en.wikipedia.org/wiki/A*_search_algorithm """ import numpy as np class Cell: """ Class cell represents a cell in the world which have the properties: position: represented by tuple of x and y coordinates initially set to (0,0). parent: Contains the parent cell object visited before we arrived at this cell. g, h, f: Parameters used when calling our heuristic function. """ def __init__(self): self.position = (0, 0) self.parent = None self.g = 0 self.h = 0 self.f = 0 """ Overrides equals method because otherwise cell assign will give wrong results. """ def __eq__(self, cell): return self.position == cell.position def showcell(self): print(self.position) class Gridworld: """ Gridworld class represents the external world here a grid M*M matrix. world_size: create a numpy array with the given world_size default is 5. """ def __init__(self, world_size=(5, 5)): self.w = np.zeros(world_size) self.world_x_limit = world_size[0] self.world_y_limit = world_size[1] def show(self): print(self.w) def get_neigbours(self, cell): """ Return the neighbours of cell """ neughbour_cord = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] current_x = cell.position[0] current_y = cell.position[1] neighbours = [] for n in neughbour_cord: x = current_x + n[0] y = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: c = Cell() c.position = (x, y) c.parent = cell neighbours.append(c) return neighbours def astar(world, start, goal): """ Implementation of a start algorithm. world : Object of the world object. start : Object of the cell as start position. stop : Object of the cell as goal position. >>> p = Gridworld() >>> start = Cell() >>> start.position = (0,0) >>> goal = Cell() >>> goal.position = (4,4) >>> astar(p, start, goal) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] """ _open = [] _closed = [] _open.append(start) while _open: min_f = np.argmin([n.f for n in _open]) current = _open[min_f] _closed.append(_open.pop(min_f)) if current == goal: break for n in world.get_neigbours(current): for c in _closed: if c == n: continue n.g = current.g + 1 x1, y1 = n.position x2, y2 = goal.position n.h = (y2 - y1) ** 2 + (x2 - x1) ** 2 n.f = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(n) path = [] while current.parent is not None: path.append(current.position) current = current.parent path.append(current.position) return path[::-1] if __name__ == "__main__": world = Gridworld() # Start position and goal start = Cell() start.position = (0, 0) goal = Cell() goal.position = (4, 4) print(f"path from {start.position} to {goal.position}") s = astar(world, start, goal) # Just for visual reasons. for i in s: world.w[i] = 1 print(world.w)
-1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from pathlib import Path import cv2 import numpy as np from matplotlib import pyplot as plt def get_rotation( img: np.ndarray, pt1: np.ndarray, pt2: np.ndarray, rows: int, cols: int ) -> np.ndarray: """ Get image rotation :param img: np.array :param pt1: 3x2 list :param pt2: 3x2 list :param rows: columns image shape :param cols: rows image shape :return: np.array """ matrix = cv2.getAffineTransform(pt1, pt2) return cv2.warpAffine(img, matrix, (rows, cols)) if __name__ == "__main__": # read original image image = cv2.imread( str(Path(__file__).resolve().parent.parent / "image_data" / "lena.jpg") ) # turn image in gray scale value gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # get image shape img_rows, img_cols = gray_img.shape # set different points to rotate image pts1 = np.array([[50, 50], [200, 50], [50, 200]], np.float32) pts2 = np.array([[10, 100], [200, 50], [100, 250]], np.float32) pts3 = np.array([[50, 50], [150, 50], [120, 200]], np.float32) pts4 = np.array([[10, 100], [80, 50], [180, 250]], np.float32) # add all rotated images in a list images = [ gray_img, get_rotation(gray_img, pts1, pts2, img_rows, img_cols), get_rotation(gray_img, pts2, pts3, img_rows, img_cols), get_rotation(gray_img, pts2, pts4, img_rows, img_cols), ] # plot different image rotations fig = plt.figure(1) titles = ["Original", "Rotation 1", "Rotation 2", "Rotation 3"] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, "gray") plt.title(titles[i]) plt.axis("off") plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
from pathlib import Path import cv2 import numpy as np from matplotlib import pyplot as plt def get_rotation( img: np.ndarray, pt1: np.ndarray, pt2: np.ndarray, rows: int, cols: int ) -> np.ndarray: """ Get image rotation :param img: np.array :param pt1: 3x2 list :param pt2: 3x2 list :param rows: columns image shape :param cols: rows image shape :return: np.array """ matrix = cv2.getAffineTransform(pt1, pt2) return cv2.warpAffine(img, matrix, (rows, cols)) if __name__ == "__main__": # read original image image = cv2.imread( str(Path(__file__).resolve().parent.parent / "image_data" / "lena.jpg") ) # turn image in gray scale value gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # get image shape img_rows, img_cols = gray_img.shape # set different points to rotate image pts1 = np.array([[50, 50], [200, 50], [50, 200]], np.float32) pts2 = np.array([[10, 100], [200, 50], [100, 250]], np.float32) pts3 = np.array([[50, 50], [150, 50], [120, 200]], np.float32) pts4 = np.array([[10, 100], [80, 50], [180, 250]], np.float32) # add all rotated images in a list images = [ gray_img, get_rotation(gray_img, pts1, pts2, img_rows, img_cols), get_rotation(gray_img, pts2, pts3, img_rows, img_cols), get_rotation(gray_img, pts2, pts4, img_rows, img_cols), ] # plot different image rotations fig = plt.figure(1) titles = ["Original", "Rotation 1", "Rotation 2", "Rotation 3"] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, "gray") plt.title(titles[i]) plt.axis("off") plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
-1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
"""A merge sort which accepts an array as input and recursively splits an array in half and sorts and combines them. """ """https://en.wikipedia.org/wiki/Merge_sort """ def merge(arr: list[int]) -> list[int]: """Return a sorted array. >>> merge([10,9,8,7,6,5,4,3,2,1]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> merge([1,2,3,4,5,6,7,8,9,10]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> merge([10,22,1,2,3,9,15,23]) [1, 2, 3, 9, 10, 15, 22, 23] >>> merge([100]) [100] >>> merge([]) [] """ if len(arr) > 1: middle_length = len(arr) // 2 # Finds the middle of the array left_array = arr[ :middle_length ] # Creates an array of the elements in the first half. right_array = arr[ middle_length: ] # Creates an array of the elements in the second half. left_size = len(left_array) right_size = len(right_array) merge(left_array) # Starts sorting the left. merge(right_array) # Starts sorting the right left_index = 0 # Left Counter right_index = 0 # Right Counter index = 0 # Position Counter while ( left_index < left_size and right_index < right_size ): # Runs until the lowers size of the left and right are sorted. if left_array[left_index] < right_array[right_index]: arr[index] = left_array[left_index] left_index += 1 else: arr[index] = right_array[right_index] right_index += 1 index += 1 while ( left_index < left_size ): # Adds the left over elements in the left half of the array arr[index] = left_array[left_index] left_index += 1 index += 1 while ( right_index < right_size ): # Adds the left over elements in the right half of the array arr[index] = right_array[right_index] right_index += 1 index += 1 return arr if __name__ == "__main__": import doctest doctest.testmod()
"""A merge sort which accepts an array as input and recursively splits an array in half and sorts and combines them. """ """https://en.wikipedia.org/wiki/Merge_sort """ def merge(arr: list[int]) -> list[int]: """Return a sorted array. >>> merge([10,9,8,7,6,5,4,3,2,1]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> merge([1,2,3,4,5,6,7,8,9,10]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> merge([10,22,1,2,3,9,15,23]) [1, 2, 3, 9, 10, 15, 22, 23] >>> merge([100]) [100] >>> merge([]) [] """ if len(arr) > 1: middle_length = len(arr) // 2 # Finds the middle of the array left_array = arr[ :middle_length ] # Creates an array of the elements in the first half. right_array = arr[ middle_length: ] # Creates an array of the elements in the second half. left_size = len(left_array) right_size = len(right_array) merge(left_array) # Starts sorting the left. merge(right_array) # Starts sorting the right left_index = 0 # Left Counter right_index = 0 # Right Counter index = 0 # Position Counter while ( left_index < left_size and right_index < right_size ): # Runs until the lowers size of the left and right are sorted. if left_array[left_index] < right_array[right_index]: arr[index] = left_array[left_index] left_index += 1 else: arr[index] = right_array[right_index] right_index += 1 index += 1 while ( left_index < left_size ): # Adds the left over elements in the left half of the array arr[index] = left_array[left_index] left_index += 1 index += 1 while ( right_index < right_size ): # Adds the left over elements in the right half of the array arr[index] = right_array[right_index] right_index += 1 index += 1 return arr if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def upper(word: str) -> str: """ Will convert the entire string to uppercase letters >>> upper("wow") 'WOW' >>> upper("Hello") 'HELLO' >>> upper("WHAT") 'WHAT' >>> upper("wh[]32") 'WH[]32' """ # Converting to ascii value int value and checking to see if char is a lower letter # if it is a lowercase letter it is getting shift by 32 which makes it an uppercase # case letter return "".join(chr(ord(char) - 32) if "a" <= char <= "z" else char for char in word) if __name__ == "__main__": from doctest import testmod testmod()
def upper(word: str) -> str: """ Will convert the entire string to uppercase letters >>> upper("wow") 'WOW' >>> upper("Hello") 'HELLO' >>> upper("WHAT") 'WHAT' >>> upper("wh[]32") 'WH[]32' """ # Converting to ascii value int value and checking to see if char is a lower letter # if it is a lowercase letter it is getting shift by 32 which makes it an uppercase # case letter return "".join(chr(ord(char) - 32) if "a" <= char <= "z" else char for char in word) if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Permuted multiples Problem 52 It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. """ def solution(): """Returns the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. >>> solution() 142857 """ i = 1 while True: if ( sorted(str(i)) == sorted(str(2 * i)) == sorted(str(3 * i)) == sorted(str(4 * i)) == sorted(str(5 * i)) == sorted(str(6 * i)) ): return i i += 1 if __name__ == "__main__": print(solution())
""" Permuted multiples Problem 52 It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. """ def solution(): """Returns the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. >>> solution() 142857 """ i = 1 while True: if ( sorted(str(i)) == sorted(str(2 * i)) == sorted(str(3 * i)) == sorted(str(4 * i)) == sorted(str(5 * i)) == sorted(str(6 * i)) ): return i i += 1 if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
7,558
Fix doctest tracebacks
### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
CaedenPH
"2022-10-23T13:52:37Z"
"2022-10-23T14:36:11Z"
0f06a0b5ff43c4cfa98db33926d21ce688b69a10
393b9605259fe19e03bdaac2b0866151e1a2afc2
Fix doctest tracebacks. ### Describe your change: Replace `File "/usr/bin..."` with `...` * [ ] 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. * [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [x] All new Python files are placed inside an existing directory. * [x] All filenames are in all lowercase characters with no spaces or dashes. * [x] All functions and variable names follow Python naming conventions. * [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ if n <= 1: return 0 a = 0 b = 2 count = 0 while 4 * b + a <= n: a, b = b, 4 * b + a count += a return count + b if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ if n <= 1: return 0 a = 0 b = 2 count = 0 while 4 * b + a <= n: a, b = b, 4 * b + a count += a return count + b if __name__ == "__main__": print(f"{solution() = }")
-1