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
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MIT License Copyright (c) 2016-2022 TheAlgorithms and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
MIT License Copyright (c) 2016-2022 TheAlgorithms and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Binary Tree Traversal ## Overview The combination of binary trees being data structures and traversal being an algorithm relates to classic problems, either directly or indirectly. > If you can grasp the traversal of binary trees, the traversal of other complicated trees will be easy for you. The following are some common ways to traverse trees. - Depth First Traversals (DFS): In-order, Pre-order, Post-order - Level Order Traversal or Breadth First or Traversal (BFS) There are applications for both DFS and BFS. Stack can be used to simplify the process of DFS traversal. Besides, since tree is a recursive data structure, recursion and stack are two key points for DFS. Graph for DFS: ![binary-tree-traversal-dfs](https://tva1.sinaimg.cn/large/007S8ZIlly1ghluhzhynsg30dw0dw3yl.gif) The key point of BFS is how to determine whether the traversal of each level has been completed. The answer is to use a variable as a flag to represent the end of the traversal of current level. ## Pre-order Traversal The traversal order of pre-order traversal is `root-left-right`. Algorithm Pre-order 1. Visit the root node and push it into a stack. 2. Pop a node from the stack, and push its right and left child node into the stack respectively. 3. Repeat step 2. Conclusion: This problem involves the classic recursive data structure (i.e. a binary tree), and the algorithm above demonstrates how a simplified solution can be reached by using a stack. If you look at the bigger picture, you'll find that the process of traversal is as followed. `Visit the left subtrees respectively from top to bottom, and visit the right subtrees respectively from bottom to top`. If we are to implement it from this perspective, things will be somewhat different. For the `top to bottom` part we can simply use recursion, and for the `bottom to top` part we can turn to stack. ## In-order Traversal The traversal order of in-order traversal is `left-root-right`. So the root node is not printed first. Things are getting a bit complicated here. Algorithm In-order 1. Visit the root and push it into a stack. 2. If there is a left child node, push it into the stack. Repeat this process until a leaf node reached. > At this point the root node and all the left nodes are in the stack. 3. Start popping nodes from the stack. If a node has a right child node, push the child node into the stack. Repeat step 2. It's worth pointing out that the in-order traversal of a binary search tree (BST) is a sorted array, which is helpful for coming up simplified solutions for some problems. ## Post-order Traversal The traversal order of post-order traversal is `left-right-root`. This one is a bit of a challenge. It deserves the `hard` tag of LeetCode. In this case, the root node is printed not as the first but the last one. A cunning way to do it is to: Record whether the current node has been visited. If 1) it's a leaf node or 2) both its left and right subtrees have been traversed, then it can be popped from the stack. As for `1) it's a leaf node`, you can easily tell whether a node is a leaf if both its left and right are `null`. As for `2) both its left and right subtrees have been traversed`, we only need a variable to record whether a node has been visited or not. In the worst case, we need to record the status for every single node and the space complexity is `O(n)`. But if you come to think about it, as we are using a stack and start printing the result from the leaf nodes, it makes sense that we only record the status for the current node popping from the stack, reducing the space complexity to `O(1)`. ## Level Order Traversal The key point of level order traversal is how do we know whether the traversal of each level is done. The answer is that we use a variable as a flag representing the end of the traversal of the current level. ![binary-tree-traversal-bfs](https://tva1.sinaimg.cn/large/007S8ZIlly1ghlui1tpoug30dw0dw3yl.gif) Algorithm Level-order 1. Visit the root node, put it in a FIFO queue, put in the queue a special flag (we are using `null` here). 2. Dequeue a node. 3. If the node equals `null`, it means that all nodes of the current level have been visited. If the queue is empty, we do nothing. Or else we put in another `null`. 4. If the node is not `null`, meaning the traversal of current level has not finished yet, we enqueue its left subtree and right subtree respectively. ## Bi-color marking We know that there is a tri-color marking in garbage collection algorithm, which works as described below. - The white color represents "not visited". - The gray color represents "not all child nodes visited". - The black color represents "all child nodes visited". Enlightened by tri-color marking, a bi-color marking method can be invented to solve all three traversal problems with one solution. The core idea is as follow. - Use a color to mark whether a node has been visited or not. Nodes yet to be visited are marked as white and visited nodes are marked as gray. - If we are visiting a white node, turn it into gray, and push its right child node, itself, and it's left child node into the stack respectively. - If we are visiting a gray node, print it. Implementation of pre-order and post-order traversal algorithms can be easily done by changing the order of pushing the child nodes into the stack. Reference: [LeetCode](https://github.com/azl397985856/leetcode/blob/master/thinkings/binary-tree-traversal.en.md)
# Binary Tree Traversal ## Overview The combination of binary trees being data structures and traversal being an algorithm relates to classic problems, either directly or indirectly. > If you can grasp the traversal of binary trees, the traversal of other complicated trees will be easy for you. The following are some common ways to traverse trees. - Depth First Traversals (DFS): In-order, Pre-order, Post-order - Level Order Traversal or Breadth First or Traversal (BFS) There are applications for both DFS and BFS. Stack can be used to simplify the process of DFS traversal. Besides, since tree is a recursive data structure, recursion and stack are two key points for DFS. Graph for DFS: ![binary-tree-traversal-dfs](https://tva1.sinaimg.cn/large/007S8ZIlly1ghluhzhynsg30dw0dw3yl.gif) The key point of BFS is how to determine whether the traversal of each level has been completed. The answer is to use a variable as a flag to represent the end of the traversal of current level. ## Pre-order Traversal The traversal order of pre-order traversal is `root-left-right`. Algorithm Pre-order 1. Visit the root node and push it into a stack. 2. Pop a node from the stack, and push its right and left child node into the stack respectively. 3. Repeat step 2. Conclusion: This problem involves the classic recursive data structure (i.e. a binary tree), and the algorithm above demonstrates how a simplified solution can be reached by using a stack. If you look at the bigger picture, you'll find that the process of traversal is as followed. `Visit the left subtrees respectively from top to bottom, and visit the right subtrees respectively from bottom to top`. If we are to implement it from this perspective, things will be somewhat different. For the `top to bottom` part we can simply use recursion, and for the `bottom to top` part we can turn to stack. ## In-order Traversal The traversal order of in-order traversal is `left-root-right`. So the root node is not printed first. Things are getting a bit complicated here. Algorithm In-order 1. Visit the root and push it into a stack. 2. If there is a left child node, push it into the stack. Repeat this process until a leaf node reached. > At this point the root node and all the left nodes are in the stack. 3. Start popping nodes from the stack. If a node has a right child node, push the child node into the stack. Repeat step 2. It's worth pointing out that the in-order traversal of a binary search tree (BST) is a sorted array, which is helpful for coming up simplified solutions for some problems. ## Post-order Traversal The traversal order of post-order traversal is `left-right-root`. This one is a bit of a challenge. It deserves the `hard` tag of LeetCode. In this case, the root node is printed not as the first but the last one. A cunning way to do it is to: Record whether the current node has been visited. If 1) it's a leaf node or 2) both its left and right subtrees have been traversed, then it can be popped from the stack. As for `1) it's a leaf node`, you can easily tell whether a node is a leaf if both its left and right are `null`. As for `2) both its left and right subtrees have been traversed`, we only need a variable to record whether a node has been visited or not. In the worst case, we need to record the status for every single node and the space complexity is `O(n)`. But if you come to think about it, as we are using a stack and start printing the result from the leaf nodes, it makes sense that we only record the status for the current node popping from the stack, reducing the space complexity to `O(1)`. ## Level Order Traversal The key point of level order traversal is how do we know whether the traversal of each level is done. The answer is that we use a variable as a flag representing the end of the traversal of the current level. ![binary-tree-traversal-bfs](https://tva1.sinaimg.cn/large/007S8ZIlly1ghlui1tpoug30dw0dw3yl.gif) Algorithm Level-order 1. Visit the root node, put it in a FIFO queue, put in the queue a special flag (we are using `null` here). 2. Dequeue a node. 3. If the node equals `null`, it means that all nodes of the current level have been visited. If the queue is empty, we do nothing. Or else we put in another `null`. 4. If the node is not `null`, meaning the traversal of current level has not finished yet, we enqueue its left subtree and right subtree respectively. ## Bi-color marking We know that there is a tri-color marking in garbage collection algorithm, which works as described below. - The white color represents "not visited". - The gray color represents "not all child nodes visited". - The black color represents "all child nodes visited". Enlightened by tri-color marking, a bi-color marking method can be invented to solve all three traversal problems with one solution. The core idea is as follow. - Use a color to mark whether a node has been visited or not. Nodes yet to be visited are marked as white and visited nodes are marked as gray. - If we are visiting a white node, turn it into gray, and push its right child node, itself, and it's left child node into the stack respectively. - If we are visiting a gray node, print it. Implementation of pre-order and post-order traversal algorithms can be easily done by changing the order of pushing the child nodes into the stack. Reference: [LeetCode](https://github.com/azl397985856/leetcode/blob/master/thinkings/binary-tree-traversal.en.md)
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Audio Filter Audio filters work on the frequency of an audio signal to attenuate unwanted frequency and amplify wanted ones. They are used within anything related to sound, whether it is radio communication or a hi-fi system. * <https://www.masteringbox.com/filter-types/> * <http://ethanwiner.com/filters.html> * <https://en.wikipedia.org/wiki/Audio_filter> * <https://en.wikipedia.org/wiki/Electronic_filter>
# Audio Filter Audio filters work on the frequency of an audio signal to attenuate unwanted frequency and amplify wanted ones. They are used within anything related to sound, whether it is radio communication or a hi-fi system. * <https://www.masteringbox.com/filter-types/> * <http://ethanwiner.com/filters.html> * <https://en.wikipedia.org/wiki/Audio_filter> * <https://en.wikipedia.org/wiki/Electronic_filter>
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Welcome to Quantum Algorithms Started at https://github.com/TheAlgorithms/Python/issues/1831 * D-Wave: https://www.dwavesys.com and https://github.com/dwavesystems * Google: https://research.google/teams/applied-science/quantum * IBM: https://qiskit.org and https://github.com/Qiskit * Rigetti: https://rigetti.com and https://github.com/rigetti ## IBM Qiskit - Start using by installing `pip install qiskit`, refer the [docs](https://qiskit.org/documentation/install.html) for more info. - Tutorials & References - https://github.com/Qiskit/qiskit-tutorials - https://quantum-computing.ibm.com/docs/iql/first-circuit - https://medium.com/qiskit/how-to-program-a-quantum-computer-982a9329ed02
# Welcome to Quantum Algorithms Started at https://github.com/TheAlgorithms/Python/issues/1831 * D-Wave: https://www.dwavesys.com and https://github.com/dwavesystems * Google: https://research.google/teams/applied-science/quantum * IBM: https://qiskit.org and https://github.com/Qiskit * Rigetti: https://rigetti.com and https://github.com/rigetti ## IBM Qiskit - Start using by installing `pip install qiskit`, refer the [docs](https://qiskit.org/documentation/install.html) for more info. - Tutorials & References - https://github.com/Qiskit/qiskit-tutorials - https://quantum-computing.ibm.com/docs/iql/first-circuit - https://medium.com/qiskit/how-to-program-a-quantum-computer-982a9329ed02
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Cellular Automata Cellular automata are a way to simulate the behavior of "life", no matter if it is a robot or cell. They usually follow simple rules but can lead to the creation of complex forms. The most popular cellular automaton is Conway's [Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). * <https://en.wikipedia.org/wiki/Cellular_automaton> * <https://mathworld.wolfram.com/ElementaryCellularAutomaton.html>
# Cellular Automata Cellular automata are a way to simulate the behavior of "life", no matter if it is a robot or cell. They usually follow simple rules but can lead to the creation of complex forms. The most popular cellular automaton is Conway's [Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). * <https://en.wikipedia.org/wiki/Cellular_automaton> * <https://mathworld.wolfram.com/ElementaryCellularAutomaton.html>
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Configuration for probot-stale - https://github.com/probot/stale # Number of days of inactivity before an Issue or Pull Request becomes stale daysUntilStale: 30 # Number of days of inactivity before an Issue or Pull Request with the stale label is closed. # Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale. daysUntilClose: 7 # Only issues or pull requests with all of these labels are check if stale. Defaults to `[]` (disabled) onlyLabels: [] # Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable exemptLabels: - "Status: on hold" # Set to true to ignore issues in a project (defaults to false) exemptProjects: false # Set to true to ignore issues in a milestone (defaults to false) exemptMilestones: false # Set to true to ignore issues with an assignee (defaults to false) exemptAssignees: false # Label to use when marking as stale staleLabel: stale # Limit the number of actions per hour, from 1-30. Default is 30 limitPerRun: 5 # Comment to post when removing the stale label. # unmarkComment: > # Your comment here. # Optionally, specify configuration settings that are specific to just 'issues' or 'pulls': pulls: # Comment to post when marking as stale. Set to `false` to disable markComment: > This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. # Comment to post when closing a stale Pull Request. closeComment: > Please reopen this pull request once you commit the changes requested or make improvements on the code. If this is not the case and you need some help, feel free to seek help from our [Gitter](https://gitter.im/TheAlgorithms) or ping one of the reviewers. Thank you for your contributions! issues: # Comment to post when marking as stale. Set to `false` to disable markComment: > This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. # Comment to post when closing a stale Issue. closeComment: > Please reopen this issue once you add more information and updates here. If this is not the case and you need some help, feel free to seek help from our [Gitter](https://gitter.im/TheAlgorithms) or ping one of the reviewers. Thank you for your contributions!
# Configuration for probot-stale - https://github.com/probot/stale # Number of days of inactivity before an Issue or Pull Request becomes stale daysUntilStale: 30 # Number of days of inactivity before an Issue or Pull Request with the stale label is closed. # Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale. daysUntilClose: 7 # Only issues or pull requests with all of these labels are check if stale. Defaults to `[]` (disabled) onlyLabels: [] # Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable exemptLabels: - "Status: on hold" # Set to true to ignore issues in a project (defaults to false) exemptProjects: false # Set to true to ignore issues in a milestone (defaults to false) exemptMilestones: false # Set to true to ignore issues with an assignee (defaults to false) exemptAssignees: false # Label to use when marking as stale staleLabel: stale # Limit the number of actions per hour, from 1-30. Default is 30 limitPerRun: 5 # Comment to post when removing the stale label. # unmarkComment: > # Your comment here. # Optionally, specify configuration settings that are specific to just 'issues' or 'pulls': pulls: # Comment to post when marking as stale. Set to `false` to disable markComment: > This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. # Comment to post when closing a stale Pull Request. closeComment: > Please reopen this pull request once you commit the changes requested or make improvements on the code. If this is not the case and you need some help, feel free to seek help from our [Gitter](https://gitter.im/TheAlgorithms) or ping one of the reviewers. Thank you for your contributions! issues: # Comment to post when marking as stale. Set to `false` to disable markComment: > This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. # Comment to post when closing a stale Issue. closeComment: > Please reopen this issue once you add more information and updates here. If this is not the case and you need some help, feel free to seek help from our [Gitter](https://gitter.im/TheAlgorithms) or ping one of the reviewers. Thank you for your contributions!
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] 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
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" https://en.wikipedia.org/wiki/Infix_notation https://en.wikipedia.org/wiki/Reverse_Polish_notation https://en.wikipedia.org/wiki/Shunting-yard_algorithm """ from .balanced_parentheses import balanced_parentheses from .stack import Stack def precedence(char: str) -> int: """ Return integer value representing an operator's precedence, or order of operation. https://en.wikipedia.org/wiki/Order_of_operations """ return {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}.get(char, -1) def infix_to_postfix(expression_str: str) -> str: """ >>> infix_to_postfix("(1*(2+3)+4))") Traceback (most recent call last): ... ValueError: Mismatched parentheses >>> infix_to_postfix("") '' >>> infix_to_postfix("3+2") '3 2 +' >>> infix_to_postfix("(3+4)*5-6") '3 4 + 5 * 6 -' >>> infix_to_postfix("(1+2)*3/4-5") '1 2 + 3 * 4 / 5 -' >>> infix_to_postfix("a+b*c+(d*e+f)*g") 'a b c * + d e * f + g * +' >>> infix_to_postfix("x^y/(5*z)+2") 'x y ^ 5 z * / 2 +' """ if not balanced_parentheses(expression_str): raise ValueError("Mismatched parentheses") stack: Stack[str] = Stack() postfix = [] for char in expression_str: if char.isalpha() or char.isdigit(): postfix.append(char) elif char == "(": stack.push(char) elif char == ")": while not stack.is_empty() and stack.peek() != "(": postfix.append(stack.pop()) stack.pop() else: while not stack.is_empty() and precedence(char) <= precedence(stack.peek()): postfix.append(stack.pop()) stack.push(char) while not stack.is_empty(): postfix.append(stack.pop()) return " ".join(postfix) if __name__ == "__main__": from doctest import testmod testmod() expression = "a+b*(c^d-e)^(f+g*h)-i" print("Infix to Postfix Notation demonstration:\n") print("Infix notation: " + expression) print("Postfix notation: " + infix_to_postfix(expression))
""" https://en.wikipedia.org/wiki/Infix_notation https://en.wikipedia.org/wiki/Reverse_Polish_notation https://en.wikipedia.org/wiki/Shunting-yard_algorithm """ from .balanced_parentheses import balanced_parentheses from .stack import Stack def precedence(char: str) -> int: """ Return integer value representing an operator's precedence, or order of operation. https://en.wikipedia.org/wiki/Order_of_operations """ return {"+": 1, "-": 1, "*": 2, "/": 2, "^": 3}.get(char, -1) def infix_to_postfix(expression_str: str) -> str: """ >>> infix_to_postfix("(1*(2+3)+4))") Traceback (most recent call last): ... ValueError: Mismatched parentheses >>> infix_to_postfix("") '' >>> infix_to_postfix("3+2") '3 2 +' >>> infix_to_postfix("(3+4)*5-6") '3 4 + 5 * 6 -' >>> infix_to_postfix("(1+2)*3/4-5") '1 2 + 3 * 4 / 5 -' >>> infix_to_postfix("a+b*c+(d*e+f)*g") 'a b c * + d e * f + g * +' >>> infix_to_postfix("x^y/(5*z)+2") 'x y ^ 5 z * / 2 +' """ if not balanced_parentheses(expression_str): raise ValueError("Mismatched parentheses") stack: Stack[str] = Stack() postfix = [] for char in expression_str: if char.isalpha() or char.isdigit(): postfix.append(char) elif char == "(": stack.push(char) elif char == ")": while not stack.is_empty() and stack.peek() != "(": postfix.append(stack.pop()) stack.pop() else: while not stack.is_empty() and precedence(char) <= precedence(stack.peek()): postfix.append(stack.pop()) stack.push(char) while not stack.is_empty(): postfix.append(stack.pop()) return " ".join(postfix) if __name__ == "__main__": from doctest import testmod testmod() expression = "a+b*(c^d-e)^(f+g*h)-i" print("Infix to Postfix Notation demonstration:\n") print("Infix notation: " + expression) print("Postfix notation: " + infix_to_postfix(expression))
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" An RSA prime factor algorithm. The program can efficiently factor RSA prime number given the private key d and public key e. Source: on page 3 of https://crypto.stanford.edu/~dabo/papers/RSA-survey.pdf More readable source: https://www.di-mgt.com.au/rsa_factorize_n.html large number can take minutes to factor, therefore are not included in doctest. """ from __future__ import annotations import math import random def rsafactor(d: int, e: int, N: int) -> list[int]: """ This function returns the factors of N, where p*q=N Return: [p, q] We call N the RSA modulus, e the encryption exponent, and d the decryption exponent. The pair (N, e) is the public key. As its name suggests, it is public and is used to encrypt messages. The pair (N, d) is the secret key or private key and is known only to the recipient of encrypted messages. >>> rsafactor(3, 16971, 25777) [149, 173] >>> rsafactor(7331, 11, 27233) [113, 241] >>> rsafactor(4021, 13, 17711) [89, 199] """ k = d * e - 1 p = 0 q = 0 while p == 0: g = random.randint(2, N - 1) t = k while True: if t % 2 == 0: t = t // 2 x = (g**t) % N y = math.gcd(x - 1, N) if x > 1 and y > 1: p = y q = N // y break # find the correct factors else: break # t is not divisible by 2, break and choose another g return sorted([p, q]) if __name__ == "__main__": import doctest doctest.testmod()
""" An RSA prime factor algorithm. The program can efficiently factor RSA prime number given the private key d and public key e. Source: on page 3 of https://crypto.stanford.edu/~dabo/papers/RSA-survey.pdf More readable source: https://www.di-mgt.com.au/rsa_factorize_n.html large number can take minutes to factor, therefore are not included in doctest. """ from __future__ import annotations import math import random def rsafactor(d: int, e: int, N: int) -> list[int]: """ This function returns the factors of N, where p*q=N Return: [p, q] We call N the RSA modulus, e the encryption exponent, and d the decryption exponent. The pair (N, e) is the public key. As its name suggests, it is public and is used to encrypt messages. The pair (N, d) is the secret key or private key and is known only to the recipient of encrypted messages. >>> rsafactor(3, 16971, 25777) [149, 173] >>> rsafactor(7331, 11, 27233) [113, 241] >>> rsafactor(4021, 13, 17711) [89, 199] """ k = d * e - 1 p = 0 q = 0 while p == 0: g = random.randint(2, N - 1) t = k while True: if t % 2 == 0: t = t // 2 x = (g**t) % N y = math.gcd(x - 1, N) if x > 1 and y > 1: p = y q = N // y break # find the correct factors else: break # t is not divisible by 2, break and choose another g return sorted([p, q]) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from collections import Counter def sock_merchant(colors: list[int]) -> int: """ >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20]) 3 >>> sock_merchant([1, 1, 3, 3]) 2 """ return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values()) if __name__ == "__main__": import doctest doctest.testmod() colors = [int(x) for x in input("Enter socks by color :").rstrip().split()] print(f"sock_merchant({colors}) = {sock_merchant(colors)}")
from collections import Counter def sock_merchant(colors: list[int]) -> int: """ >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20]) 3 >>> sock_merchant([1, 1, 3, 3]) 2 """ return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values()) if __name__ == "__main__": import doctest doctest.testmod() colors = [int(x) for x in input("Enter socks by color :").rstrip().split()] print(f"sock_merchant({colors}) = {sock_merchant(colors)}")
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import base64 def base32_encode(string: str) -> bytes: """ Encodes a given string to base32, returning a bytes-like object >>> base32_encode("Hello World!") b'JBSWY3DPEBLW64TMMQQQ====' >>> base32_encode("123456") b'GEZDGNBVGY======' >>> base32_encode("some long complex string") b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=' """ # encoded the input (we need a bytes like object) # then, b32encoded the bytes-like object return base64.b32encode(string.encode("utf-8")) def base32_decode(encoded_bytes: bytes) -> str: """ Decodes a given bytes-like object to a string, returning a string >>> base32_decode(b'JBSWY3DPEBLW64TMMQQQ====') 'Hello World!' >>> base32_decode(b'GEZDGNBVGY======') '123456' >>> base32_decode(b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=') 'some long complex string' """ # decode the bytes from base32 # then, decode the bytes-like object to return as a string return base64.b32decode(encoded_bytes).decode("utf-8") if __name__ == "__main__": test = "Hello World!" encoded = base32_encode(test) print(encoded) decoded = base32_decode(encoded) print(decoded)
import base64 def base32_encode(string: str) -> bytes: """ Encodes a given string to base32, returning a bytes-like object >>> base32_encode("Hello World!") b'JBSWY3DPEBLW64TMMQQQ====' >>> base32_encode("123456") b'GEZDGNBVGY======' >>> base32_encode("some long complex string") b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=' """ # encoded the input (we need a bytes like object) # then, b32encoded the bytes-like object return base64.b32encode(string.encode("utf-8")) def base32_decode(encoded_bytes: bytes) -> str: """ Decodes a given bytes-like object to a string, returning a string >>> base32_decode(b'JBSWY3DPEBLW64TMMQQQ====') 'Hello World!' >>> base32_decode(b'GEZDGNBVGY======') '123456' >>> base32_decode(b'ONXW2ZJANRXW4ZZAMNXW24DMMV4CA43UOJUW4ZY=') 'some long complex string' """ # decode the bytes from base32 # then, decode the bytes-like object to return as a string return base64.b32decode(encoded_bytes).decode("utf-8") if __name__ == "__main__": test = "Hello World!" encoded = base32_encode(test) print(encoded) decoded = base32_decode(encoded) print(decoded)
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A Python implementation of the quick select algorithm, which is efficient for calculating the value that would appear in the index of a list if it would be sorted, even if it is not already sorted https://en.wikipedia.org/wiki/Quickselect """ import random def _partition(data: list, pivot) -> tuple: """ Three way partition the data into smaller, equal and greater lists, in relationship to the pivot :param data: The data to be sorted (a list) :param pivot: The value to partition the data on :return: Three list: smaller, equal and greater """ less, equal, greater = [], [], [] for element in data: if element < pivot: less.append(element) elif element > pivot: greater.append(element) else: equal.append(element) return less, equal, greater def quick_select(items: list, index: int): """ >>> quick_select([2, 4, 5, 7, 899, 54, 32], 5) 54 >>> quick_select([2, 4, 5, 7, 899, 54, 32], 1) 4 >>> quick_select([5, 4, 3, 2], 2) 4 >>> quick_select([3, 5, 7, 10, 2, 12], 3) 7 """ # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(items) or index < 0: return None pivot = items[random.randint(0, len(items) - 1)] count = 0 smaller, equal, larger = _partition(items, pivot) count = len(equal) m = len(smaller) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(smaller, index) # must be in larger else: return quick_select(larger, index - (m + count))
""" A Python implementation of the quick select algorithm, which is efficient for calculating the value that would appear in the index of a list if it would be sorted, even if it is not already sorted https://en.wikipedia.org/wiki/Quickselect """ import random def _partition(data: list, pivot) -> tuple: """ Three way partition the data into smaller, equal and greater lists, in relationship to the pivot :param data: The data to be sorted (a list) :param pivot: The value to partition the data on :return: Three list: smaller, equal and greater """ less, equal, greater = [], [], [] for element in data: if element < pivot: less.append(element) elif element > pivot: greater.append(element) else: equal.append(element) return less, equal, greater def quick_select(items: list, index: int): """ >>> quick_select([2, 4, 5, 7, 899, 54, 32], 5) 54 >>> quick_select([2, 4, 5, 7, 899, 54, 32], 1) 4 >>> quick_select([5, 4, 3, 2], 2) 4 >>> quick_select([3, 5, 7, 10, 2, 12], 3) 7 """ # index = len(items) // 2 when trying to find the median # (value of index when items is sorted) # invalid input if index >= len(items) or index < 0: return None pivot = items[random.randint(0, len(items) - 1)] count = 0 smaller, equal, larger = _partition(items, pivot) count = len(equal) m = len(smaller) # index is the pivot if m <= index < m + count: return pivot # must be in smaller elif m > index: return quick_select(smaller, index) # must be in larger else: return quick_select(larger, index - (m + count))
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A Hamiltonian cycle (Hamiltonian circuit) is a graph cycle through a graph that visits each node exactly once. Determining whether such paths and cycles exist in graphs is the 'Hamiltonian path problem', which is NP-complete. Wikipedia: https://en.wikipedia.org/wiki/Hamiltonian_path """ def valid_connection( graph: list[list[int]], next_ver: int, curr_ind: int, path: list[int] ) -> bool: """ Checks whether it is possible to add next into path by validating 2 statements 1. There should be path between current and next vertex 2. Next vertex should not be in path If both validations succeed we return True, saying that it is possible to connect this vertices, otherwise we return False Case 1:Use exact graph as in main function, with initialized values >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> path = [0, -1, -1, -1, -1, 0] >>> curr_ind = 1 >>> next_ver = 1 >>> valid_connection(graph, next_ver, curr_ind, path) True Case 2: Same graph, but trying to connect to node that is already in path >>> path = [0, 1, 2, 4, -1, 0] >>> curr_ind = 4 >>> next_ver = 1 >>> valid_connection(graph, next_ver, curr_ind, path) False """ # 1. Validate that path exists between current and next vertices if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path) def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int) -> bool: """ Pseudo-Code Base Case: 1. Check if we visited all of vertices 1.1 If last visited vertex has path to starting vertex return True either return False Recursive Step: 2. Iterate over each vertex Check if next vertex is valid for transiting from current vertex 2.1 Remember next vertex as next transition 2.2 Do recursive call and check if going to this vertex solves problem 2.3 If next vertex leads to solution return True 2.4 Else backtrack, delete remembered vertex Case 1: Use exact graph as in main function, with initialized values >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> path = [0, -1, -1, -1, -1, 0] >>> curr_ind = 1 >>> util_hamilton_cycle(graph, path, curr_ind) True >>> print(path) [0, 1, 2, 4, 3, 0] Case 2: Use exact graph as in previous case, but in the properties taken from middle of calculation >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> path = [0, 1, 2, -1, -1, 0] >>> curr_ind = 3 >>> util_hamilton_cycle(graph, path, curr_ind) True >>> print(path) [0, 1, 2, 4, 3, 0] """ # Base Case if curr_ind == len(graph): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next in range(0, len(graph)): if valid_connection(graph, next, curr_ind, path): # Insert current vertex into path as next transition path[curr_ind] = next # Validate created path if util_hamilton_cycle(graph, path, curr_ind + 1): return True # Backtrack path[curr_ind] = -1 return False def hamilton_cycle(graph: list[list[int]], start_index: int = 0) -> list[int]: r""" Wrapper function to call subroutine called util_hamilton_cycle, which will either return array of vertices indicating hamiltonian cycle or an empty list indicating that hamiltonian cycle was not found. Case 1: Following graph consists of 5 edges. If we look closely, we can see that there are multiple Hamiltonian cycles. For example one result is when we iterate like: (0)->(1)->(2)->(4)->(3)->(0) (0)---(1)---(2) | / \ | | / \ | | / \ | |/ \| (3)---------(4) >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> hamilton_cycle(graph) [0, 1, 2, 4, 3, 0] Case 2: Same Graph as it was in Case 1, changed starting index from default to 3 (0)---(1)---(2) | / \ | | / \ | | / \ | |/ \| (3)---------(4) >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> hamilton_cycle(graph, 3) [3, 0, 1, 2, 4, 3] Case 3: Following Graph is exactly what it was before, but edge 3-4 is removed. Result is that there is no Hamiltonian Cycle anymore. (0)---(1)---(2) | / \ | | / \ | | / \ | |/ \| (3) (4) >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 0], ... [0, 1, 1, 0, 0]] >>> hamilton_cycle(graph,4) [] """ # Initialize path with -1, indicating that we have not visited them yet path = [-1] * (len(graph) + 1) # initialize start and end of path with starting index path[0] = path[-1] = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(graph, path, 1) else []
""" A Hamiltonian cycle (Hamiltonian circuit) is a graph cycle through a graph that visits each node exactly once. Determining whether such paths and cycles exist in graphs is the 'Hamiltonian path problem', which is NP-complete. Wikipedia: https://en.wikipedia.org/wiki/Hamiltonian_path """ def valid_connection( graph: list[list[int]], next_ver: int, curr_ind: int, path: list[int] ) -> bool: """ Checks whether it is possible to add next into path by validating 2 statements 1. There should be path between current and next vertex 2. Next vertex should not be in path If both validations succeed we return True, saying that it is possible to connect this vertices, otherwise we return False Case 1:Use exact graph as in main function, with initialized values >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> path = [0, -1, -1, -1, -1, 0] >>> curr_ind = 1 >>> next_ver = 1 >>> valid_connection(graph, next_ver, curr_ind, path) True Case 2: Same graph, but trying to connect to node that is already in path >>> path = [0, 1, 2, 4, -1, 0] >>> curr_ind = 4 >>> next_ver = 1 >>> valid_connection(graph, next_ver, curr_ind, path) False """ # 1. Validate that path exists between current and next vertices if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path) def util_hamilton_cycle(graph: list[list[int]], path: list[int], curr_ind: int) -> bool: """ Pseudo-Code Base Case: 1. Check if we visited all of vertices 1.1 If last visited vertex has path to starting vertex return True either return False Recursive Step: 2. Iterate over each vertex Check if next vertex is valid for transiting from current vertex 2.1 Remember next vertex as next transition 2.2 Do recursive call and check if going to this vertex solves problem 2.3 If next vertex leads to solution return True 2.4 Else backtrack, delete remembered vertex Case 1: Use exact graph as in main function, with initialized values >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> path = [0, -1, -1, -1, -1, 0] >>> curr_ind = 1 >>> util_hamilton_cycle(graph, path, curr_ind) True >>> print(path) [0, 1, 2, 4, 3, 0] Case 2: Use exact graph as in previous case, but in the properties taken from middle of calculation >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> path = [0, 1, 2, -1, -1, 0] >>> curr_ind = 3 >>> util_hamilton_cycle(graph, path, curr_ind) True >>> print(path) [0, 1, 2, 4, 3, 0] """ # Base Case if curr_ind == len(graph): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next in range(0, len(graph)): if valid_connection(graph, next, curr_ind, path): # Insert current vertex into path as next transition path[curr_ind] = next # Validate created path if util_hamilton_cycle(graph, path, curr_ind + 1): return True # Backtrack path[curr_ind] = -1 return False def hamilton_cycle(graph: list[list[int]], start_index: int = 0) -> list[int]: r""" Wrapper function to call subroutine called util_hamilton_cycle, which will either return array of vertices indicating hamiltonian cycle or an empty list indicating that hamiltonian cycle was not found. Case 1: Following graph consists of 5 edges. If we look closely, we can see that there are multiple Hamiltonian cycles. For example one result is when we iterate like: (0)->(1)->(2)->(4)->(3)->(0) (0)---(1)---(2) | / \ | | / \ | | / \ | |/ \| (3)---------(4) >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> hamilton_cycle(graph) [0, 1, 2, 4, 3, 0] Case 2: Same Graph as it was in Case 1, changed starting index from default to 3 (0)---(1)---(2) | / \ | | / \ | | / \ | |/ \| (3)---------(4) >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 1], ... [0, 1, 1, 1, 0]] >>> hamilton_cycle(graph, 3) [3, 0, 1, 2, 4, 3] Case 3: Following Graph is exactly what it was before, but edge 3-4 is removed. Result is that there is no Hamiltonian Cycle anymore. (0)---(1)---(2) | / \ | | / \ | | / \ | |/ \| (3) (4) >>> graph = [[0, 1, 0, 1, 0], ... [1, 0, 1, 1, 1], ... [0, 1, 0, 0, 1], ... [1, 1, 0, 0, 0], ... [0, 1, 1, 0, 0]] >>> hamilton_cycle(graph,4) [] """ # Initialize path with -1, indicating that we have not visited them yet path = [-1] * (len(graph) + 1) # initialize start and end of path with starting index path[0] = path[-1] = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(graph, path, 1) else []
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Factorial of a number using memoization from functools import lru_cache @lru_cache def factorial(num: int) -> int: """ >>> factorial(7) 5040 >>> factorial(-1) Traceback (most recent call last): ... ValueError: Number should not be negative. >>> [factorial(i) for i in range(10)] [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] """ if num < 0: raise ValueError("Number should not be negative.") return 1 if num in (0, 1) else num * factorial(num - 1) if __name__ == "__main__": import doctest doctest.testmod()
# Factorial of a number using memoization from functools import lru_cache @lru_cache def factorial(num: int) -> int: """ >>> factorial(7) 5040 >>> factorial(-1) Traceback (most recent call last): ... ValueError: Number should not be negative. >>> [factorial(i) for i in range(10)] [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] """ if num < 0: raise ValueError("Number should not be negative.") return 1 if num in (0, 1) else num * factorial(num - 1) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] 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 """ from math import sqrt def is_prime(n: int) -> bool: """ Returns boolean representing primality of given number num. >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True """ if 1 < n < 4: return True elif n < 2 or not n % 2: return False return not any(not n % i for i in range(3, int(sqrt(n) + 1), 2)) 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(num for num in range(3, n, 2) if is_prime(num)) + 2 if n > 2 else 0 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 """ from math import sqrt def is_prime(n: int) -> bool: """ Returns boolean representing primality of given number num. >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True """ if 1 < n < 4: return True elif n < 2 or not n % 2: return False return not any(not n % i for i in range(3, int(sqrt(n) + 1), 2)) 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(num for num in range(3, n, 2) if is_prime(num)) + 2 if n > 2 else 0 if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
#!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git commit" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message if # it wants to stop the commit. # # To enable this hook, rename this file to "pre-commit". if git rev-parse --verify HEAD >/dev/null 2>&1 then against=HEAD else # Initial commit: diff against an empty tree object against=$(git hash-object -t tree /dev/null) fi # If you want to allow non-ASCII filenames set this variable to true. allownonascii=$(git config --bool hooks.allownonascii) # Redirect output to stderr. exec 1>&2 # Cross platform projects tend to avoid non-ASCII filenames; prevent # them from being added to the repository. We exploit the fact that the # printable range starts at the space character and ends with tilde. if [ "$allownonascii" != "true" ] && # Note that the use of brackets around a tr range is ok here, (it's # even required, for portability to Solaris 10's /usr/bin/tr), since # the square bracket bytes happen to fall in the designated range. test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 then cat <<\EOF Error: Attempt to add a non-ASCII file name. This can cause problems if you want to work with people on other platforms. To be portable it is advisable to rename the file. If you know what you are doing you can disable this check using: git config hooks.allownonascii true EOF exit 1 fi # If there are whitespace errors, print the offending file names and fail. exec git diff-index --check --cached $against --
#!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git commit" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message if # it wants to stop the commit. # # To enable this hook, rename this file to "pre-commit". if git rev-parse --verify HEAD >/dev/null 2>&1 then against=HEAD else # Initial commit: diff against an empty tree object against=$(git hash-object -t tree /dev/null) fi # If you want to allow non-ASCII filenames set this variable to true. allownonascii=$(git config --bool hooks.allownonascii) # Redirect output to stderr. exec 1>&2 # Cross platform projects tend to avoid non-ASCII filenames; prevent # them from being added to the repository. We exploit the fact that the # printable range starts at the space character and ends with tilde. if [ "$allownonascii" != "true" ] && # Note that the use of brackets around a tr range is ok here, (it's # even required, for portability to Solaris 10's /usr/bin/tr), since # the square bracket bytes happen to fall in the designated range. test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 then cat <<\EOF Error: Attempt to add a non-ASCII file name. This can cause problems if you want to work with people on other platforms. To be portable it is advisable to rename the file. If you know what you are doing you can disable this check using: git config hooks.allownonascii true EOF exit 1 fi # If there are whitespace errors, print the offending file names and fail. exec git diff-index --check --cached $against --
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def topologicalSort(graph): """ Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph using BFS """ indegree = [0] * len(graph) queue = [] topo = [] cnt = 0 for key, values in graph.items(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if indegree[i] == 0: queue.append(i) while queue: vertex = queue.pop(0) cnt += 1 topo.append(vertex) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(x) if cnt != len(graph): print("Cycle exists") else: print(topo) # Adjacency List of Graph graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topologicalSort(graph)
def topologicalSort(graph): """ Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph using BFS """ indegree = [0] * len(graph) queue = [] topo = [] cnt = 0 for key, values in graph.items(): for i in values: indegree[i] += 1 for i in range(len(indegree)): if indegree[i] == 0: queue.append(i) while queue: vertex = queue.pop(0) cnt += 1 topo.append(vertex) for x in graph[vertex]: indegree[x] -= 1 if indegree[x] == 0: queue.append(x) if cnt != len(graph): print("Cycle exists") else: print(topo) # Adjacency List of Graph graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} topologicalSort(graph)
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Python program to implement Pigeonhole Sorting in python # Algorithm for the pigeonhole sorting def pigeonhole_sort(a): """ >>> a = [8, 3, 2, 7, 4, 6, 8] >>> b = sorted(a) # a nondestructive sort >>> pigeonhole_sort(a) # a destructive sort >>> a == b True """ # size of range of values in the list (ie, number of pigeonholes we need) min_val = min(a) # min() finds the minimum value max_val = max(a) # max() finds the maximum value size = max_val - min_val + 1 # size is difference of max and min values plus one # list of pigeonholes of size equal to the variable size holes = [0] * size # Populate the pigeonholes. for x in a: assert isinstance(x, int), "integers only please" holes[x - min_val] += 1 # Putting the elements back into the array in an order. i = 0 for count in range(size): while holes[count] > 0: holes[count] -= 1 a[i] = count + min_val i += 1 def main(): a = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(a) print("Sorted order is:", " ".join(a)) if __name__ == "__main__": main()
# Python program to implement Pigeonhole Sorting in python # Algorithm for the pigeonhole sorting def pigeonhole_sort(a): """ >>> a = [8, 3, 2, 7, 4, 6, 8] >>> b = sorted(a) # a nondestructive sort >>> pigeonhole_sort(a) # a destructive sort >>> a == b True """ # size of range of values in the list (ie, number of pigeonholes we need) min_val = min(a) # min() finds the minimum value max_val = max(a) # max() finds the maximum value size = max_val - min_val + 1 # size is difference of max and min values plus one # list of pigeonholes of size equal to the variable size holes = [0] * size # Populate the pigeonholes. for x in a: assert isinstance(x, int), "integers only please" holes[x - min_val] += 1 # Putting the elements back into the array in an order. i = 0 for count in range(size): while holes[count] > 0: holes[count] -= 1 a[i] = count + min_val i += 1 def main(): a = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(a) print("Sorted order is:", " ".join(a)) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Similarity Search : https://en.wikipedia.org/wiki/Similarity_search Similarity search is a search algorithm for finding the nearest vector from vectors, used in natural language processing. In this algorithm, it calculates distance with euclidean distance and returns a list containing two data for each vector: 1. the nearest vector 2. distance between the vector and the nearest vector (float) """ from __future__ import annotations import math import numpy as np def euclidean(input_a: np.ndarray, input_b: np.ndarray) -> float: """ Calculates euclidean distance between two data. :param input_a: ndarray of first vector. :param input_b: ndarray of second vector. :return: Euclidean distance of input_a and input_b. By using math.sqrt(), result will be float. >>> euclidean(np.array([0]), np.array([1])) 1.0 >>> euclidean(np.array([0, 1]), np.array([1, 1])) 1.0 >>> euclidean(np.array([0, 0, 0]), np.array([0, 0, 1])) 1.0 """ return math.sqrt(sum(pow(a - b, 2) for a, b in zip(input_a, input_b))) def similarity_search( dataset: np.ndarray, value_array: np.ndarray ) -> list[list[list[float] | float]]: """ :param dataset: Set containing the vectors. Should be ndarray. :param value_array: vector/vectors we want to know the nearest vector from dataset. :return: Result will be a list containing 1. the nearest vector 2. distance from the vector >>> dataset = np.array([[0], [1], [2]]) >>> value_array = np.array([[0]]) >>> similarity_search(dataset, value_array) [[[0], 0.0]] >>> dataset = np.array([[0, 0], [1, 1], [2, 2]]) >>> value_array = np.array([[0, 1]]) >>> similarity_search(dataset, value_array) [[[0, 0], 1.0]] >>> dataset = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) >>> value_array = np.array([[0, 0, 1]]) >>> similarity_search(dataset, value_array) [[[0, 0, 0], 1.0]] >>> dataset = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) >>> value_array = np.array([[0, 0, 0], [0, 0, 1]]) >>> similarity_search(dataset, value_array) [[[0, 0, 0], 0.0], [[0, 0, 0], 1.0]] These are the errors that might occur: 1. If dimensions are different. For example, dataset has 2d array and value_array has 1d array: >>> dataset = np.array([[1]]) >>> value_array = np.array([1]) >>> similarity_search(dataset, value_array) Traceback (most recent call last): ... ValueError: Wrong input data's dimensions... dataset : 2, value_array : 1 2. If data's shapes are different. For example, dataset has shape of (3, 2) and value_array has (2, 3). We are expecting same shapes of two arrays, so it is wrong. >>> dataset = np.array([[0, 0], [1, 1], [2, 2]]) >>> value_array = np.array([[0, 0, 0], [0, 0, 1]]) >>> similarity_search(dataset, value_array) Traceback (most recent call last): ... ValueError: Wrong input data's shape... dataset : 2, value_array : 3 3. If data types are different. When trying to compare, we are expecting same types so they should be same. If not, it'll come up with errors. >>> dataset = np.array([[0, 0], [1, 1], [2, 2]], dtype=np.float32) >>> value_array = np.array([[0, 0], [0, 1]], dtype=np.int32) >>> similarity_search(dataset, value_array) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TypeError: Input data have different datatype... dataset : float32, value_array : int32 """ if dataset.ndim != value_array.ndim: raise ValueError( f"Wrong input data's dimensions... dataset : {dataset.ndim}, " f"value_array : {value_array.ndim}" ) try: if dataset.shape[1] != value_array.shape[1]: raise ValueError( f"Wrong input data's shape... dataset : {dataset.shape[1]}, " f"value_array : {value_array.shape[1]}" ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError("Wrong shape") if dataset.dtype != value_array.dtype: raise TypeError( f"Input data have different datatype... dataset : {dataset.dtype}, " f"value_array : {value_array.dtype}" ) answer = [] for value in value_array: dist = euclidean(value, dataset[0]) vector = dataset[0].tolist() for dataset_value in dataset[1:]: temp_dist = euclidean(value, dataset_value) if dist > temp_dist: dist = temp_dist vector = dataset_value.tolist() answer.append([vector, dist]) return answer if __name__ == "__main__": import doctest doctest.testmod()
""" Similarity Search : https://en.wikipedia.org/wiki/Similarity_search Similarity search is a search algorithm for finding the nearest vector from vectors, used in natural language processing. In this algorithm, it calculates distance with euclidean distance and returns a list containing two data for each vector: 1. the nearest vector 2. distance between the vector and the nearest vector (float) """ from __future__ import annotations import math import numpy as np def euclidean(input_a: np.ndarray, input_b: np.ndarray) -> float: """ Calculates euclidean distance between two data. :param input_a: ndarray of first vector. :param input_b: ndarray of second vector. :return: Euclidean distance of input_a and input_b. By using math.sqrt(), result will be float. >>> euclidean(np.array([0]), np.array([1])) 1.0 >>> euclidean(np.array([0, 1]), np.array([1, 1])) 1.0 >>> euclidean(np.array([0, 0, 0]), np.array([0, 0, 1])) 1.0 """ return math.sqrt(sum(pow(a - b, 2) for a, b in zip(input_a, input_b))) def similarity_search( dataset: np.ndarray, value_array: np.ndarray ) -> list[list[list[float] | float]]: """ :param dataset: Set containing the vectors. Should be ndarray. :param value_array: vector/vectors we want to know the nearest vector from dataset. :return: Result will be a list containing 1. the nearest vector 2. distance from the vector >>> dataset = np.array([[0], [1], [2]]) >>> value_array = np.array([[0]]) >>> similarity_search(dataset, value_array) [[[0], 0.0]] >>> dataset = np.array([[0, 0], [1, 1], [2, 2]]) >>> value_array = np.array([[0, 1]]) >>> similarity_search(dataset, value_array) [[[0, 0], 1.0]] >>> dataset = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) >>> value_array = np.array([[0, 0, 1]]) >>> similarity_search(dataset, value_array) [[[0, 0, 0], 1.0]] >>> dataset = np.array([[0, 0, 0], [1, 1, 1], [2, 2, 2]]) >>> value_array = np.array([[0, 0, 0], [0, 0, 1]]) >>> similarity_search(dataset, value_array) [[[0, 0, 0], 0.0], [[0, 0, 0], 1.0]] These are the errors that might occur: 1. If dimensions are different. For example, dataset has 2d array and value_array has 1d array: >>> dataset = np.array([[1]]) >>> value_array = np.array([1]) >>> similarity_search(dataset, value_array) Traceback (most recent call last): ... ValueError: Wrong input data's dimensions... dataset : 2, value_array : 1 2. If data's shapes are different. For example, dataset has shape of (3, 2) and value_array has (2, 3). We are expecting same shapes of two arrays, so it is wrong. >>> dataset = np.array([[0, 0], [1, 1], [2, 2]]) >>> value_array = np.array([[0, 0, 0], [0, 0, 1]]) >>> similarity_search(dataset, value_array) Traceback (most recent call last): ... ValueError: Wrong input data's shape... dataset : 2, value_array : 3 3. If data types are different. When trying to compare, we are expecting same types so they should be same. If not, it'll come up with errors. >>> dataset = np.array([[0, 0], [1, 1], [2, 2]], dtype=np.float32) >>> value_array = np.array([[0, 0], [0, 1]], dtype=np.int32) >>> similarity_search(dataset, value_array) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TypeError: Input data have different datatype... dataset : float32, value_array : int32 """ if dataset.ndim != value_array.ndim: raise ValueError( f"Wrong input data's dimensions... dataset : {dataset.ndim}, " f"value_array : {value_array.ndim}" ) try: if dataset.shape[1] != value_array.shape[1]: raise ValueError( f"Wrong input data's shape... dataset : {dataset.shape[1]}, " f"value_array : {value_array.shape[1]}" ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError("Wrong shape") if dataset.dtype != value_array.dtype: raise TypeError( f"Input data have different datatype... dataset : {dataset.dtype}, " f"value_array : {value_array.dtype}" ) answer = [] for value in value_array: dist = euclidean(value, dataset[0]) vector = dataset[0].tolist() for dataset_value in dataset[1:]: temp_dist = euclidean(value, dataset_value) if dist > temp_dist: dist = temp_dist vector = dataset_value.tolist() answer.append([vector, dist]) return answer if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Testing here assumes that numpy and linalg is ALWAYS correct!!!! If running from PyCharm you can place the following line in "Additional Arguments" for the pytest run configuration -vv -m mat_ops -p no:cacheprovider """ import logging # standard libraries import sys import numpy as np import pytest # type: ignore # Custom/local libraries from matrix import matrix_operation as matop mat_a = [[12, 10], [3, 9]] mat_b = [[3, 4], [7, 4]] mat_c = [[3, 0, 2], [2, 0, -2], [0, 1, 1]] mat_d = [[3, 0, -2], [2, 0, 2], [0, 1, 1]] mat_e = [[3, 0, 2], [2, 0, -2], [0, 1, 1], [2, 0, -2]] mat_f = [1] mat_h = [2] logger = logging.getLogger() logger.level = logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) @pytest.mark.mat_ops @pytest.mark.parametrize( ("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)] ) def test_addition(mat1, mat2): if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): with pytest.raises(TypeError): logger.info(f"\n\t{test_addition.__name__} returned integer") matop.add(mat1, mat2) elif (np.array(mat1)).shape == (np.array(mat2)).shape: logger.info(f"\n\t{test_addition.__name__} with same matrix dims") act = (np.array(mat1) + np.array(mat2)).tolist() theo = matop.add(mat1, mat2) assert theo == act else: with pytest.raises(ValueError): logger.info(f"\n\t{test_addition.__name__} with different matrix dims") matop.add(mat1, mat2) @pytest.mark.mat_ops @pytest.mark.parametrize( ("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)] ) def test_subtraction(mat1, mat2): if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): with pytest.raises(TypeError): logger.info(f"\n\t{test_subtraction.__name__} returned integer") matop.subtract(mat1, mat2) elif (np.array(mat1)).shape == (np.array(mat2)).shape: logger.info(f"\n\t{test_subtraction.__name__} with same matrix dims") act = (np.array(mat1) - np.array(mat2)).tolist() theo = matop.subtract(mat1, mat2) assert theo == act else: with pytest.raises(ValueError): logger.info(f"\n\t{test_subtraction.__name__} with different matrix dims") assert matop.subtract(mat1, mat2) @pytest.mark.mat_ops @pytest.mark.parametrize( ("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)] ) def test_multiplication(mat1, mat2): if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): logger.info(f"\n\t{test_multiplication.__name__} returned integer") with pytest.raises(TypeError): matop.add(mat1, mat2) elif (np.array(mat1)).shape == (np.array(mat2)).shape: logger.info(f"\n\t{test_multiplication.__name__} meets dim requirements") act = (np.matmul(mat1, mat2)).tolist() theo = matop.multiply(mat1, mat2) assert theo == act else: with pytest.raises(ValueError): logger.info( f"\n\t{test_multiplication.__name__} does not meet dim requirements" ) assert matop.subtract(mat1, mat2) @pytest.mark.mat_ops def test_scalar_multiply(): act = (3.5 * np.array(mat_a)).tolist() theo = matop.scalar_multiply(mat_a, 3.5) assert theo == act @pytest.mark.mat_ops def test_identity(): act = (np.identity(5)).tolist() theo = matop.identity(5) assert theo == act @pytest.mark.mat_ops @pytest.mark.parametrize("mat", [mat_a, mat_b, mat_c, mat_d, mat_e, mat_f]) def test_transpose(mat): if (np.array(mat)).shape < (2, 2): with pytest.raises(TypeError): logger.info(f"\n\t{test_transpose.__name__} returned integer") matop.transpose(mat) else: act = (np.transpose(mat)).tolist() theo = matop.transpose(mat, return_map=False) assert theo == act
""" Testing here assumes that numpy and linalg is ALWAYS correct!!!! If running from PyCharm you can place the following line in "Additional Arguments" for the pytest run configuration -vv -m mat_ops -p no:cacheprovider """ import logging # standard libraries import sys import numpy as np import pytest # type: ignore # Custom/local libraries from matrix import matrix_operation as matop mat_a = [[12, 10], [3, 9]] mat_b = [[3, 4], [7, 4]] mat_c = [[3, 0, 2], [2, 0, -2], [0, 1, 1]] mat_d = [[3, 0, -2], [2, 0, 2], [0, 1, 1]] mat_e = [[3, 0, 2], [2, 0, -2], [0, 1, 1], [2, 0, -2]] mat_f = [1] mat_h = [2] logger = logging.getLogger() logger.level = logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) @pytest.mark.mat_ops @pytest.mark.parametrize( ("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)] ) def test_addition(mat1, mat2): if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): with pytest.raises(TypeError): logger.info(f"\n\t{test_addition.__name__} returned integer") matop.add(mat1, mat2) elif (np.array(mat1)).shape == (np.array(mat2)).shape: logger.info(f"\n\t{test_addition.__name__} with same matrix dims") act = (np.array(mat1) + np.array(mat2)).tolist() theo = matop.add(mat1, mat2) assert theo == act else: with pytest.raises(ValueError): logger.info(f"\n\t{test_addition.__name__} with different matrix dims") matop.add(mat1, mat2) @pytest.mark.mat_ops @pytest.mark.parametrize( ("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)] ) def test_subtraction(mat1, mat2): if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): with pytest.raises(TypeError): logger.info(f"\n\t{test_subtraction.__name__} returned integer") matop.subtract(mat1, mat2) elif (np.array(mat1)).shape == (np.array(mat2)).shape: logger.info(f"\n\t{test_subtraction.__name__} with same matrix dims") act = (np.array(mat1) - np.array(mat2)).tolist() theo = matop.subtract(mat1, mat2) assert theo == act else: with pytest.raises(ValueError): logger.info(f"\n\t{test_subtraction.__name__} with different matrix dims") assert matop.subtract(mat1, mat2) @pytest.mark.mat_ops @pytest.mark.parametrize( ("mat1", "mat2"), [(mat_a, mat_b), (mat_c, mat_d), (mat_d, mat_e), (mat_f, mat_h)] ) def test_multiplication(mat1, mat2): if (np.array(mat1)).shape < (2, 2) or (np.array(mat2)).shape < (2, 2): logger.info(f"\n\t{test_multiplication.__name__} returned integer") with pytest.raises(TypeError): matop.add(mat1, mat2) elif (np.array(mat1)).shape == (np.array(mat2)).shape: logger.info(f"\n\t{test_multiplication.__name__} meets dim requirements") act = (np.matmul(mat1, mat2)).tolist() theo = matop.multiply(mat1, mat2) assert theo == act else: with pytest.raises(ValueError): logger.info( f"\n\t{test_multiplication.__name__} does not meet dim requirements" ) assert matop.subtract(mat1, mat2) @pytest.mark.mat_ops def test_scalar_multiply(): act = (3.5 * np.array(mat_a)).tolist() theo = matop.scalar_multiply(mat_a, 3.5) assert theo == act @pytest.mark.mat_ops def test_identity(): act = (np.identity(5)).tolist() theo = matop.identity(5) assert theo == act @pytest.mark.mat_ops @pytest.mark.parametrize("mat", [mat_a, mat_b, mat_c, mat_d, mat_e, mat_f]) def test_transpose(mat): if (np.array(mat)).shape < (2, 2): with pytest.raises(TypeError): logger.info(f"\n\t{test_transpose.__name__} returned integer") matop.transpose(mat) else: act = (np.transpose(mat)).tolist() theo = matop.transpose(mat, return_map=False) assert theo == act
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import numpy as np from PIL import Image def rgb2gray(rgb: np.array) -> np.array: """ Return gray image from rgb image >>> rgb2gray(np.array([[[127, 255, 0]]])) array([[187.6453]]) >>> rgb2gray(np.array([[[0, 0, 0]]])) array([[0.]]) >>> rgb2gray(np.array([[[2, 4, 1]]])) array([[3.0598]]) >>> rgb2gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]])) array([[159.0524, 90.0635, 117.6989]]) """ r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray2binary(gray: np.array) -> np.array: """ Return binary image from gray image >>> gray2binary(np.array([[127, 255, 0]])) array([[False, True, False]]) >>> gray2binary(np.array([[0]])) array([[False]]) >>> gray2binary(np.array([[26.2409, 4.9315, 1.4729]])) array([[False, False, False]]) >>> gray2binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]])) array([[False, True, False], [False, True, False], [False, True, False]]) """ return (127 < gray) & (gray <= 255) def erosion(image: np.array, kernel: np.array) -> np.array: """ Return eroded image >>> erosion(np.array([[True, True, False]]), np.array([[0, 1, 0]])) array([[False, False, False]]) >>> erosion(np.array([[True, False, False]]), np.array([[1, 1, 0]])) array([[False, False, False]]) """ output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image # Iterate over image & apply kernel for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation == 5) return output # kernel to be applied structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) if __name__ == "__main__": # read original image image = np.array(Image.open(r"..\image_data\lena.jpg")) # Apply erosion operation to a binary image output = erosion(gray2binary(rgb2gray(image)), structuring_element) # Save the output image pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_erosion.png")
import numpy as np from PIL import Image def rgb2gray(rgb: np.array) -> np.array: """ Return gray image from rgb image >>> rgb2gray(np.array([[[127, 255, 0]]])) array([[187.6453]]) >>> rgb2gray(np.array([[[0, 0, 0]]])) array([[0.]]) >>> rgb2gray(np.array([[[2, 4, 1]]])) array([[3.0598]]) >>> rgb2gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]])) array([[159.0524, 90.0635, 117.6989]]) """ r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray2binary(gray: np.array) -> np.array: """ Return binary image from gray image >>> gray2binary(np.array([[127, 255, 0]])) array([[False, True, False]]) >>> gray2binary(np.array([[0]])) array([[False]]) >>> gray2binary(np.array([[26.2409, 4.9315, 1.4729]])) array([[False, False, False]]) >>> gray2binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]])) array([[False, True, False], [False, True, False], [False, True, False]]) """ return (127 < gray) & (gray <= 255) def erosion(image: np.array, kernel: np.array) -> np.array: """ Return eroded image >>> erosion(np.array([[True, True, False]]), np.array([[0, 1, 0]])) array([[False, False, False]]) >>> erosion(np.array([[True, False, False]]), np.array([[1, 1, 0]])) array([[False, False, False]]) """ output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image # Iterate over image & apply kernel for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation == 5) return output # kernel to be applied structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) if __name__ == "__main__": # read original image image = np.array(Image.open(r"..\image_data\lena.jpg")) # Apply erosion operation to a binary image output = erosion(gray2binary(rgb2gray(image)), structuring_element) # Save the output image pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_erosion.png")
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations def median_of_two_arrays(nums1: list[float], nums2: list[float]) -> float: """ >>> median_of_two_arrays([1, 2], [3]) 2 >>> median_of_two_arrays([0, -1.1], [2.5, 1]) 0.5 >>> median_of_two_arrays([], [2.5, 1]) 1.75 >>> median_of_two_arrays([], [0]) 0 >>> median_of_two_arrays([], []) Traceback (most recent call last): ... IndexError: list index out of range """ all_numbers = sorted(nums1 + nums2) div, mod = divmod(len(all_numbers), 2) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() array_1 = [float(x) for x in input("Enter the elements of first array: ").split()] array_2 = [float(x) for x in input("Enter the elements of second array: ").split()] print(f"The median of two arrays is: {median_of_two_arrays(array_1, array_2)}")
from __future__ import annotations def median_of_two_arrays(nums1: list[float], nums2: list[float]) -> float: """ >>> median_of_two_arrays([1, 2], [3]) 2 >>> median_of_two_arrays([0, -1.1], [2.5, 1]) 0.5 >>> median_of_two_arrays([], [2.5, 1]) 1.75 >>> median_of_two_arrays([], [0]) 0 >>> median_of_two_arrays([], []) Traceback (most recent call last): ... IndexError: list index out of range """ all_numbers = sorted(nums1 + nums2) div, mod = divmod(len(all_numbers), 2) if mod == 1: return all_numbers[div] else: return (all_numbers[div] + all_numbers[div - 1]) / 2 if __name__ == "__main__": import doctest doctest.testmod() array_1 = [float(x) for x in input("Enter the elements of first array: ").split()] array_2 = [float(x) for x in input("Enter the elements of second array: ").split()] print(f"The median of two arrays is: {median_of_two_arrays(array_1, array_2)}")
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
[report] sort = Cover omit = .env/*
[report] sort = Cover omit = .env/*
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ xmulti = [] zmulti = [] z = 3 x = 5 temp = 1 while True: result = z * temp if result < n: zmulti.append(result) temp += 1 else: temp = 1 break while True: result = x * temp if result < n: xmulti.append(result) temp += 1 else: break collection = list(set(xmulti + zmulti)) return sum(collection) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ xmulti = [] zmulti = [] z = 3 x = 5 temp = 1 while True: result = z * temp if result < n: zmulti.append(result) temp += 1 else: temp = 1 break while True: result = x * temp if result < n: xmulti.append(result) temp += 1 else: break collection = list(set(xmulti + zmulti)) return sum(collection) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" A naive recursive implementation of 0-1 Knapsack Problem https://en.wikipedia.org/wiki/Knapsack_problem """ from __future__ import annotations def knapsack(capacity: int, weights: list[int], values: list[int], counter: int) -> int: """ Returns the maximum value that can be put in a knapsack of a capacity cap, whereby each weight w has a specific value val. >>> cap = 50 >>> val = [60, 100, 120] >>> w = [10, 20, 30] >>> c = len(val) >>> knapsack(cap, w, val, c) 220 The result is 220 cause the values of 100 and 120 got the weight of 50 which is the limit of the capacity. """ # Base Case if counter == 0 or capacity == 0: return 0 # If weight of the nth item is more than Knapsack of capacity, # then this item cannot be included in the optimal solution, # else return the maximum of two cases: # (1) nth item included # (2) not included if weights[counter - 1] > capacity: return knapsack(capacity, weights, values, counter - 1) else: left_capacity = capacity - weights[counter - 1] new_value_included = values[counter - 1] + knapsack( left_capacity, weights, values, counter - 1 ) without_new_value = knapsack(capacity, weights, values, counter - 1) return max(new_value_included, without_new_value) if __name__ == "__main__": import doctest doctest.testmod()
""" A naive recursive implementation of 0-1 Knapsack Problem https://en.wikipedia.org/wiki/Knapsack_problem """ from __future__ import annotations def knapsack(capacity: int, weights: list[int], values: list[int], counter: int) -> int: """ Returns the maximum value that can be put in a knapsack of a capacity cap, whereby each weight w has a specific value val. >>> cap = 50 >>> val = [60, 100, 120] >>> w = [10, 20, 30] >>> c = len(val) >>> knapsack(cap, w, val, c) 220 The result is 220 cause the values of 100 and 120 got the weight of 50 which is the limit of the capacity. """ # Base Case if counter == 0 or capacity == 0: return 0 # If weight of the nth item is more than Knapsack of capacity, # then this item cannot be included in the optimal solution, # else return the maximum of two cases: # (1) nth item included # (2) not included if weights[counter - 1] > capacity: return knapsack(capacity, weights, values, counter - 1) else: left_capacity = capacity - weights[counter - 1] new_value_included = values[counter - 1] + knapsack( left_capacity, weights, values, counter - 1 ) without_new_value = knapsack(capacity, weights, values, counter - 1) return max(new_value_included, without_new_value) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Problem 28 Url: https://projecteuler.net/problem=28 Statement: Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101. What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? """ from math import ceil def solution(n: int = 1001) -> int: """Returns the sum of the numbers on the diagonals in a n by n spiral formed in the same way. >>> solution(1001) 669171001 >>> solution(500) 82959497 >>> solution(100) 651897 >>> solution(50) 79697 >>> solution(10) 537 """ total = 1 for i in range(1, int(ceil(n / 2.0))): odd = 2 * i + 1 even = 2 * i total = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: n = int(sys.argv[1]) print(solution(n)) except ValueError: print("Invalid entry - please enter a number")
""" Problem 28 Url: https://projecteuler.net/problem=28 Statement: Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13 It can be verified that the sum of the numbers on the diagonals is 101. What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way? """ from math import ceil def solution(n: int = 1001) -> int: """Returns the sum of the numbers on the diagonals in a n by n spiral formed in the same way. >>> solution(1001) 669171001 >>> solution(500) 82959497 >>> solution(100) 651897 >>> solution(50) 79697 >>> solution(10) 537 """ total = 1 for i in range(1, int(ceil(n / 2.0))): odd = 2 * i + 1 even = 2 * i total = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: n = int(sys.argv[1]) print(solution(n)) except ValueError: print("Invalid entry - please enter a number")
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] 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("Enter key [2-%s]: " % (len(message) - 1))) mode = input("Encryption/Decryption [e/d]: ") if mode.lower().startswith("e"): text = encryptMessage(key, message) elif mode.lower().startswith("d"): text = decryptMessage(key, message) # Append pipe symbol (vertical bar) to identify spaces at the end. print("Output:\n%s" % (text + "|")) def encryptMessage(key: int, message: str) -> str: """ >>> encryptMessage(6, 'Harshil Darji') 'Hlia rDsahrij' """ cipherText = [""] * key for col in range(key): pointer = col while pointer < len(message): cipherText[col] += message[pointer] pointer += key return "".join(cipherText) def decryptMessage(key: int, message: str) -> str: """ >>> decryptMessage(6, 'Hlia rDsahrij') 'Harshil Darji' """ numCols = math.ceil(len(message) / key) numRows = key numShadedBoxes = (numCols * numRows) - len(message) plainText = [""] * numCols col = 0 row = 0 for symbol in message: plainText[col] += symbol col += 1 if ( (col == numCols) or (col == numCols - 1) and (row >= numRows - numShadedBoxes) ): col = 0 row += 1 return "".join(plainText) 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("Enter key [2-%s]: " % (len(message) - 1))) mode = input("Encryption/Decryption [e/d]: ") if mode.lower().startswith("e"): text = encryptMessage(key, message) elif mode.lower().startswith("d"): text = decryptMessage(key, message) # Append pipe symbol (vertical bar) to identify spaces at the end. print("Output:\n%s" % (text + "|")) def encryptMessage(key: int, message: str) -> str: """ >>> encryptMessage(6, 'Harshil Darji') 'Hlia rDsahrij' """ cipherText = [""] * key for col in range(key): pointer = col while pointer < len(message): cipherText[col] += message[pointer] pointer += key return "".join(cipherText) def decryptMessage(key: int, message: str) -> str: """ >>> decryptMessage(6, 'Hlia rDsahrij') 'Harshil Darji' """ numCols = math.ceil(len(message) / key) numRows = key numShadedBoxes = (numCols * numRows) - len(message) plainText = [""] * numCols col = 0 row = 0 for symbol in message: plainText[col] += symbol col += 1 if ( (col == numCols) or (col == numCols - 1) and (row >= numRows - numShadedBoxes) ): col = 0 row += 1 return "".join(plainText) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
6,236
Upgrade GitHub Actions
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
cclauss
"2022-07-06T20:10:25Z"
"2022-07-07T03:25:25Z"
9135a1f41192ebe1d835282a1465dc284359d95c
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
Upgrade GitHub Actions. ### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Upgrade automated testing ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# https://en.wikipedia.org/wiki/Ohm%27s_law from __future__ import annotations def ohms_law(voltage: float, current: float, resistance: float) -> dict[str, float]: """ Apply Ohm's Law, on any two given electrical values, which can be voltage, current, and resistance, and then in a Python dict return name/value pair of the zero value. >>> ohms_law(voltage=10, resistance=5, current=0) {'current': 2.0} >>> ohms_law(voltage=0, current=0, resistance=10) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> ohms_law(voltage=0, current=1, resistance=-2) Traceback (most recent call last): ... ValueError: Resistance cannot be negative >>> ohms_law(resistance=0, voltage=-10, current=1) {'resistance': -10.0} >>> ohms_law(voltage=0, current=-1.5, resistance=2) {'voltage': -3.0} """ if (voltage, current, resistance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance < 0: raise ValueError("Resistance cannot be negative") if voltage == 0: return {"voltage": float(current * resistance)} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
# https://en.wikipedia.org/wiki/Ohm%27s_law from __future__ import annotations def ohms_law(voltage: float, current: float, resistance: float) -> dict[str, float]: """ Apply Ohm's Law, on any two given electrical values, which can be voltage, current, and resistance, and then in a Python dict return name/value pair of the zero value. >>> ohms_law(voltage=10, resistance=5, current=0) {'current': 2.0} >>> ohms_law(voltage=0, current=0, resistance=10) Traceback (most recent call last): ... ValueError: One and only one argument must be 0 >>> ohms_law(voltage=0, current=1, resistance=-2) Traceback (most recent call last): ... ValueError: Resistance cannot be negative >>> ohms_law(resistance=0, voltage=-10, current=1) {'resistance': -10.0} >>> ohms_law(voltage=0, current=-1.5, resistance=2) {'voltage': -3.0} """ if (voltage, current, resistance).count(0) != 1: raise ValueError("One and only one argument must be 0") if resistance < 0: raise ValueError("Resistance cannot be negative") if voltage == 0: return {"voltage": float(current * resistance)} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0") if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
""" Checks if a system of forces is in static equilibrium. """ from __future__ import annotations from numpy import array, cos, cross, float64, radians, sin from numpy.typing import NDArray def polar_force( magnitude: float, angle: float, radian_mode: bool = False ) -> list[float]: """ Resolves force along rectangular components. (force, angle) => (force_x, force_y) >>> import math >>> force = polar_force(10, 45) >>> math.isclose(force[0], 7.071067811865477) True >>> math.isclose(force[1], 7.0710678118654755) True >>> polar_force(10, 3.14, radian_mode=True) [-9.999987317275396, 0.01592652916486828] """ if radian_mode: return [magnitude * cos(angle), magnitude * sin(angle)] return [magnitude * cos(radians(angle)), magnitude * sin(radians(angle))] def in_static_equilibrium( forces: NDArray[float64], location: NDArray[float64], eps: float = 10**-1 ) -> bool: """ Check if a system is in equilibrium. It takes two numpy.array objects. forces ==> [ [force1_x, force1_y], [force2_x, force2_y], ....] location ==> [ [x1, y1], [x2, y2], ....] >>> force = array([[1, 1], [-1, 2]]) >>> location = array([[1, 0], [10, 0]]) >>> in_static_equilibrium(force, location) False """ # summation of moments is zero moments: NDArray[float64] = cross(location, forces) sum_moments: float = sum(moments) return abs(sum_moments) < eps if __name__ == "__main__": # Test to check if it works forces = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) location: NDArray[float64] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg forces = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) location = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg forces = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]]) location = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
""" Checks if a system of forces is in static equilibrium. """ from __future__ import annotations from numpy import array, cos, cross, float64, radians, sin from numpy.typing import NDArray def polar_force( magnitude: float, angle: float, radian_mode: bool = False ) -> list[float]: """ Resolves force along rectangular components. (force, angle) => (force_x, force_y) >>> import math >>> force = polar_force(10, 45) >>> math.isclose(force[0], 7.071067811865477) True >>> math.isclose(force[1], 7.0710678118654755) True >>> force = polar_force(10, 3.14, radian_mode=True) >>> math.isclose(force[0], -9.999987317275396) True >>> math.isclose(force[1], 0.01592652916486828) True """ if radian_mode: return [magnitude * cos(angle), magnitude * sin(angle)] return [magnitude * cos(radians(angle)), magnitude * sin(radians(angle))] def in_static_equilibrium( forces: NDArray[float64], location: NDArray[float64], eps: float = 10**-1 ) -> bool: """ Check if a system is in equilibrium. It takes two numpy.array objects. forces ==> [ [force1_x, force1_y], [force2_x, force2_y], ....] location ==> [ [x1, y1], [x2, y2], ....] >>> force = array([[1, 1], [-1, 2]]) >>> location = array([[1, 0], [10, 0]]) >>> in_static_equilibrium(force, location) False """ # summation of moments is zero moments: NDArray[float64] = cross(location, forces) sum_moments: float = sum(moments) return abs(sum_moments) < eps if __name__ == "__main__": # Test to check if it works forces = array( [ polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90), ] ) location: NDArray[float64] = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg forces = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) location = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg forces = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]]) location = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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://github.com/rupansh/QuantumComputing/blob/master/rippleadd.py # https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder # https://en.wikipedia.org/wiki/Controlled_NOT_gate from qiskit import Aer, QuantumCircuit, execute from qiskit.providers import BaseBackend def store_two_classics(val1: int, val2: int) -> tuple[QuantumCircuit, str, str]: """ Generates a Quantum Circuit which stores two classical integers Returns the circuit and binary representation of the integers """ x, y = bin(val1)[2:], bin(val2)[2:] # Remove leading '0b' # Ensure that both strings are of the same length if len(x) > len(y): y = y.zfill(len(x)) else: x = x.zfill(len(y)) # We need (3 * number of bits in the larger number)+1 qBits # The second parameter is the number of classical registers, to measure the result circuit = QuantumCircuit((len(x) * 3) + 1, len(x) + 1) # We are essentially "not-ing" the bits that are 1 # Reversed because its easier to perform ops on more significant bits for i in range(len(x)): if x[::-1][i] == "1": circuit.x(i) for j in range(len(y)): if y[::-1][j] == "1": circuit.x(len(x) + j) return circuit, x, y def full_adder( circuit: QuantumCircuit, input1_loc: int, input2_loc: int, carry_in: int, carry_out: int, ): """ Quantum Equivalent of a Full Adder Circuit CX/CCX is like 2-way/3-way XOR """ circuit.ccx(input1_loc, input2_loc, carry_out) circuit.cx(input1_loc, input2_loc) circuit.ccx(input2_loc, carry_in, carry_out) circuit.cx(input2_loc, carry_in) circuit.cx(input1_loc, input2_loc) # The default value for **backend** is the result of a function call which is not # normally recommended and causes flake8-bugbear to raise a B008 error. However, # in this case, this is accptable because `Aer.get_backend()` is called when the # function is defined and that same backend is then reused for all function calls. def ripple_adder( val1: int, val2: int, backend: BaseBackend = Aer.get_backend("qasm_simulator"), # noqa: B008 ) -> int: """ Quantum Equivalent of a Ripple Adder Circuit Uses qasm_simulator backend by default Currently only adds 'emulated' Classical Bits but nothing prevents us from doing this with hadamard'd bits :) Only supports adding positive integers >>> ripple_adder(3, 4) 7 >>> ripple_adder(10, 4) 14 >>> ripple_adder(-1, 10) Traceback (most recent call last): ... ValueError: Both Integers must be positive! """ if val1 < 0 or val2 < 0: raise ValueError("Both Integers must be positive!") # Store the Integers circuit, x, y = store_two_classics(val1, val2) """ We are essentially using each bit of x & y respectively as full_adder's input the carry_input is used from the previous circuit (for circuit num > 1) the carry_out is just below carry_input because it will be essentially the carry_input for the next full_adder """ for i in range(len(x)): full_adder(circuit, i, len(x) + i, len(x) + len(y) + i, len(x) + len(y) + i + 1) circuit.barrier() # Optional, just for aesthetics # Measure the resultant qBits for i in range(len(x) + 1): circuit.measure([(len(x) * 2) + i], [i]) res = execute(circuit, backend, shots=1).result() # The result is in binary. Convert it back to int return int(list(res.get_counts())[0], 2) if __name__ == "__main__": import doctest doctest.testmod()
# https://github.com/rupansh/QuantumComputing/blob/master/rippleadd.py # https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder # https://en.wikipedia.org/wiki/Controlled_NOT_gate from qiskit import Aer, QuantumCircuit, execute from qiskit.providers import Backend def store_two_classics(val1: int, val2: int) -> tuple[QuantumCircuit, str, str]: """ Generates a Quantum Circuit which stores two classical integers Returns the circuit and binary representation of the integers """ x, y = bin(val1)[2:], bin(val2)[2:] # Remove leading '0b' # Ensure that both strings are of the same length if len(x) > len(y): y = y.zfill(len(x)) else: x = x.zfill(len(y)) # We need (3 * number of bits in the larger number)+1 qBits # The second parameter is the number of classical registers, to measure the result circuit = QuantumCircuit((len(x) * 3) + 1, len(x) + 1) # We are essentially "not-ing" the bits that are 1 # Reversed because its easier to perform ops on more significant bits for i in range(len(x)): if x[::-1][i] == "1": circuit.x(i) for j in range(len(y)): if y[::-1][j] == "1": circuit.x(len(x) + j) return circuit, x, y def full_adder( circuit: QuantumCircuit, input1_loc: int, input2_loc: int, carry_in: int, carry_out: int, ): """ Quantum Equivalent of a Full Adder Circuit CX/CCX is like 2-way/3-way XOR """ circuit.ccx(input1_loc, input2_loc, carry_out) circuit.cx(input1_loc, input2_loc) circuit.ccx(input2_loc, carry_in, carry_out) circuit.cx(input2_loc, carry_in) circuit.cx(input1_loc, input2_loc) # The default value for **backend** is the result of a function call which is not # normally recommended and causes flake8-bugbear to raise a B008 error. However, # in this case, this is accptable because `Aer.get_backend()` is called when the # function is defined and that same backend is then reused for all function calls. def ripple_adder( val1: int, val2: int, backend: Backend = Aer.get_backend("qasm_simulator"), # noqa: B008 ) -> int: """ Quantum Equivalent of a Ripple Adder Circuit Uses qasm_simulator backend by default Currently only adds 'emulated' Classical Bits but nothing prevents us from doing this with hadamard'd bits :) Only supports adding positive integers >>> ripple_adder(3, 4) 7 >>> ripple_adder(10, 4) 14 >>> ripple_adder(-1, 10) Traceback (most recent call last): ... ValueError: Both Integers must be positive! """ if val1 < 0 or val2 < 0: raise ValueError("Both Integers must be positive!") # Store the Integers circuit, x, y = store_two_classics(val1, val2) """ We are essentially using each bit of x & y respectively as full_adder's input the carry_input is used from the previous circuit (for circuit num > 1) the carry_out is just below carry_input because it will be essentially the carry_input for the next full_adder """ for i in range(len(x)): full_adder(circuit, i, len(x) + i, len(x) + len(y) + i, len(x) + len(y) + i + 1) circuit.barrier() # Optional, just for aesthetics # Measure the resultant qBits for i in range(len(x) + 1): circuit.measure([(len(x) * 2) + i], [i]) res = execute(circuit, backend, shots=1).result() # The result is in binary. Convert it back to int return int(list(res.get_counts())[0], 2) if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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 hamming_distance(string1: str, string2: str) -> int: """Calculate the Hamming distance between two equal length strings In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. https://en.wikipedia.org/wiki/Hamming_distance Args: string1 (str): Sequence 1 string2 (str): Sequence 2 Returns: int: Hamming distance >>> hamming_distance("python", "python") 0 >>> hamming_distance("karolin", "kathrin") 3 >>> hamming_distance("00000", "11111") 5 >>> hamming_distance("karolin", "kath") ValueError: String lengths must match! """ if len(string1) != len(string2): raise ValueError("String lengths must match!") count = 0 for char1, char2 in zip(string1, string2): if char1 != char2: count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
def hamming_distance(string1: str, string2: str) -> int: """Calculate the Hamming distance between two equal length strings In information theory, the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. https://en.wikipedia.org/wiki/Hamming_distance Args: string1 (str): Sequence 1 string2 (str): Sequence 2 Returns: int: Hamming distance >>> hamming_distance("python", "python") 0 >>> hamming_distance("karolin", "kathrin") 3 >>> hamming_distance("00000", "11111") 5 >>> hamming_distance("karolin", "kath") Traceback (most recent call last): ... ValueError: String lengths must match! """ if len(string1) != len(string2): raise ValueError("String lengths must match!") count = 0 for char1, char2 in zip(string1, string2): if char1 != char2: count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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 random class Point: def __init__(self, x: float, y: float) -> None: self.x = x self.y = y def is_in_unit_circle(self) -> bool: """ True, if the point lies in the unit circle False, otherwise """ return (self.x**2 + self.y**2) <= 1 @classmethod def random_unit_square(cls): """ Generates a point randomly drawn from the unit square [0, 1) x [0, 1). """ return cls(x=random.random(), y=random.random()) def estimate_pi(number_of_simulations: int) -> float: """ Generates an estimate of the mathematical constant PI. See https://en.wikipedia.org/wiki/Monte_Carlo_method#Overview The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from the unit square [0, 1) x [0, 1). The probability that U lies in the unit circle is: P[U in unit circle] = 1/4 PI and therefore PI = 4 * P[U in unit circle] We can get an estimate of the probability P[U in unit circle]. See https://en.wikipedia.org/wiki/Empirical_probability by: 1. Draw a point uniformly from the unit square. 2. Repeat the first step n times and count the number of points in the unit circle, which is called m. 3. An estimate of P[U in unit circle] is m/n """ if number_of_simulations < 1: raise ValueError("At least one simulation is necessary to estimate PI.") number_in_unit_circle = 0 for simulation_index in range(number_of_simulations): random_point = Point.random_unit_square() if random_point.is_in_unit_circle(): number_in_unit_circle += 1 return 4 * number_in_unit_circle / number_of_simulations if __name__ == "__main__": # import doctest # doctest.testmod() from math import pi prompt = "Please enter the desired number of Monte Carlo simulations: " my_pi = estimate_pi(int(input(prompt).strip())) print(f"An estimate of PI is {my_pi} with an error of {abs(my_pi - pi)}")
import random class Point: def __init__(self, x: float, y: float) -> None: self.x = x self.y = y def is_in_unit_circle(self) -> bool: """ True, if the point lies in the unit circle False, otherwise """ return (self.x**2 + self.y**2) <= 1 @classmethod def random_unit_square(cls): """ Generates a point randomly drawn from the unit square [0, 1) x [0, 1). """ return cls(x=random.random(), y=random.random()) def estimate_pi(number_of_simulations: int) -> float: """ Generates an estimate of the mathematical constant PI. See https://en.wikipedia.org/wiki/Monte_Carlo_method#Overview The estimate is generated by Monte Carlo simulations. Let U be uniformly drawn from the unit square [0, 1) x [0, 1). The probability that U lies in the unit circle is: P[U in unit circle] = 1/4 PI and therefore PI = 4 * P[U in unit circle] We can get an estimate of the probability P[U in unit circle]. See https://en.wikipedia.org/wiki/Empirical_probability by: 1. Draw a point uniformly from the unit square. 2. Repeat the first step n times and count the number of points in the unit circle, which is called m. 3. An estimate of P[U in unit circle] is m/n """ if number_of_simulations < 1: raise ValueError("At least one simulation is necessary to estimate PI.") number_in_unit_circle = 0 for simulation_index in range(number_of_simulations): random_point = Point.random_unit_square() if random_point.is_in_unit_circle(): number_in_unit_circle += 1 return 4 * number_in_unit_circle / number_of_simulations if __name__ == "__main__": # import doctest # doctest.testmod() from math import pi prompt = "Please enter the desired number of Monte Carlo simulations: " my_pi = estimate_pi(int(input(prompt).strip())) print(f"An estimate of PI is {my_pi} with an error of {abs(my_pi - pi)}")
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
""" Problem 14: https://projecteuler.net/problem=14 Problem Statement: The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? """ def solution(n: int = 1000000) -> int: """Returns the number under n that generates the longest sequence using the formula: n → n/2 (n is even) n → 3n + 1 (n is odd) >>> solution(1000000) 837799 >>> solution(200) 171 >>> solution(5000) 3711 >>> solution(15000) 13255 """ largest_number = 1 pre_counter = 1 counters = {1: 1} for input1 in range(2, n): counter = 0 number = input1 while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: number = (3 * number) + 1 counter += 1 if input1 not in counters: counters[input1] = counter if counter > pre_counter: largest_number = input1 pre_counter = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
""" Problem 14: https://projecteuler.net/problem=14 Problem Statement: The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. Which starting number, under one million, produces the longest chain? """ def solution(n: int = 1000000) -> int: """Returns the number under n that generates the longest sequence using the formula: n → n/2 (n is even) n → 3n + 1 (n is odd) >>> solution(1000000) 837799 >>> solution(200) 171 >>> solution(5000) 3711 >>> solution(15000) 13255 """ largest_number = 1 pre_counter = 1 counters = {1: 1} for input1 in range(2, n): counter = 0 number = input1 while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: number = (3 * number) + 1 counter += 1 if input1 not in counters: counters[input1] = counter if counter > pre_counter: largest_number = input1 pre_counter = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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 json import os import re import sys import urllib.request import requests from bs4 import BeautifulSoup headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } def download_images_from_google_query(query: str = "dhaka", max_images: int = 5) -> int: """Searches google using the provided query term and downloads the images in a folder. Args: query : The image search term to be provided by the user. Defaults to "dhaka". image_numbers : [description]. Defaults to 5. Returns: The number of images successfully downloaded. # Comment out slow (4.20s call) doctests # >>> download_images_from_google_query() 5 # >>> download_images_from_google_query("potato") 5 """ max_images = min(max_images, 50) # Prevent abuse! params = { "q": query, "tbm": "isch", "hl": "en", "ijn": "0", } html = requests.get("https://www.google.com/search", params=params, headers=headers) soup = BeautifulSoup(html.text, "html.parser") matched_images_data = "".join( re.findall(r"AF_initDataCallback\(([^<]+)\);", str(soup.select("script"))) ) matched_images_data_fix = json.dumps(matched_images_data) matched_images_data_json = json.loads(matched_images_data_fix) matched_google_image_data = re.findall( r"\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",", matched_images_data_json, ) if not matched_google_image_data: return 0 removed_matched_google_images_thumbnails = re.sub( r"\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]", "", str(matched_google_image_data), ) matched_google_full_resolution_images = re.findall( r"(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]", removed_matched_google_images_thumbnails, ) for index, fixed_full_res_image in enumerate(matched_google_full_resolution_images): if index >= max_images: return index original_size_img_not_fixed = bytes(fixed_full_res_image, "ascii").decode( "unicode-escape" ) original_size_img = bytes(original_size_img_not_fixed, "ascii").decode( "unicode-escape" ) opener = urllib.request.build_opener() opener.addheaders = [ ( "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582", ) ] urllib.request.install_opener(opener) path_name = f"query_{query.replace(' ', '_')}" if not os.path.exists(path_name): os.makedirs(path_name) urllib.request.urlretrieve( original_size_img, f"{path_name}/original_size_img_{index}.jpg" ) return index if __name__ == "__main__": try: image_count = download_images_from_google_query(sys.argv[1]) print(f"{image_count} images were downloaded to disk.") except IndexError: print("Please provide a search term.") raise
import json import os import re import sys import urllib.request import requests from bs4 import BeautifulSoup headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } def download_images_from_google_query(query: str = "dhaka", max_images: int = 5) -> int: """Searches google using the provided query term and downloads the images in a folder. Args: query : The image search term to be provided by the user. Defaults to "dhaka". image_numbers : [description]. Defaults to 5. Returns: The number of images successfully downloaded. # Comment out slow (4.20s call) doctests # >>> download_images_from_google_query() 5 # >>> download_images_from_google_query("potato") 5 """ max_images = min(max_images, 50) # Prevent abuse! params = { "q": query, "tbm": "isch", "hl": "en", "ijn": "0", } html = requests.get("https://www.google.com/search", params=params, headers=headers) soup = BeautifulSoup(html.text, "html.parser") matched_images_data = "".join( re.findall(r"AF_initDataCallback\(([^<]+)\);", str(soup.select("script"))) ) matched_images_data_fix = json.dumps(matched_images_data) matched_images_data_json = json.loads(matched_images_data_fix) matched_google_image_data = re.findall( r"\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",", matched_images_data_json, ) if not matched_google_image_data: return 0 removed_matched_google_images_thumbnails = re.sub( r"\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]", "", str(matched_google_image_data), ) matched_google_full_resolution_images = re.findall( r"(?:'|,),\[\"(https:|http.*?)\",\d+,\d+\]", removed_matched_google_images_thumbnails, ) for index, fixed_full_res_image in enumerate(matched_google_full_resolution_images): if index >= max_images: return index original_size_img_not_fixed = bytes(fixed_full_res_image, "ascii").decode( "unicode-escape" ) original_size_img = bytes(original_size_img_not_fixed, "ascii").decode( "unicode-escape" ) opener = urllib.request.build_opener() opener.addheaders = [ ( "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582", ) ] urllib.request.install_opener(opener) path_name = f"query_{query.replace(' ', '_')}" if not os.path.exists(path_name): os.makedirs(path_name) urllib.request.urlretrieve( original_size_img, f"{path_name}/original_size_img_{index}.jpg" ) return index if __name__ == "__main__": try: image_count = download_images_from_google_query(sys.argv[1]) print(f"{image_count} images were downloaded to disk.") except IndexError: print("Please provide a search term.") raise
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
# This Will Check Whether A Given Password Is Strong Or Not # It Follows The Rule that Length Of Password Should Be At Least 8 Characters # And At Least 1 Lower, 1 Upper, 1 Number And 1 Special Character from string import ascii_lowercase, ascii_uppercase, digits, punctuation def strong_password_detector(password: str, min_length: int = 8) -> str: """ >>> strong_password_detector('Hwea7$2!') 'This is a strong Password' >>> strong_password_detector('Sh0r1') 'Your Password must be at least 8 characters long' >>> strong_password_detector('Hello123') 'Password should contain UPPERCASE, lowercase, numbers, special characters' >>> strong_password_detector('Hello1238udfhiaf038fajdvjjf!jaiuFhkqi1') 'This is a strong Password' >>> strong_password_detector(0) 'Your Password must be at least 8 characters long' """ if len(str(password)) < 8: return "Your Password must be at least 8 characters long" upper = any(char in ascii_uppercase for char in password) lower = any(char in ascii_lowercase for char in password) num = any(char in digits for char in password) spec_char = any(char in punctuation for char in password) if upper and lower and num and spec_char: return "This is a strong Password" else: return ( "Password should contain UPPERCASE, lowercase, " "numbers, special characters" ) if __name__ == "__main__": import doctest doctest.testmod()
# This Will Check Whether A Given Password Is Strong Or Not # It Follows The Rule that Length Of Password Should Be At Least 8 Characters # And At Least 1 Lower, 1 Upper, 1 Number And 1 Special Character from string import ascii_lowercase, ascii_uppercase, digits, punctuation def strong_password_detector(password: str, min_length: int = 8) -> str: """ >>> strong_password_detector('Hwea7$2!') 'This is a strong Password' >>> strong_password_detector('Sh0r1') 'Your Password must be at least 8 characters long' >>> strong_password_detector('Hello123') 'Password should contain UPPERCASE, lowercase, numbers, special characters' >>> strong_password_detector('Hello1238udfhiaf038fajdvjjf!jaiuFhkqi1') 'This is a strong Password' >>> strong_password_detector(0) 'Your Password must be at least 8 characters long' """ if len(str(password)) < 8: return "Your Password must be at least 8 characters long" upper = any(char in ascii_uppercase for char in password) lower = any(char in ascii_lowercase for char in password) num = any(char in digits for char in password) spec_char = any(char in punctuation for char in password) if upper and lower and num and spec_char: return "This is a strong Password" else: return ( "Password should contain UPPERCASE, lowercase, " "numbers, special characters" ) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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 random import randint from tempfile import TemporaryFile import numpy as np def _inPlaceQuickSort(A, start, end): count = 0 if start < end: pivot = randint(start, end) temp = A[end] A[end] = A[pivot] A[pivot] = temp p, count = _inPlacePartition(A, start, end) count += _inPlaceQuickSort(A, start, p - 1) count += _inPlaceQuickSort(A, p + 1, end) return count def _inPlacePartition(A, start, end): count = 0 pivot = randint(start, end) temp = A[end] A[end] = A[pivot] A[pivot] = temp newPivotIndex = start - 1 for index in range(start, end): count += 1 if A[index] < A[end]: # check if current val is less than pivot value newPivotIndex = newPivotIndex + 1 temp = A[newPivotIndex] A[newPivotIndex] = A[index] A[index] = temp temp = A[newPivotIndex + 1] A[newPivotIndex + 1] = A[end] A[end] = temp return newPivotIndex + 1, count outfile = TemporaryFile() p = 100 # 1000 elements are to be sorted mu, sigma = 0, 1 # mean and standard deviation X = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array M = np.load(outfile) r = len(M) - 1 z = _inPlaceQuickSort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
from random import randint from tempfile import TemporaryFile import numpy as np def _inPlaceQuickSort(A, start, end): count = 0 if start < end: pivot = randint(start, end) temp = A[end] A[end] = A[pivot] A[pivot] = temp p, count = _inPlacePartition(A, start, end) count += _inPlaceQuickSort(A, start, p - 1) count += _inPlaceQuickSort(A, p + 1, end) return count def _inPlacePartition(A, start, end): count = 0 pivot = randint(start, end) temp = A[end] A[end] = A[pivot] A[pivot] = temp newPivotIndex = start - 1 for index in range(start, end): count += 1 if A[index] < A[end]: # check if current val is less than pivot value newPivotIndex = newPivotIndex + 1 temp = A[newPivotIndex] A[newPivotIndex] = A[index] A[index] = temp temp = A[newPivotIndex + 1] A[newPivotIndex + 1] = A[end] A[end] = temp return newPivotIndex + 1, count outfile = TemporaryFile() p = 100 # 1000 elements are to be sorted mu, sigma = 0, 1 # mean and standard deviation X = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array M = np.load(outfile) r = len(M) - 1 z = _inPlaceQuickSort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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 PIL import Image def change_brightness(img: Image, level: float) -> Image: """ Change the brightness of a PIL Image to a given level. """ def brightness(c: int) -> float: """ Fundamental Transformation/Operation that'll be performed on every bit. """ return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("level must be between -255.0 (black) and 255.0 (white)") return img.point(brightness) if __name__ == "__main__": # Load image with Image.open("image_data/lena.jpg") as img: # Change brightness to 100 brigt_img = change_brightness(img, 100) brigt_img.save("image_data/lena_brightness.png", format="png")
from PIL import Image def change_brightness(img: Image, level: float) -> Image: """ Change the brightness of a PIL Image to a given level. """ def brightness(c: int) -> float: """ Fundamental Transformation/Operation that'll be performed on every bit. """ return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError("level must be between -255.0 (black) and 255.0 (white)") return img.point(brightness) if __name__ == "__main__": # Load image with Image.open("image_data/lena.jpg") as img: # Change brightness to 100 brigt_img = change_brightness(img, 100) brigt_img.save("image_data/lena_brightness.png", format="png")
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
""" Perceptron w = w + N * (d(k) - y) * x(k) Using perceptron network for oil analysis, with Measuring of 3 parameters that represent chemical characteristics we can classify the oil, in p1 or p2 p1 = -1 p2 = 1 """ import random class Perceptron: def __init__( self, sample: list[list[float]], target: list[int], learning_rate: float = 0.01, epoch_number: int = 1000, bias: float = -1, ) -> None: """ Initializes a Perceptron network for oil analysis :param sample: sample dataset of 3 parameters with shape [30,3] :param target: variable for classification with two possible states -1 or 1 :param learning_rate: learning rate used in optimizing. :param epoch_number: number of epochs to train network on. :param bias: bias value for the network. >>> p = Perceptron([], (0, 1, 2)) Traceback (most recent call last): ... ValueError: Sample data can not be empty >>> p = Perceptron(([0], 1, 2), []) Traceback (most recent call last): ... ValueError: Target data can not be empty >>> p = Perceptron(([0], 1, 2), (0, 1)) Traceback (most recent call last): ... ValueError: Sample data and Target data do not have matching lengths """ self.sample = sample if len(self.sample) == 0: raise ValueError("Sample data can not be empty") self.target = target if len(self.target) == 0: raise ValueError("Target data can not be empty") if len(self.sample) != len(self.target): raise ValueError("Sample data and Target data do not have matching lengths") self.learning_rate = learning_rate self.epoch_number = epoch_number self.bias = bias self.number_sample = len(sample) self.col_sample = len(sample[0]) # number of columns in dataset self.weight: list = [] def training(self) -> None: """ Trains perceptron for epochs <= given number of epochs :return: None >>> data = [[2.0149, 0.6192, 10.9263]] >>> targets = [-1] >>> perceptron = Perceptron(data,targets) >>> perceptron.training() # doctest: +ELLIPSIS ('\\nEpoch:\\n', ...) ... """ for sample in self.sample: sample.insert(0, self.bias) for i in range(self.col_sample): self.weight.append(random.random()) self.weight.insert(0, self.bias) epoch_count = 0 while True: has_misclassified = False for i in range(self.number_sample): u = 0 for j in range(self.col_sample + 1): u = u + self.weight[j] * self.sample[i][j] y = self.sign(u) if y != self.target[i]: for j in range(self.col_sample + 1): self.weight[j] = ( self.weight[j] + self.learning_rate * (self.target[i] - y) * self.sample[i][j] ) has_misclassified = True # print('Epoch: \n',epoch_count) epoch_count = epoch_count + 1 # if you want control the epoch or just by error if not has_misclassified: print(("\nEpoch:\n", epoch_count)) print("------------------------\n") # if epoch_count > self.epoch_number or not error: break def sort(self, sample: list[float]) -> None: """ :param sample: example row to classify as P1 or P2 :return: None >>> data = [[2.0149, 0.6192, 10.9263]] >>> targets = [-1] >>> perceptron = Perceptron(data,targets) >>> perceptron.training() # doctest: +ELLIPSIS ('\\nEpoch:\\n', ...) ... >>> perceptron.sort([-0.6508, 0.1097, 4.0009]) # doctest: +ELLIPSIS ('Sample: ', ...) classification: P... """ if len(self.sample) == 0: raise ValueError("Sample data can not be empty") sample.insert(0, self.bias) u = 0 for i in range(self.col_sample + 1): u = u + self.weight[i] * sample[i] y = self.sign(u) if y == -1: print(("Sample: ", sample)) print("classification: P1") else: print(("Sample: ", sample)) print("classification: P2") def sign(self, u: float) -> int: """ threshold function for classification :param u: input number :return: 1 if the input is greater than 0, otherwise -1 >>> data = [[0],[-0.5],[0.5]] >>> targets = [1,-1,1] >>> perceptron = Perceptron(data,targets) >>> perceptron.sign(0) 1 >>> perceptron.sign(-0.5) -1 >>> perceptron.sign(0.5) 1 """ return 1 if u >= 0 else -1 samples = [ [-0.6508, 0.1097, 4.0009], [-1.4492, 0.8896, 4.4005], [2.0850, 0.6876, 12.0710], [0.2626, 1.1476, 7.7985], [0.6418, 1.0234, 7.0427], [0.2569, 0.6730, 8.3265], [1.1155, 0.6043, 7.4446], [0.0914, 0.3399, 7.0677], [0.0121, 0.5256, 4.6316], [-0.0429, 0.4660, 5.4323], [0.4340, 0.6870, 8.2287], [0.2735, 1.0287, 7.1934], [0.4839, 0.4851, 7.4850], [0.4089, -0.1267, 5.5019], [1.4391, 0.1614, 8.5843], [-0.9115, -0.1973, 2.1962], [0.3654, 1.0475, 7.4858], [0.2144, 0.7515, 7.1699], [0.2013, 1.0014, 6.5489], [0.6483, 0.2183, 5.8991], [-0.1147, 0.2242, 7.2435], [-0.7970, 0.8795, 3.8762], [-1.0625, 0.6366, 2.4707], [0.5307, 0.1285, 5.6883], [-1.2200, 0.7777, 1.7252], [0.3957, 0.1076, 5.6623], [-0.1013, 0.5989, 7.1812], [2.4482, 0.9455, 11.2095], [2.0149, 0.6192, 10.9263], [0.2012, 0.2611, 5.4631], ] exit = [ -1, -1, -1, 1, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, 1, 1, 1, -1, 1, 1, 1, 1, -1, -1, 1, -1, 1, ] if __name__ == "__main__": import doctest doctest.testmod() network = Perceptron( sample=samples, target=exit, learning_rate=0.01, epoch_number=1000, bias=-1 ) network.training() print("Finished training perceptron") print("Enter values to predict or q to exit") while True: sample: list = [] for i in range(len(samples[0])): user_input = input("value: ").strip() if user_input == "q": break observation = float(user_input) sample.insert(i, observation) network.sort(sample)
""" Perceptron w = w + N * (d(k) - y) * x(k) Using perceptron network for oil analysis, with Measuring of 3 parameters that represent chemical characteristics we can classify the oil, in p1 or p2 p1 = -1 p2 = 1 """ import random class Perceptron: def __init__( self, sample: list[list[float]], target: list[int], learning_rate: float = 0.01, epoch_number: int = 1000, bias: float = -1, ) -> None: """ Initializes a Perceptron network for oil analysis :param sample: sample dataset of 3 parameters with shape [30,3] :param target: variable for classification with two possible states -1 or 1 :param learning_rate: learning rate used in optimizing. :param epoch_number: number of epochs to train network on. :param bias: bias value for the network. >>> p = Perceptron([], (0, 1, 2)) Traceback (most recent call last): ... ValueError: Sample data can not be empty >>> p = Perceptron(([0], 1, 2), []) Traceback (most recent call last): ... ValueError: Target data can not be empty >>> p = Perceptron(([0], 1, 2), (0, 1)) Traceback (most recent call last): ... ValueError: Sample data and Target data do not have matching lengths """ self.sample = sample if len(self.sample) == 0: raise ValueError("Sample data can not be empty") self.target = target if len(self.target) == 0: raise ValueError("Target data can not be empty") if len(self.sample) != len(self.target): raise ValueError("Sample data and Target data do not have matching lengths") self.learning_rate = learning_rate self.epoch_number = epoch_number self.bias = bias self.number_sample = len(sample) self.col_sample = len(sample[0]) # number of columns in dataset self.weight: list = [] def training(self) -> None: """ Trains perceptron for epochs <= given number of epochs :return: None >>> data = [[2.0149, 0.6192, 10.9263]] >>> targets = [-1] >>> perceptron = Perceptron(data,targets) >>> perceptron.training() # doctest: +ELLIPSIS ('\\nEpoch:\\n', ...) ... """ for sample in self.sample: sample.insert(0, self.bias) for i in range(self.col_sample): self.weight.append(random.random()) self.weight.insert(0, self.bias) epoch_count = 0 while True: has_misclassified = False for i in range(self.number_sample): u = 0 for j in range(self.col_sample + 1): u = u + self.weight[j] * self.sample[i][j] y = self.sign(u) if y != self.target[i]: for j in range(self.col_sample + 1): self.weight[j] = ( self.weight[j] + self.learning_rate * (self.target[i] - y) * self.sample[i][j] ) has_misclassified = True # print('Epoch: \n',epoch_count) epoch_count = epoch_count + 1 # if you want control the epoch or just by error if not has_misclassified: print(("\nEpoch:\n", epoch_count)) print("------------------------\n") # if epoch_count > self.epoch_number or not error: break def sort(self, sample: list[float]) -> None: """ :param sample: example row to classify as P1 or P2 :return: None >>> data = [[2.0149, 0.6192, 10.9263]] >>> targets = [-1] >>> perceptron = Perceptron(data,targets) >>> perceptron.training() # doctest: +ELLIPSIS ('\\nEpoch:\\n', ...) ... >>> perceptron.sort([-0.6508, 0.1097, 4.0009]) # doctest: +ELLIPSIS ('Sample: ', ...) classification: P... """ if len(self.sample) == 0: raise ValueError("Sample data can not be empty") sample.insert(0, self.bias) u = 0 for i in range(self.col_sample + 1): u = u + self.weight[i] * sample[i] y = self.sign(u) if y == -1: print(("Sample: ", sample)) print("classification: P1") else: print(("Sample: ", sample)) print("classification: P2") def sign(self, u: float) -> int: """ threshold function for classification :param u: input number :return: 1 if the input is greater than 0, otherwise -1 >>> data = [[0],[-0.5],[0.5]] >>> targets = [1,-1,1] >>> perceptron = Perceptron(data,targets) >>> perceptron.sign(0) 1 >>> perceptron.sign(-0.5) -1 >>> perceptron.sign(0.5) 1 """ return 1 if u >= 0 else -1 samples = [ [-0.6508, 0.1097, 4.0009], [-1.4492, 0.8896, 4.4005], [2.0850, 0.6876, 12.0710], [0.2626, 1.1476, 7.7985], [0.6418, 1.0234, 7.0427], [0.2569, 0.6730, 8.3265], [1.1155, 0.6043, 7.4446], [0.0914, 0.3399, 7.0677], [0.0121, 0.5256, 4.6316], [-0.0429, 0.4660, 5.4323], [0.4340, 0.6870, 8.2287], [0.2735, 1.0287, 7.1934], [0.4839, 0.4851, 7.4850], [0.4089, -0.1267, 5.5019], [1.4391, 0.1614, 8.5843], [-0.9115, -0.1973, 2.1962], [0.3654, 1.0475, 7.4858], [0.2144, 0.7515, 7.1699], [0.2013, 1.0014, 6.5489], [0.6483, 0.2183, 5.8991], [-0.1147, 0.2242, 7.2435], [-0.7970, 0.8795, 3.8762], [-1.0625, 0.6366, 2.4707], [0.5307, 0.1285, 5.6883], [-1.2200, 0.7777, 1.7252], [0.3957, 0.1076, 5.6623], [-0.1013, 0.5989, 7.1812], [2.4482, 0.9455, 11.2095], [2.0149, 0.6192, 10.9263], [0.2012, 0.2611, 5.4631], ] exit = [ -1, -1, -1, 1, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, 1, 1, 1, -1, 1, 1, 1, 1, -1, -1, 1, -1, 1, ] if __name__ == "__main__": import doctest doctest.testmod() network = Perceptron( sample=samples, target=exit, learning_rate=0.01, epoch_number=1000, bias=-1 ) network.training() print("Finished training perceptron") print("Enter values to predict or q to exit") while True: sample: list = [] for i in range(len(samples[0])): user_input = input("value: ").strip() if user_input == "q": break observation = float(user_input) sample.insert(i, observation) network.sort(sample)
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
# Video Explanation: https://www.youtube.com/watch?v=6w60Zi1NtL8&feature=emb_logo from __future__ import annotations def maximum_non_adjacent_sum(nums: list[int]) -> int: """ Find the maximum non-adjacent sum of the integers in the nums input list >>> print(maximum_non_adjacent_sum([1, 2, 3])) 4 >>> maximum_non_adjacent_sum([1, 5, 3, 7, 2, 2, 6]) 18 >>> maximum_non_adjacent_sum([-1, -5, -3, -7, -2, -2, -6]) 0 >>> maximum_non_adjacent_sum([499, 500, -3, -7, -2, -2, -6]) 500 """ if not nums: return 0 max_including = nums[0] max_excluding = 0 for num in nums[1:]: max_including, max_excluding = ( max_excluding + num, max(max_including, max_excluding), ) return max(max_excluding, max_including) if __name__ == "__main__": import doctest doctest.testmod()
# Video Explanation: https://www.youtube.com/watch?v=6w60Zi1NtL8&feature=emb_logo from __future__ import annotations def maximum_non_adjacent_sum(nums: list[int]) -> int: """ Find the maximum non-adjacent sum of the integers in the nums input list >>> print(maximum_non_adjacent_sum([1, 2, 3])) 4 >>> maximum_non_adjacent_sum([1, 5, 3, 7, 2, 2, 6]) 18 >>> maximum_non_adjacent_sum([-1, -5, -3, -7, -2, -2, -6]) 0 >>> maximum_non_adjacent_sum([499, 500, -3, -7, -2, -2, -6]) 500 """ if not nums: return 0 max_including = nums[0] max_excluding = 0 for num in nums[1:]: max_including, max_excluding = ( max_excluding + num, max(max_including, max_excluding), ) return max(max_excluding, max_including) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
""" This is a pure Python implementation of the Harmonic Series algorithm https://en.wikipedia.org/wiki/Harmonic_series_(mathematics) For doctests run following command: python -m doctest -v harmonic_series.py or python3 -m doctest -v harmonic_series.py For manual testing run: python3 harmonic_series.py """ def harmonic_series(n_term: str) -> list: """Pure Python implementation of Harmonic Series algorithm :param n_term: The last (nth) term of Harmonic Series :return: The Harmonic Series starting from 1 to last (nth) term Examples: >>> harmonic_series(5) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(5.0) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(5.1) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(-5) [] >>> harmonic_series(0) [] >>> harmonic_series(1) ['1'] """ if n_term == "": return [] series: list = [] for temp in range(int(n_term)): series.append(f"1/{temp + 1}" if series else "1") return series if __name__ == "__main__": nth_term = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
""" This is a pure Python implementation of the Harmonic Series algorithm https://en.wikipedia.org/wiki/Harmonic_series_(mathematics) For doctests run following command: python -m doctest -v harmonic_series.py or python3 -m doctest -v harmonic_series.py For manual testing run: python3 harmonic_series.py """ def harmonic_series(n_term: str) -> list: """Pure Python implementation of Harmonic Series algorithm :param n_term: The last (nth) term of Harmonic Series :return: The Harmonic Series starting from 1 to last (nth) term Examples: >>> harmonic_series(5) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(5.0) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(5.1) ['1', '1/2', '1/3', '1/4', '1/5'] >>> harmonic_series(-5) [] >>> harmonic_series(0) [] >>> harmonic_series(1) ['1'] """ if n_term == "": return [] series: list = [] for temp in range(int(n_term)): series.append(f"1/{temp + 1}" if series else "1") return series if __name__ == "__main__": nth_term = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ import itertools import math def is_prime(number: int) -> bool: """ Determines whether a given number is prime or not >>> is_prime(2) True >>> is_prime(15) False >>> is_prime(29) True """ if number % 2 == 0 and number > 2: return False return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2)) def prime_generator(): """ Generate a sequence of prime numbers """ num = 2 while True: if is_prime(num): yield num num += 1 def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ return next(itertools.islice(prime_generator(), nth - 1, nth)) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 7: https://projecteuler.net/problem=7 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001st prime number? References: - https://en.wikipedia.org/wiki/Prime_number """ import itertools import math def is_prime(number: int) -> bool: """ Determines whether a given number is prime or not >>> is_prime(2) True >>> is_prime(15) False >>> is_prime(29) True """ if number % 2 == 0 and number > 2: return False return all(number % i for i in range(3, int(math.sqrt(number)) + 1, 2)) def prime_generator(): """ Generate a sequence of prime numbers """ num = 2 while True: if is_prime(num): yield num num += 1 def solution(nth: int = 10001) -> int: """ Returns the n-th prime number. >>> solution(6) 13 >>> solution(1) 2 >>> solution(3) 5 >>> solution(20) 71 >>> solution(50) 229 >>> solution(100) 541 """ return next(itertools.islice(prime_generator(), nth - 1, nth)) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
# Knight Tour Intro: https://www.youtube.com/watch?v=ab_dY3dZFHM from __future__ import annotations def get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]: """ Find all the valid positions a knight can move to from the current position. >>> get_valid_pos((1, 3), 4) [(2, 1), (0, 1), (3, 2)] """ y, x = position positions = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] permissible_positions = [] for position in positions: y_test, x_test = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(position) return permissible_positions def is_complete(board: list[list[int]]) -> bool: """ Check if the board (matrix) has been completely filled with non-zero values. >>> is_complete([[1]]) True >>> is_complete([[1, 2], [3, 0]]) False """ return not any(elem == 0 for row in board for elem in row) def open_knight_tour_helper( board: list[list[int]], pos: tuple[int, int], curr: int ) -> bool: """ Helper function to solve knight tour problem. """ if is_complete(board): return True for position in get_valid_pos(pos, len(board)): y, x = position if board[y][x] == 0: board[y][x] = curr + 1 if open_knight_tour_helper(board, position, curr + 1): return True board[y][x] = 0 return False def open_knight_tour(n: int) -> list[list[int]]: """ Find the solution for the knight tour problem for a board of size n. Raises ValueError if the tour cannot be performed for the given size. >>> open_knight_tour(1) [[1]] >>> open_knight_tour(2) Traceback (most recent call last): ... ValueError: Open Kight Tour cannot be performed on a board of size 2 """ board = [[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): board[i][j] = 1 if open_knight_tour_helper(board, (i, j), 1): return board board[i][j] = 0 raise ValueError(f"Open Kight Tour cannot be performed on a board of size {n}") if __name__ == "__main__": import doctest doctest.testmod()
# Knight Tour Intro: https://www.youtube.com/watch?v=ab_dY3dZFHM from __future__ import annotations def get_valid_pos(position: tuple[int, int], n: int) -> list[tuple[int, int]]: """ Find all the valid positions a knight can move to from the current position. >>> get_valid_pos((1, 3), 4) [(2, 1), (0, 1), (3, 2)] """ y, x = position positions = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] permissible_positions = [] for position in positions: y_test, x_test = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(position) return permissible_positions def is_complete(board: list[list[int]]) -> bool: """ Check if the board (matrix) has been completely filled with non-zero values. >>> is_complete([[1]]) True >>> is_complete([[1, 2], [3, 0]]) False """ return not any(elem == 0 for row in board for elem in row) def open_knight_tour_helper( board: list[list[int]], pos: tuple[int, int], curr: int ) -> bool: """ Helper function to solve knight tour problem. """ if is_complete(board): return True for position in get_valid_pos(pos, len(board)): y, x = position if board[y][x] == 0: board[y][x] = curr + 1 if open_knight_tour_helper(board, position, curr + 1): return True board[y][x] = 0 return False def open_knight_tour(n: int) -> list[list[int]]: """ Find the solution for the knight tour problem for a board of size n. Raises ValueError if the tour cannot be performed for the given size. >>> open_knight_tour(1) [[1]] >>> open_knight_tour(2) Traceback (most recent call last): ... ValueError: Open Kight Tour cannot be performed on a board of size 2 """ board = [[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): board[i][j] = 1 if open_knight_tour_helper(board, (i, j), 1): return board board[i][j] = 0 raise ValueError(f"Open Kight Tour cannot be performed on a board of size {n}") if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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): 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()
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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/Jaro%E2%80%93Winkler_distance""" def jaro_winkler(str1: str, str2: str) -> float: """ Jaro–Winkler distance is a string metric measuring an edit distance between two sequences. Output value is between 0.0 and 1.0. >>> jaro_winkler("martha", "marhta") 0.9611111111111111 >>> jaro_winkler("CRATE", "TRACE") 0.7333333333333334 >>> jaro_winkler("test", "dbdbdbdb") 0.0 >>> jaro_winkler("test", "test") 1.0 >>> jaro_winkler("hello world", "HeLLo W0rlD") 0.6363636363636364 >>> jaro_winkler("test", "") 0.0 >>> jaro_winkler("hello", "world") 0.4666666666666666 >>> jaro_winkler("hell**o", "*world") 0.4365079365079365 """ def get_matched_characters(_str1: str, _str2: str) -> str: matched = [] limit = min(len(_str1), len(_str2)) // 2 for i, l in enumerate(_str1): left = int(max(0, i - limit)) right = int(min(i + limit + 1, len(_str2))) if l in _str2[left:right]: matched.append(l) _str2 = f"{_str2[0:_str2.index(l)]} {_str2[_str2.index(l) + 1:]}" return "".join(matched) # matching characters matching_1 = get_matched_characters(str1, str2) matching_2 = get_matched_characters(str2, str1) match_count = len(matching_1) # transposition transpositions = ( len([(c1, c2) for c1, c2 in zip(matching_1, matching_2) if c1 != c2]) // 2 ) if not match_count: jaro = 0.0 else: jaro = ( 1 / 3 * ( match_count / len(str1) + match_count / len(str2) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters prefix_len = 0 for c1, c2 in zip(str1[:4], str2[:4]): if c1 == c2: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("hello", "world"))
"""https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance""" def jaro_winkler(str1: str, str2: str) -> float: """ Jaro–Winkler distance is a string metric measuring an edit distance between two sequences. Output value is between 0.0 and 1.0. >>> jaro_winkler("martha", "marhta") 0.9611111111111111 >>> jaro_winkler("CRATE", "TRACE") 0.7333333333333334 >>> jaro_winkler("test", "dbdbdbdb") 0.0 >>> jaro_winkler("test", "test") 1.0 >>> jaro_winkler("hello world", "HeLLo W0rlD") 0.6363636363636364 >>> jaro_winkler("test", "") 0.0 >>> jaro_winkler("hello", "world") 0.4666666666666666 >>> jaro_winkler("hell**o", "*world") 0.4365079365079365 """ def get_matched_characters(_str1: str, _str2: str) -> str: matched = [] limit = min(len(_str1), len(_str2)) // 2 for i, l in enumerate(_str1): left = int(max(0, i - limit)) right = int(min(i + limit + 1, len(_str2))) if l in _str2[left:right]: matched.append(l) _str2 = f"{_str2[0:_str2.index(l)]} {_str2[_str2.index(l) + 1:]}" return "".join(matched) # matching characters matching_1 = get_matched_characters(str1, str2) matching_2 = get_matched_characters(str2, str1) match_count = len(matching_1) # transposition transpositions = ( len([(c1, c2) for c1, c2 in zip(matching_1, matching_2) if c1 != c2]) // 2 ) if not match_count: jaro = 0.0 else: jaro = ( 1 / 3 * ( match_count / len(str1) + match_count / len(str2) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters prefix_len = 0 for c1, c2 in zip(str1[:4], str2[:4]): if c1 == c2: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("hello", "world"))
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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 typing import Callable import numpy as np def explicit_euler( ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float ) -> np.ndarray: """Calculate numeric solution at each step to an ODE using Euler's Method For reference to Euler's method refer to https://en.wikipedia.org/wiki/Euler_method. Args: ode_func (Callable): The ordinary differential equation as a function of x and y. y0 (float): The initial value for y. x0 (float): The initial value for x. step_size (float): The increment value for x. x_end (float): The final value of x to be calculated. Returns: np.ndarray: Solution of y for every step in x. >>> # the exact solution is math.exp(x) >>> def f(x, y): ... return y >>> y0 = 1 >>> y = explicit_euler(f, y0, 0.0, 0.01, 5) >>> y[-1] 144.77277243257308 """ N = int(np.ceil((x_end - x0) / step_size)) y = np.zeros((N + 1,)) y[0] = y0 x = x0 for k in range(N): y[k + 1] = y[k] + step_size * ode_func(x, y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
from typing import Callable import numpy as np def explicit_euler( ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float ) -> np.ndarray: """Calculate numeric solution at each step to an ODE using Euler's Method For reference to Euler's method refer to https://en.wikipedia.org/wiki/Euler_method. Args: ode_func (Callable): The ordinary differential equation as a function of x and y. y0 (float): The initial value for y. x0 (float): The initial value for x. step_size (float): The increment value for x. x_end (float): The final value of x to be calculated. Returns: np.ndarray: Solution of y for every step in x. >>> # the exact solution is math.exp(x) >>> def f(x, y): ... return y >>> y0 = 1 >>> y = explicit_euler(f, y0, 0.0, 0.01, 5) >>> y[-1] 144.77277243257308 """ N = int(np.ceil((x_end - x0) / step_size)) y = np.zeros((N + 1,)) y[0] = y0 x = x0 for k in range(N): y[k + 1] = y[k] + step_size * ode_func(x, y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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 number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ from __future__ import annotations seive = [True] * 1000001 seive[1] = False i = 2 while i * i <= 1000000: if seive[i]: for j in range(i * i, 1000001, i): seive[j] = False i += 1 def is_prime(n: int) -> bool: """ Returns True if n is prime, False otherwise, for 1 <= n <= 1000000 >>> is_prime(87) False >>> is_prime(1) False >>> is_prime(25363) False """ return seive[n] def list_truncated_nums(n: int) -> list[int]: """ Returns a list of all left and right truncated numbers of n >>> list_truncated_nums(927628) [927628, 27628, 92762, 7628, 9276, 628, 927, 28, 92, 8, 9] >>> list_truncated_nums(467) [467, 67, 46, 7, 4] >>> list_truncated_nums(58) [58, 8, 5] """ str_num = str(n) list_nums = [n] for i in range(1, len(str_num)): list_nums.append(int(str_num[i:])) list_nums.append(int(str_num[:-i])) return list_nums def validate(n: int) -> bool: """ To optimize the approach, we will rule out the numbers above 1000, whose first or last three digits are not prime >>> validate(74679) False >>> validate(235693) False >>> validate(3797) True """ if len(str(n)) > 3: if not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])): return False return True def compute_truncated_primes(count: int = 11) -> list[int]: """ Returns the list of truncated primes >>> compute_truncated_primes(11) [23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397] """ list_truncated_primes: list[int] = [] num = 13 while len(list_truncated_primes) != count: if validate(num): list_nums = list_truncated_nums(num) if all(is_prime(i) for i in list_nums): list_truncated_primes.append(num) num += 2 return list_truncated_primes def solution() -> int: """ Returns the sum of truncated primes """ return sum(compute_truncated_primes(11)) if __name__ == "__main__": print(f"{sum(compute_truncated_primes(11)) = }")
""" The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. Find the sum of the only eleven primes that are both truncatable from left to right and right to left. NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes. """ from __future__ import annotations seive = [True] * 1000001 seive[1] = False i = 2 while i * i <= 1000000: if seive[i]: for j in range(i * i, 1000001, i): seive[j] = False i += 1 def is_prime(n: int) -> bool: """ Returns True if n is prime, False otherwise, for 1 <= n <= 1000000 >>> is_prime(87) False >>> is_prime(1) False >>> is_prime(25363) False """ return seive[n] def list_truncated_nums(n: int) -> list[int]: """ Returns a list of all left and right truncated numbers of n >>> list_truncated_nums(927628) [927628, 27628, 92762, 7628, 9276, 628, 927, 28, 92, 8, 9] >>> list_truncated_nums(467) [467, 67, 46, 7, 4] >>> list_truncated_nums(58) [58, 8, 5] """ str_num = str(n) list_nums = [n] for i in range(1, len(str_num)): list_nums.append(int(str_num[i:])) list_nums.append(int(str_num[:-i])) return list_nums def validate(n: int) -> bool: """ To optimize the approach, we will rule out the numbers above 1000, whose first or last three digits are not prime >>> validate(74679) False >>> validate(235693) False >>> validate(3797) True """ if len(str(n)) > 3: if not is_prime(int(str(n)[-3:])) or not is_prime(int(str(n)[:3])): return False return True def compute_truncated_primes(count: int = 11) -> list[int]: """ Returns the list of truncated primes >>> compute_truncated_primes(11) [23, 37, 53, 73, 313, 317, 373, 797, 3137, 3797, 739397] """ list_truncated_primes: list[int] = [] num = 13 while len(list_truncated_primes) != count: if validate(num): list_nums = list_truncated_nums(num) if all(is_prime(i) for i in list_nums): list_truncated_primes.append(num) num += 2 return list_truncated_primes def solution() -> int: """ Returns the sum of truncated primes """ return sum(compute_truncated_primes(11)) if __name__ == "__main__": print(f"{sum(compute_truncated_primes(11)) = }")
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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 typing import Any class Node: def __init__(self, data: Any): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def print_list(self): temp = self.head while temp is not None: print(temp.data, end=" ") temp = temp.next print() # adding nodes def push(self, new_data: Any): new_node = Node(new_data) new_node.next = self.head self.head = new_node # swapping nodes def swap_nodes(self, node_data_1, node_data_2): if node_data_1 == node_data_2: return else: node_1 = self.head while node_1 is not None and node_1.data != node_data_1: node_1 = node_1.next node_2 = self.head while node_2 is not None and node_2.data != node_data_2: node_2 = node_2.next if node_1 is None or node_2 is None: return node_1.data, node_2.data = node_2.data, node_1.data if __name__ == "__main__": ll = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print("After swapping") ll.print_list()
from typing import Any class Node: def __init__(self, data: Any): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def print_list(self): temp = self.head while temp is not None: print(temp.data, end=" ") temp = temp.next print() # adding nodes def push(self, new_data: Any): new_node = Node(new_data) new_node.next = self.head self.head = new_node # swapping nodes def swap_nodes(self, node_data_1, node_data_2): if node_data_1 == node_data_2: return else: node_1 = self.head while node_1 is not None and node_1.data != node_data_1: node_1 = node_1.next node_2 = self.head while node_2 is not None and node_2.data != node_data_2: node_2 = node_2.next if node_1 is None or node_2 is None: return node_1.data, node_2.data = node_2.data, node_1.data if __name__ == "__main__": ll = LinkedList() for i in range(5, 0, -1): ll.push(i) ll.print_list() ll.swap_nodes(1, 4) print("After swapping") ll.print_list()
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
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, maxCost, keyFunc): itemsCopy = sorted(item, key=keyFunc, reverse=True) result = [] totalValue, total_cost = 0.0, 0.0 for i in range(len(itemsCopy)): if (total_cost + itemsCopy[i].get_weight()) <= maxCost: result.append(itemsCopy[i]) total_cost += itemsCopy[i].get_weight() totalValue += itemsCopy[i].get_value() return (result, totalValue) 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, maxCost, keyFunc): itemsCopy = sorted(item, key=keyFunc, reverse=True) result = [] totalValue, total_cost = 0.0, 0.0 for i in range(len(itemsCopy)): if (total_cost + itemsCopy[i].get_weight()) <= maxCost: result.append(itemsCopy[i]) total_cost += itemsCopy[i].get_weight() totalValue += itemsCopy[i].get_value() return (result, totalValue) 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
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
""" * Author: Manuel Di Lullo (https://github.com/manueldilullo) * Description: Approximization algorithm for minimum vertex cover problem. Matching Approach. Uses graphs represented with an adjacency list URL: https://mathworld.wolfram.com/MinimumVertexCover.html URL: https://www.princeton.edu/~aaa/Public/Teaching/ORF523/ORF523_Lec6.pdf """ def matching_min_vertex_cover(graph: dict) -> set: """ APX Algorithm for min Vertex Cover using Matching Approach @input: graph (graph stored in an adjacency list where each vertex is represented as an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} >>> matching_min_vertex_cover(graph) {0, 1, 2, 4} """ # chosen_vertices = set of chosen vertices chosen_vertices = set() # edges = list of graph's edges edges = get_edges(graph) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: from_node, to_node = edges.pop() chosen_vertices.add(from_node) chosen_vertices.add(to_node) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(edge) return chosen_vertices def get_edges(graph: dict) -> set: """ Return a set of couples that represents all of the edges. @input: graph (graph stored in an adjacency list where each vertex is represented as an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3], 3: [0, 1, 2]} >>> get_edges(graph) {(0, 1), (3, 1), (0, 3), (2, 0), (3, 0), (2, 3), (1, 0), (3, 2), (1, 3)} """ edges = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node)) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
""" * Author: Manuel Di Lullo (https://github.com/manueldilullo) * Description: Approximization algorithm for minimum vertex cover problem. Matching Approach. Uses graphs represented with an adjacency list URL: https://mathworld.wolfram.com/MinimumVertexCover.html URL: https://www.princeton.edu/~aaa/Public/Teaching/ORF523/ORF523_Lec6.pdf """ def matching_min_vertex_cover(graph: dict) -> set: """ APX Algorithm for min Vertex Cover using Matching Approach @input: graph (graph stored in an adjacency list where each vertex is represented as an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} >>> matching_min_vertex_cover(graph) {0, 1, 2, 4} """ # chosen_vertices = set of chosen vertices chosen_vertices = set() # edges = list of graph's edges edges = get_edges(graph) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: from_node, to_node = edges.pop() chosen_vertices.add(from_node) chosen_vertices.add(to_node) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(edge) return chosen_vertices def get_edges(graph: dict) -> set: """ Return a set of couples that represents all of the edges. @input: graph (graph stored in an adjacency list where each vertex is represented as an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3], 3: [0, 1, 2]} >>> get_edges(graph) {(0, 1), (3, 1), (0, 3), (2, 0), (3, 0), (2, 3), (1, 0), (3, 2), (1, 3)} """ edges = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node)) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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 __future__ import annotations from typing import Iterable class Heap: """A Max Heap Implementation >>> unsorted = [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5] >>> h = Heap() >>> h.build_max_heap(unsorted) >>> print(h) [209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5] >>> >>> h.extract_max() 209 >>> print(h) [201, 107, 25, 103, 11, 15, 1, 9, 7, 5] >>> >>> h.insert(100) >>> print(h) [201, 107, 25, 103, 100, 15, 1, 9, 7, 5, 11] >>> >>> h.heap_sort() >>> print(h) [1, 5, 7, 9, 11, 15, 25, 100, 103, 107, 201] """ def __init__(self) -> None: self.h: list[float] = [] self.heap_size: int = 0 def __repr__(self) -> str: return str(self.h) def parent_index(self, child_idx: int) -> int | None: """return the parent index of given child""" if child_idx > 0: return (child_idx - 1) // 2 return None def left_child_idx(self, parent_idx: int) -> int | None: """ return the left child index if the left child exists. if not, return None. """ left_child_index = 2 * parent_idx + 1 if left_child_index < self.heap_size: return left_child_index return None def right_child_idx(self, parent_idx: int) -> int | None: """ return the right child index if the right child exists. if not, return None. """ right_child_index = 2 * parent_idx + 2 if right_child_index < self.heap_size: return right_child_index return None def max_heapify(self, index: int) -> None: """ correct a single violation of the heap property in a subtree's root. """ if index < self.heap_size: violation: int = index left_child = self.left_child_idx(index) right_child = self.right_child_idx(index) # check which child is larger than its parent if left_child is not None and self.h[left_child] > self.h[violation]: violation = left_child if right_child is not None and self.h[right_child] > self.h[violation]: violation = right_child # if violation indeed exists if violation != index: # swap to fix the violation self.h[violation], self.h[index] = self.h[index], self.h[violation] # fix the subsequent violation recursively if any self.max_heapify(violation) def build_max_heap(self, collection: Iterable[float]) -> None: """build max heap from an unsorted array""" self.h = list(collection) self.heap_size = len(self.h) if self.heap_size > 1: # max_heapify from right to left but exclude leaves (last level) for i in range(self.heap_size // 2 - 1, -1, -1): self.max_heapify(i) def max(self) -> float: """return the max in the heap""" if self.heap_size >= 1: return self.h[0] else: raise Exception("Empty heap") def extract_max(self) -> float: """get and remove max from heap""" if self.heap_size >= 2: me = self.h[0] self.h[0] = self.h.pop(-1) self.heap_size -= 1 self.max_heapify(0) return me elif self.heap_size == 1: self.heap_size -= 1 return self.h.pop(-1) else: raise Exception("Empty heap") def insert(self, value: float) -> None: """insert a new value into the max heap""" self.h.append(value) idx = (self.heap_size - 1) // 2 self.heap_size += 1 while idx >= 0: self.max_heapify(idx) idx = (idx - 1) // 2 def heap_sort(self) -> None: size = self.heap_size for j in range(size - 1, 0, -1): self.h[0], self.h[j] = self.h[j], self.h[0] self.heap_size -= 1 self.max_heapify(0) self.heap_size = size if __name__ == "__main__": import doctest # run doc test doctest.testmod() # demo for unsorted in [ [0], [2], [3, 5], [5, 3], [5, 5], [0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 3, 5], [0, 2, 2, 3, 5], [2, 5, 3, 0, 2, 3, 0, 3], [6, 1, 2, 7, 9, 3, 4, 5, 10, 8], [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5], [-45, -2, -5], ]: print(f"unsorted array: {unsorted}") heap = Heap() heap.build_max_heap(unsorted) print(f"after build heap: {heap}") print(f"max value: {heap.extract_max()}") print(f"after max value removed: {heap}") heap.insert(100) print(f"after new value 100 inserted: {heap}") heap.heap_sort() print(f"heap-sorted array: {heap}\n")
from __future__ import annotations from typing import Iterable class Heap: """A Max Heap Implementation >>> unsorted = [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5] >>> h = Heap() >>> h.build_max_heap(unsorted) >>> print(h) [209, 201, 25, 103, 107, 15, 1, 9, 7, 11, 5] >>> >>> h.extract_max() 209 >>> print(h) [201, 107, 25, 103, 11, 15, 1, 9, 7, 5] >>> >>> h.insert(100) >>> print(h) [201, 107, 25, 103, 100, 15, 1, 9, 7, 5, 11] >>> >>> h.heap_sort() >>> print(h) [1, 5, 7, 9, 11, 15, 25, 100, 103, 107, 201] """ def __init__(self) -> None: self.h: list[float] = [] self.heap_size: int = 0 def __repr__(self) -> str: return str(self.h) def parent_index(self, child_idx: int) -> int | None: """return the parent index of given child""" if child_idx > 0: return (child_idx - 1) // 2 return None def left_child_idx(self, parent_idx: int) -> int | None: """ return the left child index if the left child exists. if not, return None. """ left_child_index = 2 * parent_idx + 1 if left_child_index < self.heap_size: return left_child_index return None def right_child_idx(self, parent_idx: int) -> int | None: """ return the right child index if the right child exists. if not, return None. """ right_child_index = 2 * parent_idx + 2 if right_child_index < self.heap_size: return right_child_index return None def max_heapify(self, index: int) -> None: """ correct a single violation of the heap property in a subtree's root. """ if index < self.heap_size: violation: int = index left_child = self.left_child_idx(index) right_child = self.right_child_idx(index) # check which child is larger than its parent if left_child is not None and self.h[left_child] > self.h[violation]: violation = left_child if right_child is not None and self.h[right_child] > self.h[violation]: violation = right_child # if violation indeed exists if violation != index: # swap to fix the violation self.h[violation], self.h[index] = self.h[index], self.h[violation] # fix the subsequent violation recursively if any self.max_heapify(violation) def build_max_heap(self, collection: Iterable[float]) -> None: """build max heap from an unsorted array""" self.h = list(collection) self.heap_size = len(self.h) if self.heap_size > 1: # max_heapify from right to left but exclude leaves (last level) for i in range(self.heap_size // 2 - 1, -1, -1): self.max_heapify(i) def max(self) -> float: """return the max in the heap""" if self.heap_size >= 1: return self.h[0] else: raise Exception("Empty heap") def extract_max(self) -> float: """get and remove max from heap""" if self.heap_size >= 2: me = self.h[0] self.h[0] = self.h.pop(-1) self.heap_size -= 1 self.max_heapify(0) return me elif self.heap_size == 1: self.heap_size -= 1 return self.h.pop(-1) else: raise Exception("Empty heap") def insert(self, value: float) -> None: """insert a new value into the max heap""" self.h.append(value) idx = (self.heap_size - 1) // 2 self.heap_size += 1 while idx >= 0: self.max_heapify(idx) idx = (idx - 1) // 2 def heap_sort(self) -> None: size = self.heap_size for j in range(size - 1, 0, -1): self.h[0], self.h[j] = self.h[j], self.h[0] self.heap_size -= 1 self.max_heapify(0) self.heap_size = size if __name__ == "__main__": import doctest # run doc test doctest.testmod() # demo for unsorted in [ [0], [2], [3, 5], [5, 3], [5, 5], [0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 3, 5], [0, 2, 2, 3, 5], [2, 5, 3, 0, 2, 3, 0, 3], [6, 1, 2, 7, 9, 3, 4, 5, 10, 8], [103, 9, 1, 7, 11, 15, 25, 201, 209, 107, 5], [-45, -2, -5], ]: print(f"unsorted array: {unsorted}") heap = Heap() heap.build_max_heap(unsorted) print(f"after build heap: {heap}") print(f"max value: {heap.extract_max()}") print(f"after max value removed: {heap}") heap.insert(100) print(f"after new value 100 inserted: {heap}") heap.heap_sort() print(f"heap-sorted array: {heap}\n")
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
# @Author : lightXu # @File : convolve.py # @Time : 2019/7/8 0008 下午 16:13 from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import array, dot, pad, ravel, uint8, zeros def im2col(image, block_size): rows, cols = image.shape dst_height = cols - block_size[1] + 1 dst_width = rows - block_size[0] + 1 image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0])) row = 0 for i in range(0, dst_height): for j in range(0, dst_width): window = ravel(image[i : i + block_size[0], j : j + block_size[1]]) image_array[row, :] = window row += 1 return image_array def img_convolve(image, filter_kernel): height, width = image.shape[0], image.shape[1] k_size = filter_kernel.shape[0] pad_size = k_size // 2 # Pads image with the edge values of array. image_tmp = pad(image, pad_size, mode="edge") # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows image_array = im2col(image_tmp, (k_size, k_size)) # turn the kernel into shape(k*k, 1) kernel_array = ravel(filter_kernel) # reshape and get the dst image dst = dot(image_array, kernel_array).reshape(height, width) return dst if __name__ == "__main__": # read original image img = imread(r"../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # Laplace operator Laplace_kernel = array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) out = img_convolve(gray, Laplace_kernel).astype(uint8) imshow("Laplacian", out) waitKey(0)
# @Author : lightXu # @File : convolve.py # @Time : 2019/7/8 0008 下午 16:13 from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import array, dot, pad, ravel, uint8, zeros def im2col(image, block_size): rows, cols = image.shape dst_height = cols - block_size[1] + 1 dst_width = rows - block_size[0] + 1 image_array = zeros((dst_height * dst_width, block_size[1] * block_size[0])) row = 0 for i in range(0, dst_height): for j in range(0, dst_width): window = ravel(image[i : i + block_size[0], j : j + block_size[1]]) image_array[row, :] = window row += 1 return image_array def img_convolve(image, filter_kernel): height, width = image.shape[0], image.shape[1] k_size = filter_kernel.shape[0] pad_size = k_size // 2 # Pads image with the edge values of array. image_tmp = pad(image, pad_size, mode="edge") # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows image_array = im2col(image_tmp, (k_size, k_size)) # turn the kernel into shape(k*k, 1) kernel_array = ravel(filter_kernel) # reshape and get the dst image dst = dot(image_array, kernel_array).reshape(height, width) return dst if __name__ == "__main__": # read original image img = imread(r"../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) # Laplace operator Laplace_kernel = array([[0, 1, 0], [1, -4, 1], [0, 1, 0]]) out = img_convolve(gray, Laplace_kernel).astype(uint8) imshow("Laplacian", out) waitKey(0)
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
""" Self Powers Problem 48 The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. """ def solution(): """ Returns the last 10 digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. >>> solution() '9110846700' """ total = 0 for i in range(1, 1001): total += i**i return str(total)[-10:] if __name__ == "__main__": print(solution())
""" Self Powers Problem 48 The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317. Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. """ def solution(): """ Returns the last 10 digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000. >>> solution() '9110846700' """ total = 0 for i in range(1, 1001): total += i**i return str(total)[-10:] if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
""" 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
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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 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
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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 Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ def fibonacci(n: int) -> int: """ Computes the Fibonacci number for input n by iterating through n numbers and creating an array of ints using the Fibonacci formula. Returns the nth element of the array. >>> fibonacci(2) 1 >>> fibonacci(3) 2 >>> fibonacci(5) 5 >>> fibonacci(10) 55 >>> fibonacci(12) 144 """ if n == 1 or type(n) is not int: return 0 elif n == 2: return 1 else: sequence = [0, 1] for i in range(2, n + 1): sequence.append(sequence[i - 1] + sequence[i - 2]) return sequence[n] def fibonacci_digits_index(n: int) -> int: """ Computes incrementing Fibonacci numbers starting from 3 until the length of the resulting Fibonacci result is the input value n. Returns the term of the Fibonacci sequence where this occurs. >>> fibonacci_digits_index(1000) 4782 >>> fibonacci_digits_index(100) 476 >>> fibonacci_digits_index(50) 237 >>> fibonacci_digits_index(3) 12 """ digits = 0 index = 2 while digits < n: index += 1 digits = len(str(fibonacci(index))) return index def solution(n: int = 1000) -> int: """ Returns the index of the first term in the Fibonacci sequence to contain n digits. >>> solution(1000) 4782 >>> solution(100) 476 >>> solution(50) 237 >>> solution(3) 12 """ return fibonacci_digits_index(n) if __name__ == "__main__": print(solution(int(str(input()).strip())))
""" The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 The 12th term, F12, is the first term to contain three digits. What is the index of the first term in the Fibonacci sequence to contain 1000 digits? """ def fibonacci(n: int) -> int: """ Computes the Fibonacci number for input n by iterating through n numbers and creating an array of ints using the Fibonacci formula. Returns the nth element of the array. >>> fibonacci(2) 1 >>> fibonacci(3) 2 >>> fibonacci(5) 5 >>> fibonacci(10) 55 >>> fibonacci(12) 144 """ if n == 1 or type(n) is not int: return 0 elif n == 2: return 1 else: sequence = [0, 1] for i in range(2, n + 1): sequence.append(sequence[i - 1] + sequence[i - 2]) return sequence[n] def fibonacci_digits_index(n: int) -> int: """ Computes incrementing Fibonacci numbers starting from 3 until the length of the resulting Fibonacci result is the input value n. Returns the term of the Fibonacci sequence where this occurs. >>> fibonacci_digits_index(1000) 4782 >>> fibonacci_digits_index(100) 476 >>> fibonacci_digits_index(50) 237 >>> fibonacci_digits_index(3) 12 """ digits = 0 index = 2 while digits < n: index += 1 digits = len(str(fibonacci(index))) return index def solution(n: int = 1000) -> int: """ Returns the index of the first term in the Fibonacci sequence to contain n digits. >>> solution(1000) 4782 >>> solution(100) 476 >>> solution(50) 237 >>> solution(3) 12 """ return fibonacci_digits_index(n) if __name__ == "__main__": print(solution(int(str(input()).strip())))
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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 moveTower(height, fromPole, toPole, withPole): """ >>> moveTower(3, 'A', 'B', 'C') moving disk from A to B moving disk from A to C moving disk from B to C moving disk from A to B moving disk from C to A moving disk from C to B moving disk from A to B """ if height >= 1: moveTower(height - 1, fromPole, withPole, toPole) moveDisk(fromPole, toPole) moveTower(height - 1, withPole, toPole, fromPole) def moveDisk(fp, tp): print("moving disk from", fp, "to", tp) def main(): height = int(input("Height of hanoi: ").strip()) moveTower(height, "A", "B", "C") if __name__ == "__main__": main()
def moveTower(height, fromPole, toPole, withPole): """ >>> moveTower(3, 'A', 'B', 'C') moving disk from A to B moving disk from A to C moving disk from B to C moving disk from A to B moving disk from C to A moving disk from C to B moving disk from A to B """ if height >= 1: moveTower(height - 1, fromPole, withPole, toPole) moveDisk(fromPole, toPole) moveTower(height - 1, withPole, toPole, fromPole) def moveDisk(fp, tp): print("moving disk from", fp, "to", tp) def main(): height = int(input("Height of hanoi: ").strip()) moveTower(height, "A", "B", "C") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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 __future__ import annotations import requests valid_terms = set( """approved_at_utc approved_by author_flair_background_color author_flair_css_class author_flair_richtext author_flair_template_id author_fullname author_premium can_mod_post category clicked content_categories created_utc downs edited gilded gildings hidden hide_score is_created_from_ads_ui is_meta is_original_content is_reddit_media_domain is_video link_flair_css_class link_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title name permalink pwls quarantine saved score secure_media secure_media_embed selftext subreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type total_awards_received ups upvote_ratio url user_reports""".split() ) def get_subreddit_data( subreddit: str, limit: int = 1, age: str = "new", wanted_data: list | None = None ) -> dict: """ subreddit : Subreddit to query limit : Number of posts to fetch age : ["new", "top", "hot"] wanted_data : Get only the required data in the list >>> pass """ wanted_data = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(wanted_data) - valid_terms)): raise ValueError(f"Invalid search term: {invalid_search_terms}") response = requests.get( f"https://reddit.com/r/{subreddit}/{age}.json?limit={limit}", headers={"User-agent": "A random string"}, ) if response.status_code == 429: raise requests.HTTPError data = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(limit)} data_dict = {} for id_ in range(limit): data_dict[id_] = { item: data["data"]["children"][id_]["data"][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data("learnpython", wanted_data=["title", "url", "selftext"]))
from __future__ import annotations import requests valid_terms = set( """approved_at_utc approved_by author_flair_background_color author_flair_css_class author_flair_richtext author_flair_template_id author_fullname author_premium can_mod_post category clicked content_categories created_utc downs edited gilded gildings hidden hide_score is_created_from_ads_ui is_meta is_original_content is_reddit_media_domain is_video link_flair_css_class link_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title name permalink pwls quarantine saved score secure_media secure_media_embed selftext subreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type total_awards_received ups upvote_ratio url user_reports""".split() ) def get_subreddit_data( subreddit: str, limit: int = 1, age: str = "new", wanted_data: list | None = None ) -> dict: """ subreddit : Subreddit to query limit : Number of posts to fetch age : ["new", "top", "hot"] wanted_data : Get only the required data in the list >>> pass """ wanted_data = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(wanted_data) - valid_terms)): raise ValueError(f"Invalid search term: {invalid_search_terms}") response = requests.get( f"https://reddit.com/r/{subreddit}/{age}.json?limit={limit}", headers={"User-agent": "A random string"}, ) if response.status_code == 429: raise requests.HTTPError data = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(limit)} data_dict = {} for id_ in range(limit): data_dict[id_] = { item: data["data"]["children"][id_]["data"][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data("learnpython", wanted_data=["title", "url", "selftext"]))
-1
TheAlgorithms/Python
6,233
Fix doctests and builds in various files
### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
poyea
"2022-07-06T07:32:36Z"
"2022-07-06T08:00:05Z"
89fc7bf0b024e4c9508db80f575efd5b5616f932
9135a1f41192ebe1d835282a1465dc284359d95c
Fix doctests and builds in various files. ### Describe your change: This fixes several doctest and typing issues, in 3 files to make the build pass. * [ ] 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. * [ ] 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}`.
""" Author : Syed Faizan (3rd Year Student IIIT Pune) github : faizan2700 You are given a bitmask m and you want to efficiently iterate through all of its submasks. The mask s is submask of m if only bits that were included in bitmask are set """ from __future__ import annotations def list_of_submasks(mask: int) -> list[int]: """ Args: mask : number which shows mask ( always integer > 0, zero does not have any submasks ) Returns: all_submasks : the list of submasks of mask (mask s is called submask of mask m if only bits that were included in original mask are set Raises: AssertionError: mask not positive integer >>> list_of_submasks(15) [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] >>> list_of_submasks(13) [13, 12, 9, 8, 5, 4, 1] >>> list_of_submasks(-7) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: mask needs to be positive integer, your input -7 >>> list_of_submasks(0) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: mask needs to be positive integer, your input 0 """ assert ( isinstance(mask, int) and mask > 0 ), f"mask needs to be positive integer, your input {mask}" """ first submask iterated will be mask itself then operation will be performed to get other submasks till we reach empty submask that is zero ( zero is not included in final submasks list ) """ all_submasks = [] submask = mask while submask: all_submasks.append(submask) submask = (submask - 1) & mask return all_submasks if __name__ == "__main__": import doctest doctest.testmod()
""" Author : Syed Faizan (3rd Year Student IIIT Pune) github : faizan2700 You are given a bitmask m and you want to efficiently iterate through all of its submasks. The mask s is submask of m if only bits that were included in bitmask are set """ from __future__ import annotations def list_of_submasks(mask: int) -> list[int]: """ Args: mask : number which shows mask ( always integer > 0, zero does not have any submasks ) Returns: all_submasks : the list of submasks of mask (mask s is called submask of mask m if only bits that were included in original mask are set Raises: AssertionError: mask not positive integer >>> list_of_submasks(15) [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] >>> list_of_submasks(13) [13, 12, 9, 8, 5, 4, 1] >>> list_of_submasks(-7) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: mask needs to be positive integer, your input -7 >>> list_of_submasks(0) # doctest: +ELLIPSIS Traceback (most recent call last): ... AssertionError: mask needs to be positive integer, your input 0 """ assert ( isinstance(mask, int) and mask > 0 ), f"mask needs to be positive integer, your input {mask}" """ first submask iterated will be mask itself then operation will be performed to get other submasks till we reach empty submask that is zero ( zero is not included in final submasks list ) """ all_submasks = [] submask = mask while submask: all_submasks.append(submask) submask = (submask - 1) & mask return all_submasks if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller min_primitive_root = 3 # I have written my code naively same as definition of primitive root # however every time I run this program, memory exceeded... # so I used 4.80 Algorithm in # Handbook of Applied Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996) # and it seems to run nicely! def primitive_root(p_val: int) -> int: print("Generating primitive root of p") while True: g = random.randrange(3, p_val) if pow(g, 2, p_val) == 1: continue if pow(g, p_val, p_val) == 1: continue return g def generate_key(key_size: int) -> tuple[tuple[int, int, int, int], tuple[int, int]]: print("Generating prime p...") p = rabin_miller.generateLargePrime(key_size) # select large prime number. e_1 = primitive_root(p) # one primitive root on modulo p. d = random.randrange(3, p) # private_key -> have to be greater than 2 for safety. e_2 = cryptomath.find_mod_inverse(pow(e_1, d, p), p) public_key = (key_size, e_1, e_2, p) private_key = (key_size, d) return public_key, private_key def make_key_files(name: str, keySize: int) -> None: if os.path.exists("%s_pubkey.txt" % name) or os.path.exists( "%s_privkey.txt" % name ): print("\nWARNING:") print( '"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n' "Use a different name or delete these files and re-run this program." % (name, name) ) sys.exit() publicKey, privateKey = generate_key(keySize) print("\nWriting public key to file %s_pubkey.txt..." % name) with open("%s_pubkey.txt" % name, "w") as fo: fo.write( "%d,%d,%d,%d" % (publicKey[0], publicKey[1], publicKey[2], publicKey[3]) ) print("Writing private key to file %s_privkey.txt..." % name) with open("%s_privkey.txt" % name, "w") as fo: fo.write("%d,%d" % (privateKey[0], privateKey[1])) def main() -> None: print("Making key files...") make_key_files("elgamal", 2048) print("Key files generation successful") if __name__ == "__main__": main()
import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller min_primitive_root = 3 # I have written my code naively same as definition of primitive root # however every time I run this program, memory exceeded... # so I used 4.80 Algorithm in # Handbook of Applied Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996) # and it seems to run nicely! def primitive_root(p_val: int) -> int: print("Generating primitive root of p") while True: g = random.randrange(3, p_val) if pow(g, 2, p_val) == 1: continue if pow(g, p_val, p_val) == 1: continue return g def generate_key(key_size: int) -> tuple[tuple[int, int, int, int], tuple[int, int]]: print("Generating prime p...") p = rabin_miller.generateLargePrime(key_size) # select large prime number. e_1 = primitive_root(p) # one primitive root on modulo p. d = random.randrange(3, p) # private_key -> have to be greater than 2 for safety. e_2 = cryptomath.find_mod_inverse(pow(e_1, d, p), p) public_key = (key_size, e_1, e_2, p) private_key = (key_size, d) return public_key, private_key def make_key_files(name: str, keySize: int) -> None: if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"): print("\nWARNING:") print( '"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n' "Use a different name or delete these files and re-run this program." % (name, name) ) sys.exit() publicKey, privateKey = generate_key(keySize) print(f"\nWriting public key to file {name}_pubkey.txt...") with open(f"{name}_pubkey.txt", "w") as fo: fo.write( "%d,%d,%d,%d" % (publicKey[0], publicKey[1], publicKey[2], publicKey[3]) ) print(f"Writing private key to file {name}_privkey.txt...") with open(f"{name}_privkey.txt", "w") as fo: fo.write("%d,%d" % (privateKey[0], privateKey[1])) def main() -> None: print("Making key files...") make_key_files("elgamal", 2048) print("Key files generation successful") if __name__ == "__main__": main()
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 os import sys from . import rsa_key_generator as rkg DEFAULT_BLOCK_SIZE = 128 BYTE_SIZE = 256 def get_blocks_from_text( message: str, block_size: int = DEFAULT_BLOCK_SIZE ) -> list[int]: message_bytes = message.encode("ascii") block_ints = [] for block_start in range(0, len(message_bytes), block_size): block_int = 0 for i in range(block_start, min(block_start + block_size, len(message_bytes))): block_int += message_bytes[i] * (BYTE_SIZE ** (i % block_size)) block_ints.append(block_int) return block_ints def get_text_from_blocks( block_ints: list[int], message_length: int, block_size: int = DEFAULT_BLOCK_SIZE ) -> str: message: list[str] = [] for block_int in block_ints: block_message: list[str] = [] for i in range(block_size - 1, -1, -1): if len(message) + i < message_length: ascii_number = block_int // (BYTE_SIZE**i) block_int = block_int % (BYTE_SIZE**i) block_message.insert(0, chr(ascii_number)) message.extend(block_message) return "".join(message) def encrypt_message( message: str, key: tuple[int, int], blockSize: int = DEFAULT_BLOCK_SIZE ) -> list[int]: encrypted_blocks = [] n, e = key for block in get_blocks_from_text(message, blockSize): encrypted_blocks.append(pow(block, e, n)) return encrypted_blocks def decrypt_message( encrypted_blocks: list[int], message_length: int, key: tuple[int, int], block_size: int = DEFAULT_BLOCK_SIZE, ) -> str: decrypted_blocks = [] n, d = key for block in encrypted_blocks: decrypted_blocks.append(pow(block, d, n)) return get_text_from_blocks(decrypted_blocks, message_length, block_size) def read_key_file(key_filename: str) -> tuple[int, int, int]: with open(key_filename) as fo: content = fo.read() key_size, n, EorD = content.split(",") return (int(key_size), int(n), int(EorD)) def encrypt_and_write_to_file( message_filename: str, key_filename: str, message: str, block_size: int = DEFAULT_BLOCK_SIZE, ) -> str: key_size, n, e = read_key_file(key_filename) if key_size < block_size * 8: sys.exit( "ERROR: Block size is %s bits and key size is %s bits. The RSA cipher " "requires the block size to be equal to or greater than the key size. " "Either decrease the block size or use different keys." % (block_size * 8, key_size) ) encrypted_blocks = [str(i) for i in encrypt_message(message, (n, e), block_size)] encrypted_content = ",".join(encrypted_blocks) encrypted_content = f"{len(message)}_{block_size}_{encrypted_content}" with open(message_filename, "w") as fo: fo.write(encrypted_content) return encrypted_content def read_from_file_and_decrypt(message_filename: str, key_filename: str) -> str: key_size, n, d = read_key_file(key_filename) with open(message_filename) as fo: content = fo.read() message_length_str, block_size_str, encrypted_message = content.split("_") message_length = int(message_length_str) block_size = int(block_size_str) if key_size < block_size * 8: sys.exit( "ERROR: Block size is %s bits and key size is %s bits. The RSA cipher " "requires the block size to be equal to or greater than the key size. " "Did you specify the correct key file and encrypted file?" % (block_size * 8, key_size) ) encrypted_blocks = [] for block in encrypted_message.split(","): encrypted_blocks.append(int(block)) return decrypt_message(encrypted_blocks, message_length, (n, d), block_size) def main() -> None: filename = "encrypted_file.txt" response = input(r"Encrypt\Decrypt [e\d]: ") if response.lower().startswith("e"): mode = "encrypt" elif response.lower().startswith("d"): mode = "decrypt" if mode == "encrypt": if not os.path.exists("rsa_pubkey.txt"): rkg.makeKeyFiles("rsa", 1024) message = input("\nEnter message: ") pubkey_filename = "rsa_pubkey.txt" print("Encrypting and writing to %s..." % (filename)) encryptedText = encrypt_and_write_to_file(filename, pubkey_filename, message) print("\nEncrypted text:") print(encryptedText) elif mode == "decrypt": privkey_filename = "rsa_privkey.txt" print("Reading from %s and decrypting..." % (filename)) decrypted_text = read_from_file_and_decrypt(filename, privkey_filename) print("writing decryption to rsa_decryption.txt...") with open("rsa_decryption.txt", "w") as dec: dec.write(decrypted_text) print("\nDecryption:") print(decrypted_text) if __name__ == "__main__": main()
import os import sys from . import rsa_key_generator as rkg DEFAULT_BLOCK_SIZE = 128 BYTE_SIZE = 256 def get_blocks_from_text( message: str, block_size: int = DEFAULT_BLOCK_SIZE ) -> list[int]: message_bytes = message.encode("ascii") block_ints = [] for block_start in range(0, len(message_bytes), block_size): block_int = 0 for i in range(block_start, min(block_start + block_size, len(message_bytes))): block_int += message_bytes[i] * (BYTE_SIZE ** (i % block_size)) block_ints.append(block_int) return block_ints def get_text_from_blocks( block_ints: list[int], message_length: int, block_size: int = DEFAULT_BLOCK_SIZE ) -> str: message: list[str] = [] for block_int in block_ints: block_message: list[str] = [] for i in range(block_size - 1, -1, -1): if len(message) + i < message_length: ascii_number = block_int // (BYTE_SIZE**i) block_int = block_int % (BYTE_SIZE**i) block_message.insert(0, chr(ascii_number)) message.extend(block_message) return "".join(message) def encrypt_message( message: str, key: tuple[int, int], blockSize: int = DEFAULT_BLOCK_SIZE ) -> list[int]: encrypted_blocks = [] n, e = key for block in get_blocks_from_text(message, blockSize): encrypted_blocks.append(pow(block, e, n)) return encrypted_blocks def decrypt_message( encrypted_blocks: list[int], message_length: int, key: tuple[int, int], block_size: int = DEFAULT_BLOCK_SIZE, ) -> str: decrypted_blocks = [] n, d = key for block in encrypted_blocks: decrypted_blocks.append(pow(block, d, n)) return get_text_from_blocks(decrypted_blocks, message_length, block_size) def read_key_file(key_filename: str) -> tuple[int, int, int]: with open(key_filename) as fo: content = fo.read() key_size, n, EorD = content.split(",") return (int(key_size), int(n), int(EorD)) def encrypt_and_write_to_file( message_filename: str, key_filename: str, message: str, block_size: int = DEFAULT_BLOCK_SIZE, ) -> str: key_size, n, e = read_key_file(key_filename) if key_size < block_size * 8: sys.exit( "ERROR: Block size is %s bits and key size is %s bits. The RSA cipher " "requires the block size to be equal to or greater than the key size. " "Either decrease the block size or use different keys." % (block_size * 8, key_size) ) encrypted_blocks = [str(i) for i in encrypt_message(message, (n, e), block_size)] encrypted_content = ",".join(encrypted_blocks) encrypted_content = f"{len(message)}_{block_size}_{encrypted_content}" with open(message_filename, "w") as fo: fo.write(encrypted_content) return encrypted_content def read_from_file_and_decrypt(message_filename: str, key_filename: str) -> str: key_size, n, d = read_key_file(key_filename) with open(message_filename) as fo: content = fo.read() message_length_str, block_size_str, encrypted_message = content.split("_") message_length = int(message_length_str) block_size = int(block_size_str) if key_size < block_size * 8: sys.exit( "ERROR: Block size is %s bits and key size is %s bits. The RSA cipher " "requires the block size to be equal to or greater than the key size. " "Did you specify the correct key file and encrypted file?" % (block_size * 8, key_size) ) encrypted_blocks = [] for block in encrypted_message.split(","): encrypted_blocks.append(int(block)) return decrypt_message(encrypted_blocks, message_length, (n, d), block_size) def main() -> None: filename = "encrypted_file.txt" response = input(r"Encrypt\Decrypt [e\d]: ") if response.lower().startswith("e"): mode = "encrypt" elif response.lower().startswith("d"): mode = "decrypt" if mode == "encrypt": if not os.path.exists("rsa_pubkey.txt"): rkg.makeKeyFiles("rsa", 1024) message = input("\nEnter message: ") pubkey_filename = "rsa_pubkey.txt" print(f"Encrypting and writing to {filename}...") encryptedText = encrypt_and_write_to_file(filename, pubkey_filename, message) print("\nEncrypted text:") print(encryptedText) elif mode == "decrypt": privkey_filename = "rsa_privkey.txt" print(f"Reading from {filename} and decrypting...") decrypted_text = read_from_file_and_decrypt(filename, privkey_filename) print("writing decryption to rsa_decryption.txt...") with open("rsa_decryption.txt", "w") as dec: dec.write(decrypted_text) print("\nDecryption:") print(decrypted_text) if __name__ == "__main__": main()
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 os import random import sys from . import cryptomath_module as cryptoMath from . import rabin_miller as rabinMiller def main() -> None: print("Making key files...") makeKeyFiles("rsa", 1024) print("Key files generation successful.") def generateKey(keySize: int) -> tuple[tuple[int, int], tuple[int, int]]: print("Generating prime p...") p = rabinMiller.generateLargePrime(keySize) print("Generating prime q...") q = rabinMiller.generateLargePrime(keySize) n = p * q print("Generating e that is relatively prime to (p - 1) * (q - 1)...") while True: e = random.randrange(2 ** (keySize - 1), 2 ** (keySize)) if cryptoMath.gcd(e, (p - 1) * (q - 1)) == 1: break print("Calculating d that is mod inverse of e...") d = cryptoMath.find_mod_inverse(e, (p - 1) * (q - 1)) publicKey = (n, e) privateKey = (n, d) return (publicKey, privateKey) def makeKeyFiles(name: str, keySize: int) -> None: if os.path.exists("%s_pubkey.txt" % (name)) or os.path.exists( "%s_privkey.txt" % (name) ): print("\nWARNING:") print( '"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n' "Use a different name or delete these files and re-run this program." % (name, name) ) sys.exit() publicKey, privateKey = generateKey(keySize) print("\nWriting public key to file %s_pubkey.txt..." % name) with open("%s_pubkey.txt" % name, "w") as out_file: out_file.write(f"{keySize},{publicKey[0]},{publicKey[1]}") print("Writing private key to file %s_privkey.txt..." % name) with open("%s_privkey.txt" % name, "w") as out_file: out_file.write(f"{keySize},{privateKey[0]},{privateKey[1]}") if __name__ == "__main__": main()
import os import random import sys from . import cryptomath_module as cryptoMath from . import rabin_miller as rabinMiller def main() -> None: print("Making key files...") makeKeyFiles("rsa", 1024) print("Key files generation successful.") def generateKey(keySize: int) -> tuple[tuple[int, int], tuple[int, int]]: print("Generating prime p...") p = rabinMiller.generateLargePrime(keySize) print("Generating prime q...") q = rabinMiller.generateLargePrime(keySize) n = p * q print("Generating e that is relatively prime to (p - 1) * (q - 1)...") while True: e = random.randrange(2 ** (keySize - 1), 2 ** (keySize)) if cryptoMath.gcd(e, (p - 1) * (q - 1)) == 1: break print("Calculating d that is mod inverse of e...") d = cryptoMath.find_mod_inverse(e, (p - 1) * (q - 1)) publicKey = (n, e) privateKey = (n, d) return (publicKey, privateKey) def makeKeyFiles(name: str, keySize: int) -> None: if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"): print("\nWARNING:") print( '"%s_pubkey.txt" or "%s_privkey.txt" already exists. \n' "Use a different name or delete these files and re-run this program." % (name, name) ) sys.exit() publicKey, privateKey = generateKey(keySize) print(f"\nWriting public key to file {name}_pubkey.txt...") with open(f"{name}_pubkey.txt", "w") as out_file: out_file.write(f"{keySize},{publicKey[0]},{publicKey[1]}") print(f"Writing private key to file {name}_privkey.txt...") with open(f"{name}_privkey.txt", "w") as out_file: out_file.write(f"{keySize},{privateKey[0]},{privateKey[1]}") if __name__ == "__main__": main()
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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("Enter key [2-%s]: " % (len(message) - 1))) mode = input("Encryption/Decryption [e/d]: ") if mode.lower().startswith("e"): text = encryptMessage(key, message) elif mode.lower().startswith("d"): text = decryptMessage(key, message) # Append pipe symbol (vertical bar) to identify spaces at the end. print("Output:\n%s" % (text + "|")) def encryptMessage(key: int, message: str) -> str: """ >>> encryptMessage(6, 'Harshil Darji') 'Hlia rDsahrij' """ cipherText = [""] * key for col in range(key): pointer = col while pointer < len(message): cipherText[col] += message[pointer] pointer += key return "".join(cipherText) def decryptMessage(key: int, message: str) -> str: """ >>> decryptMessage(6, 'Hlia rDsahrij') 'Harshil Darji' """ numCols = math.ceil(len(message) / key) numRows = key numShadedBoxes = (numCols * numRows) - len(message) plainText = [""] * numCols col = 0 row = 0 for symbol in message: plainText[col] += symbol col += 1 if ( (col == numCols) or (col == numCols - 1) and (row >= numRows - numShadedBoxes) ): col = 0 row += 1 return "".join(plainText) 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 = encryptMessage(key, message) elif mode.lower().startswith("d"): text = decryptMessage(key, message) # Append pipe symbol (vertical bar) to identify spaces at the end. print(f"Output:\n{text + '|'}") def encryptMessage(key: int, message: str) -> str: """ >>> encryptMessage(6, 'Harshil Darji') 'Hlia rDsahrij' """ cipherText = [""] * key for col in range(key): pointer = col while pointer < len(message): cipherText[col] += message[pointer] pointer += key return "".join(cipherText) def decryptMessage(key: int, message: str) -> str: """ >>> decryptMessage(6, 'Hlia rDsahrij') 'Harshil Darji' """ numCols = math.ceil(len(message) / key) numRows = key numShadedBoxes = (numCols * numRows) - len(message) plainText = [""] * numCols col = 0 row = 0 for symbol in message: plainText[col] += symbol col += 1 if ( (col == numCols) or (col == numCols - 1) and (row >= numRows - numShadedBoxes) ): col = 0 row += 1 return "".join(plainText) if __name__ == "__main__": import doctest doctest.testmod() main()
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 os import sys import time from . import transposition_cipher as transCipher def main() -> None: inputFile = "Prehistoric Men.txt" outputFile = "Output.txt" key = int(input("Enter key: ")) mode = input("Encrypt/Decrypt [e/d]: ") if not os.path.exists(inputFile): print("File %s does not exist. Quitting..." % inputFile) sys.exit() if os.path.exists(outputFile): print("Overwrite %s? [y/n]" % outputFile) response = input("> ") if not response.lower().startswith("y"): sys.exit() startTime = time.time() if mode.lower().startswith("e"): with open(inputFile) as f: content = f.read() translated = transCipher.encryptMessage(key, content) elif mode.lower().startswith("d"): with open(outputFile) as f: content = f.read() translated = transCipher.decryptMessage(key, content) with open(outputFile, "w") as outputObj: outputObj.write(translated) totalTime = round(time.time() - startTime, 2) print(("Done (", totalTime, "seconds )")) if __name__ == "__main__": main()
import os import sys import time from . import transposition_cipher as transCipher def main() -> None: inputFile = "Prehistoric Men.txt" outputFile = "Output.txt" key = int(input("Enter key: ")) mode = input("Encrypt/Decrypt [e/d]: ") if not os.path.exists(inputFile): print(f"File {inputFile} does not exist. Quitting...") sys.exit() if os.path.exists(outputFile): print(f"Overwrite {outputFile}? [y/n]") response = input("> ") if not response.lower().startswith("y"): sys.exit() startTime = time.time() if mode.lower().startswith("e"): with open(inputFile) as f: content = f.read() translated = transCipher.encryptMessage(key, content) elif mode.lower().startswith("d"): with open(outputFile) as f: content = f.read() translated = transCipher.decryptMessage(key, content) with open(outputFile, "w") as outputObj: outputObj.write(translated) totalTime = round(time.time() - startTime, 2) print(("Done (", totalTime, "seconds )")) if __name__ == "__main__": main()
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def main() -> None: message = input("Enter message: ") key = input("Enter key [alphanumeric]: ") mode = input("Encrypt/Decrypt [e/d]: ") if mode.lower().startswith("e"): mode = "encrypt" translated = encryptMessage(key, message) elif mode.lower().startswith("d"): mode = "decrypt" translated = decryptMessage(key, message) print("\n%sed message:" % mode.title()) print(translated) def encryptMessage(key: str, message: str) -> str: """ >>> encryptMessage('HDarji', 'This is Harshil Darji from Dharmaj.') 'Akij ra Odrjqqs Gaisq muod Mphumrs.' """ return translateMessage(key, message, "encrypt") def decryptMessage(key: str, message: str) -> str: """ >>> decryptMessage('HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.') 'This is Harshil Darji from Dharmaj.' """ return translateMessage(key, message, "decrypt") def translateMessage(key: str, message: str, mode: str) -> str: translated = [] keyIndex = 0 key = key.upper() for symbol in message: num = LETTERS.find(symbol.upper()) if num != -1: if mode == "encrypt": num += LETTERS.find(key[keyIndex]) elif mode == "decrypt": num -= LETTERS.find(key[keyIndex]) num %= len(LETTERS) if symbol.isupper(): translated.append(LETTERS[num]) elif symbol.islower(): translated.append(LETTERS[num].lower()) keyIndex += 1 if keyIndex == len(key): keyIndex = 0 else: translated.append(symbol) return "".join(translated) if __name__ == "__main__": main()
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def main() -> None: message = input("Enter message: ") key = input("Enter key [alphanumeric]: ") mode = input("Encrypt/Decrypt [e/d]: ") if mode.lower().startswith("e"): mode = "encrypt" translated = encryptMessage(key, message) elif mode.lower().startswith("d"): mode = "decrypt" translated = decryptMessage(key, message) print(f"\n{mode.title()}ed message:") print(translated) def encryptMessage(key: str, message: str) -> str: """ >>> encryptMessage('HDarji', 'This is Harshil Darji from Dharmaj.') 'Akij ra Odrjqqs Gaisq muod Mphumrs.' """ return translateMessage(key, message, "encrypt") def decryptMessage(key: str, message: str) -> str: """ >>> decryptMessage('HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.') 'This is Harshil Darji from Dharmaj.' """ return translateMessage(key, message, "decrypt") def translateMessage(key: str, message: str, mode: str) -> str: translated = [] keyIndex = 0 key = key.upper() for symbol in message: num = LETTERS.find(symbol.upper()) if num != -1: if mode == "encrypt": num += LETTERS.find(key[keyIndex]) elif mode == "decrypt": num -= LETTERS.find(key[keyIndex]) num %= len(LETTERS) if symbol.isupper(): translated.append(LETTERS[num]) elif symbol.islower(): translated.append(LETTERS[num].lower()) keyIndex += 1 if keyIndex == len(key): keyIndex = 0 else: translated.append(symbol) return "".join(translated) if __name__ == "__main__": main()
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 binary search Tree """ class Node: def __init__(self, value, parent): self.value = value self.parent = parent # Added in order to delete a node easier self.left = None self.right = None def __repr__(self): from pprint import pformat if self.left is None and self.right is None: return str(self.value) return pformat({"%s" % (self.value): (self.left, self.right)}, indent=1) class BinarySearchTree: def __init__(self, root=None): self.root = root def __str__(self): """ Return a string of all the Nodes using in order traversal """ return str(self.root) def __reassign_nodes(self, node, new_children): if new_children is not None: # reset its kids new_children.parent = node.parent if node.parent is not None: # reset its parent if self.is_right(node): # If it is the right children node.parent.right = new_children else: node.parent.left = new_children else: self.root = new_children def is_right(self, node): return node == node.parent.right def empty(self): return self.root is None def __insert(self, value): """ Insert a new node in Binary Search Tree with value label """ new_node = Node(value, None) # create a new Node if self.empty(): # if Tree is empty self.root = new_node # set its root else: # Tree is not empty parent_node = self.root # from root while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: parent_node.left = new_node # We insert the new node in a leaf break else: parent_node = parent_node.left else: if parent_node.right is None: parent_node.right = new_node break else: parent_node = parent_node.right new_node.parent = parent_node def insert(self, *values): for value in values: self.__insert(value) return self def search(self, value): if self.empty(): raise IndexError("Warning: Tree is empty! please use another.") else: node = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: node = node.left if value < node.value else node.right return node def get_max(self, node=None): """ We go deep on the right branch """ if node is None: node = self.root if not self.empty(): while node.right is not None: node = node.right return node def get_min(self, node=None): """ We go deep on the left branch """ if node is None: node = self.root if not self.empty(): node = self.root while node.left is not None: node = node.left return node def remove(self, value): node = self.search(value) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(node, None) elif node.left is None: # Has only right children self.__reassign_nodes(node, node.right) elif node.right is None: # Has only left children self.__reassign_nodes(node, node.left) else: tmp_node = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value) node.value = ( tmp_node.value ) # Assigns the value to the node to delete and keep tree structure def preorder_traverse(self, node): if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left) yield from self.preorder_traverse(node.right) def traversal_tree(self, traversal_function=None): """ This function traversal the tree. You can pass a function to traversal the tree as needed by client code """ if traversal_function is None: return self.preorder_traverse(self.root) else: return traversal_function(self.root) def inorder(self, arr: list, node: Node): """Perform an inorder traversal and append values of the nodes to a list named arr""" if node: self.inorder(arr, node.left) arr.append(node.value) self.inorder(arr, node.right) def find_kth_smallest(self, k: int, node: Node) -> int: """Return the kth smallest element in a binary search tree""" arr: list = [] self.inorder(arr, node) # append all values to list using inorder traversal return arr[k - 1] def postorder(curr_node): """ postOrder (left, right, self) """ node_list = list() if curr_node is not None: node_list = postorder(curr_node.left) + postorder(curr_node.right) + [curr_node] return node_list def binary_search_tree(): r""" Example 8 / \ 3 10 / \ \ 1 6 14 / \ / 4 7 13 >>> t = BinarySearchTree().insert(8, 3, 6, 1, 10, 14, 13, 4, 7) >>> print(" ".join(repr(i.value) for i in t.traversal_tree())) 8 3 1 6 4 7 10 14 13 >>> print(" ".join(repr(i.value) for i in t.traversal_tree(postorder))) 1 4 7 6 3 13 14 10 8 >>> BinarySearchTree().search(6) Traceback (most recent call last): ... IndexError: Warning: Tree is empty! please use another. """ testlist = (8, 3, 6, 1, 10, 14, 13, 4, 7) t = BinarySearchTree() for i in testlist: t.insert(i) # Prints all the elements of the list in order traversal print(t) if t.search(6) is not None: print("The value 6 exists") else: print("The value 6 doesn't exist") if t.search(-1) is not None: print("The value -1 exists") else: print("The value -1 doesn't exist") if not t.empty(): print("Max Value: ", t.get_max().value) print("Min Value: ", t.get_min().value) for i in testlist: t.remove(i) print(t) if __name__ == "__main__": import doctest doctest.testmod() # binary_search_tree()
""" A binary search Tree """ class Node: def __init__(self, value, parent): self.value = value self.parent = parent # Added in order to delete a node easier self.left = None self.right = None def __repr__(self): from pprint import pformat if self.left is None and self.right is None: return str(self.value) return pformat({f"{self.value}": (self.left, self.right)}, indent=1) class BinarySearchTree: def __init__(self, root=None): self.root = root def __str__(self): """ Return a string of all the Nodes using in order traversal """ return str(self.root) def __reassign_nodes(self, node, new_children): if new_children is not None: # reset its kids new_children.parent = node.parent if node.parent is not None: # reset its parent if self.is_right(node): # If it is the right children node.parent.right = new_children else: node.parent.left = new_children else: self.root = new_children def is_right(self, node): return node == node.parent.right def empty(self): return self.root is None def __insert(self, value): """ Insert a new node in Binary Search Tree with value label """ new_node = Node(value, None) # create a new Node if self.empty(): # if Tree is empty self.root = new_node # set its root else: # Tree is not empty parent_node = self.root # from root while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: parent_node.left = new_node # We insert the new node in a leaf break else: parent_node = parent_node.left else: if parent_node.right is None: parent_node.right = new_node break else: parent_node = parent_node.right new_node.parent = parent_node def insert(self, *values): for value in values: self.__insert(value) return self def search(self, value): if self.empty(): raise IndexError("Warning: Tree is empty! please use another.") else: node = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: node = node.left if value < node.value else node.right return node def get_max(self, node=None): """ We go deep on the right branch """ if node is None: node = self.root if not self.empty(): while node.right is not None: node = node.right return node def get_min(self, node=None): """ We go deep on the left branch """ if node is None: node = self.root if not self.empty(): node = self.root while node.left is not None: node = node.left return node def remove(self, value): node = self.search(value) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(node, None) elif node.left is None: # Has only right children self.__reassign_nodes(node, node.right) elif node.right is None: # Has only left children self.__reassign_nodes(node, node.left) else: tmp_node = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value) node.value = ( tmp_node.value ) # Assigns the value to the node to delete and keep tree structure def preorder_traverse(self, node): if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left) yield from self.preorder_traverse(node.right) def traversal_tree(self, traversal_function=None): """ This function traversal the tree. You can pass a function to traversal the tree as needed by client code """ if traversal_function is None: return self.preorder_traverse(self.root) else: return traversal_function(self.root) def inorder(self, arr: list, node: Node): """Perform an inorder traversal and append values of the nodes to a list named arr""" if node: self.inorder(arr, node.left) arr.append(node.value) self.inorder(arr, node.right) def find_kth_smallest(self, k: int, node: Node) -> int: """Return the kth smallest element in a binary search tree""" arr: list = [] self.inorder(arr, node) # append all values to list using inorder traversal return arr[k - 1] def postorder(curr_node): """ postOrder (left, right, self) """ node_list = list() if curr_node is not None: node_list = postorder(curr_node.left) + postorder(curr_node.right) + [curr_node] return node_list def binary_search_tree(): r""" Example 8 / \ 3 10 / \ \ 1 6 14 / \ / 4 7 13 >>> t = BinarySearchTree().insert(8, 3, 6, 1, 10, 14, 13, 4, 7) >>> print(" ".join(repr(i.value) for i in t.traversal_tree())) 8 3 1 6 4 7 10 14 13 >>> print(" ".join(repr(i.value) for i in t.traversal_tree(postorder))) 1 4 7 6 3 13 14 10 8 >>> BinarySearchTree().search(6) Traceback (most recent call last): ... IndexError: Warning: Tree is empty! please use another. """ testlist = (8, 3, 6, 1, 10, 14, 13, 4, 7) t = BinarySearchTree() for i in testlist: t.insert(i) # Prints all the elements of the list in order traversal print(t) if t.search(6) is not None: print("The value 6 exists") else: print("The value 6 doesn't exist") if t.search(-1) is not None: print("The value -1 exists") else: print("The value -1 doesn't exist") if not t.empty(): print("Max Value: ", t.get_max().value) print("Min Value: ", t.get_min().value) for i in testlist: t.remove(i) print(t) if __name__ == "__main__": import doctest doctest.testmod() # binary_search_tree()
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
"""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 i 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("%s" % 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 i 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
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
"""Implementation of GradientBoostingRegressor in sklearn using the boston dataset which is very popular for regression problem to predict house price. """ import matplotlib.pyplot as plt import pandas as pd from sklearn.datasets import load_boston from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split def main(): # loading the dataset from the sklearn df = load_boston() print(df.keys()) # now let construct a data frame df_boston = pd.DataFrame(df.data, columns=df.feature_names) # let add the target to the dataframe df_boston["Price"] = df.target # print the first five rows using the head function print(df_boston.head()) # Summary statistics print(df_boston.describe().T) # Feature selection X = df_boston.iloc[:, :-1] y = df_boston.iloc[:, -1] # target variable # split the data with 75% train and 25% test sets. X_train, X_test, y_train, y_test = train_test_split( X, y, random_state=0, test_size=0.25 ) model = GradientBoostingRegressor( n_estimators=500, max_depth=5, min_samples_split=4, learning_rate=0.01 ) # training the model model.fit(X_train, y_train) # to see how good the model fit the data training_score = model.score(X_train, y_train).round(3) test_score = model.score(X_test, y_test).round(3) print("Training score of GradientBoosting is :", training_score) print("The test score of GradientBoosting is :", test_score) # Let us evaluation the model by finding the errors y_pred = model.predict(X_test) # The mean squared error print("Mean squared error: %.2f" % mean_squared_error(y_test, y_pred)) # Explained variance score: 1 is perfect prediction print("Test Variance score: %.2f" % r2_score(y_test, y_pred)) # So let's run the model against the test data fig, ax = plt.subplots() ax.scatter(y_test, y_pred, edgecolors=(0, 0, 0)) ax.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], "k--", lw=4) ax.set_xlabel("Actual") ax.set_ylabel("Predicted") ax.set_title("Truth vs Predicted") # this show function will display the plotting plt.show() if __name__ == "__main__": main()
"""Implementation of GradientBoostingRegressor in sklearn using the boston dataset which is very popular for regression problem to predict house price. """ import matplotlib.pyplot as plt import pandas as pd from sklearn.datasets import load_boston from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split def main(): # loading the dataset from the sklearn df = load_boston() print(df.keys()) # now let construct a data frame df_boston = pd.DataFrame(df.data, columns=df.feature_names) # let add the target to the dataframe df_boston["Price"] = df.target # print the first five rows using the head function print(df_boston.head()) # Summary statistics print(df_boston.describe().T) # Feature selection X = df_boston.iloc[:, :-1] y = df_boston.iloc[:, -1] # target variable # split the data with 75% train and 25% test sets. X_train, X_test, y_train, y_test = train_test_split( X, y, random_state=0, test_size=0.25 ) model = GradientBoostingRegressor( n_estimators=500, max_depth=5, min_samples_split=4, learning_rate=0.01 ) # training the model model.fit(X_train, y_train) # to see how good the model fit the data training_score = model.score(X_train, y_train).round(3) test_score = model.score(X_test, y_test).round(3) print("Training score of GradientBoosting is :", training_score) print("The test score of GradientBoosting is :", test_score) # Let us evaluation the model by finding the errors y_pred = model.predict(X_test) # The mean squared error print(f"Mean squared error: {mean_squared_error(y_test, y_pred):.2f}") # Explained variance score: 1 is perfect prediction print(f"Test Variance score: {r2_score(y_test, y_pred):.2f}") # So let's run the model against the test data fig, ax = plt.subplots() ax.scatter(y_test, y_pred, edgecolors=(0, 0, 0)) ax.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], "k--", lw=4) ax.set_xlabel("Actual") ax.set_ylabel("Predicted") ax.set_title("Truth vs Predicted") # this show function will display the plotting plt.show() if __name__ == "__main__": main()
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
"""README, Author - Anurag Kumar(mailto:[email protected]) Requirements: - sklearn - numpy - matplotlib Python: - 3.5 Inputs: - X , a 2D numpy array of features. - k , number of clusters to create. - initial_centroids , initial centroid values generated by utility function(mentioned in usage). - maxiter , maximum number of iterations to process. - heterogeneity , empty list that will be filled with hetrogeneity values if passed to kmeans func. Usage: 1. define 'k' value, 'X' features array and 'hetrogeneity' empty list 2. create initial_centroids, initial_centroids = get_initial_centroids( X, k, seed=0 # seed value for initial centroid generation, # None for randomness(default=None) ) 3. find centroids and clusters using kmeans function. centroids, cluster_assignment = kmeans( X, k, initial_centroids, maxiter=400, record_heterogeneity=heterogeneity, verbose=True # whether to print logs in console or not.(default=False) ) 4. Plot the loss function, hetrogeneity values for every iteration saved in hetrogeneity list. plot_heterogeneity( heterogeneity, k ) 5. Transfers Dataframe into excel format it must have feature called 'Clust' with k means clustering numbers in it. """ import warnings import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.metrics import pairwise_distances warnings.filterwarnings("ignore") TAG = "K-MEANS-CLUST/ " def get_initial_centroids(data, k, seed=None): """Randomly choose k data points as initial centroids""" if seed is not None: # useful for obtaining consistent results np.random.seed(seed) n = data.shape[0] # number of data points # Pick K indices from range [0, N). rand_indices = np.random.randint(0, n, k) # Keep centroids as dense format, as many entries will be nonzero due to averaging. # As long as at least one document in a cluster contains a word, # it will carry a nonzero weight in the TF-IDF vector of the centroid. centroids = data[rand_indices, :] return centroids def centroid_pairwise_dist(X, centroids): return pairwise_distances(X, centroids, metric="euclidean") def assign_clusters(data, centroids): # Compute distances between each data point and the set of centroids: # Fill in the blank (RHS only) distances_from_centroids = centroid_pairwise_dist(data, centroids) # Compute cluster assignments for each data point: # Fill in the blank (RHS only) cluster_assignment = np.argmin(distances_from_centroids, axis=1) return cluster_assignment def revise_centroids(data, k, cluster_assignment): new_centroids = [] for i in range(k): # Select all data points that belong to cluster i. Fill in the blank (RHS only) member_data_points = data[cluster_assignment == i] # Compute the mean of the data points. Fill in the blank (RHS only) centroid = member_data_points.mean(axis=0) new_centroids.append(centroid) new_centroids = np.array(new_centroids) return new_centroids def compute_heterogeneity(data, k, centroids, cluster_assignment): heterogeneity = 0.0 for i in range(k): # Select all data points that belong to cluster i. Fill in the blank (RHS only) member_data_points = data[cluster_assignment == i, :] if member_data_points.shape[0] > 0: # check if i-th cluster is non-empty # Compute distances from centroid to data points (RHS only) distances = pairwise_distances( member_data_points, [centroids[i]], metric="euclidean" ) squared_distances = distances**2 heterogeneity += np.sum(squared_distances) return heterogeneity def plot_heterogeneity(heterogeneity, k): plt.figure(figsize=(7, 4)) plt.plot(heterogeneity, linewidth=4) plt.xlabel("# Iterations") plt.ylabel("Heterogeneity") plt.title(f"Heterogeneity of clustering over time, K={k:d}") plt.rcParams.update({"font.size": 16}) plt.show() def kmeans( data, k, initial_centroids, maxiter=500, record_heterogeneity=None, verbose=False ): """This function runs k-means on given data and initial set of centroids. maxiter: maximum number of iterations to run.(default=500) record_heterogeneity: (optional) a list, to store the history of heterogeneity as function of iterations if None, do not store the history. verbose: if True, print how many data points changed their cluster labels in each iteration""" centroids = initial_centroids[:] prev_cluster_assignment = None for itr in range(maxiter): if verbose: print(itr, end="") # 1. Make cluster assignments using nearest centroids cluster_assignment = assign_clusters(data, centroids) # 2. Compute a new centroid for each of the k clusters, averaging all data # points assigned to that cluster. centroids = revise_centroids(data, k, cluster_assignment) # Check for convergence: if none of the assignments changed, stop if ( prev_cluster_assignment is not None and (prev_cluster_assignment == cluster_assignment).all() ): break # Print number of new assignments if prev_cluster_assignment is not None: num_changed = np.sum(prev_cluster_assignment != cluster_assignment) if verbose: print( " {:5d} elements changed their cluster assignment.".format( num_changed ) ) # Record heterogeneity convergence metric if record_heterogeneity is not None: # YOUR CODE HERE score = compute_heterogeneity(data, k, centroids, cluster_assignment) record_heterogeneity.append(score) prev_cluster_assignment = cluster_assignment[:] return centroids, cluster_assignment # Mock test below if False: # change to true to run this test case. from sklearn import datasets as ds dataset = ds.load_iris() k = 3 heterogeneity = [] initial_centroids = get_initial_centroids(dataset["data"], k, seed=0) centroids, cluster_assignment = kmeans( dataset["data"], k, initial_centroids, maxiter=400, record_heterogeneity=heterogeneity, verbose=True, ) plot_heterogeneity(heterogeneity, k) def ReportGenerator( df: pd.DataFrame, ClusteringVariables: np.ndarray, FillMissingReport=None ) -> pd.DataFrame: """ Function generates easy-erading clustering report. It takes 2 arguments as an input: DataFrame - dataframe with predicted cluester column; FillMissingReport - dictionary of rules how we are going to fill missing values of for final report generate (not included in modeling); in order to run the function following libraries must be imported: import pandas as pd import numpy as np >>> data = pd.DataFrame() >>> data['numbers'] = [1, 2, 3] >>> data['col1'] = [0.5, 2.5, 4.5] >>> data['col2'] = [100, 200, 300] >>> data['col3'] = [10, 20, 30] >>> data['Cluster'] = [1, 1, 2] >>> ReportGenerator(data, ['col1', 'col2'], 0) Features Type Mark 1 2 0 # of Customers ClusterSize False 2.000000 1.000000 1 % of Customers ClusterProportion False 0.666667 0.333333 2 col1 mean_with_zeros True 1.500000 4.500000 3 col2 mean_with_zeros True 150.000000 300.000000 4 numbers mean_with_zeros False 1.500000 3.000000 .. ... ... ... ... ... 99 dummy 5% False 1.000000 1.000000 100 dummy 95% False 1.000000 1.000000 101 dummy stdev False 0.000000 NaN 102 dummy mode False 1.000000 1.000000 103 dummy median False 1.000000 1.000000 <BLANKLINE> [104 rows x 5 columns] """ # Fill missing values with given rules if FillMissingReport: df.fillna(value=FillMissingReport, inplace=True) df["dummy"] = 1 numeric_cols = df.select_dtypes(np.number).columns report = ( df.groupby(["Cluster"])[ # construct report dataframe numeric_cols ] # group by cluster number .agg( [ ("sum", np.sum), ("mean_with_zeros", lambda x: np.mean(np.nan_to_num(x))), ("mean_without_zeros", lambda x: x.replace(0, np.NaN).mean()), ( "mean_25-75", lambda x: np.mean( np.nan_to_num( sorted(x)[ round(len(x) * 25 / 100) : round(len(x) * 75 / 100) ] ) ), ), ("mean_with_na", np.mean), ("min", lambda x: x.min()), ("5%", lambda x: x.quantile(0.05)), ("25%", lambda x: x.quantile(0.25)), ("50%", lambda x: x.quantile(0.50)), ("75%", lambda x: x.quantile(0.75)), ("95%", lambda x: x.quantile(0.95)), ("max", lambda x: x.max()), ("count", lambda x: x.count()), ("stdev", lambda x: x.std()), ("mode", lambda x: x.mode()[0]), ("median", lambda x: x.median()), ("# > 0", lambda x: (x > 0).sum()), ] ) .T.reset_index() .rename(index=str, columns={"level_0": "Features", "level_1": "Type"}) ) # rename columns # calculate the size of cluster(count of clientID's) clustersize = report[ (report["Features"] == "dummy") & (report["Type"] == "count") ].copy() # avoid SettingWithCopyWarning clustersize.Type = ( "ClusterSize" # rename created cluster df to match report column names ) clustersize.Features = "# of Customers" clusterproportion = pd.DataFrame( clustersize.iloc[:, 2:].values / clustersize.iloc[:, 2:].values.sum() # calculating the proportion of cluster ) clusterproportion[ "Type" ] = "% of Customers" # rename created cluster df to match report column names clusterproportion["Features"] = "ClusterProportion" cols = clusterproportion.columns.tolist() cols = cols[-2:] + cols[:-2] clusterproportion = clusterproportion[cols] # rearrange columns to match report clusterproportion.columns = report.columns a = pd.DataFrame( abs( report[report["Type"] == "count"].iloc[:, 2:].values - clustersize.iloc[:, 2:].values ) ) # generating df with count of nan values a["Features"] = 0 a["Type"] = "# of nan" a.Features = report[ report["Type"] == "count" ].Features.tolist() # filling values in order to match report cols = a.columns.tolist() cols = cols[-2:] + cols[:-2] a = a[cols] # rearrange columns to match report a.columns = report.columns # rename columns to match report report = report.drop( report[report.Type == "count"].index ) # drop count values except cluster size report = pd.concat( [report, a, clustersize, clusterproportion], axis=0 ) # concat report with clustert size and nan values report["Mark"] = report["Features"].isin(ClusteringVariables) cols = report.columns.tolist() cols = cols[0:2] + cols[-1:] + cols[2:-1] report = report[cols] sorter1 = { "ClusterSize": 9, "ClusterProportion": 8, "mean_with_zeros": 7, "mean_with_na": 6, "max": 5, "50%": 4, "min": 3, "25%": 2, "75%": 1, "# of nan": 0, "# > 0": -1, "sum_with_na": -2, } report = ( report.assign( Sorter1=lambda x: x.Type.map(sorter1), Sorter2=lambda x: list(reversed(range(len(x)))), ) .sort_values(["Sorter1", "Mark", "Sorter2"], ascending=False) .drop(["Sorter1", "Sorter2"], axis=1) ) report.columns.name = "" report = report.reset_index() report.drop(columns=["index"], inplace=True) return report if __name__ == "__main__": import doctest doctest.testmod()
"""README, Author - Anurag Kumar(mailto:[email protected]) Requirements: - sklearn - numpy - matplotlib Python: - 3.5 Inputs: - X , a 2D numpy array of features. - k , number of clusters to create. - initial_centroids , initial centroid values generated by utility function(mentioned in usage). - maxiter , maximum number of iterations to process. - heterogeneity , empty list that will be filled with hetrogeneity values if passed to kmeans func. Usage: 1. define 'k' value, 'X' features array and 'hetrogeneity' empty list 2. create initial_centroids, initial_centroids = get_initial_centroids( X, k, seed=0 # seed value for initial centroid generation, # None for randomness(default=None) ) 3. find centroids and clusters using kmeans function. centroids, cluster_assignment = kmeans( X, k, initial_centroids, maxiter=400, record_heterogeneity=heterogeneity, verbose=True # whether to print logs in console or not.(default=False) ) 4. Plot the loss function, hetrogeneity values for every iteration saved in hetrogeneity list. plot_heterogeneity( heterogeneity, k ) 5. Transfers Dataframe into excel format it must have feature called 'Clust' with k means clustering numbers in it. """ import warnings import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn.metrics import pairwise_distances warnings.filterwarnings("ignore") TAG = "K-MEANS-CLUST/ " def get_initial_centroids(data, k, seed=None): """Randomly choose k data points as initial centroids""" if seed is not None: # useful for obtaining consistent results np.random.seed(seed) n = data.shape[0] # number of data points # Pick K indices from range [0, N). rand_indices = np.random.randint(0, n, k) # Keep centroids as dense format, as many entries will be nonzero due to averaging. # As long as at least one document in a cluster contains a word, # it will carry a nonzero weight in the TF-IDF vector of the centroid. centroids = data[rand_indices, :] return centroids def centroid_pairwise_dist(X, centroids): return pairwise_distances(X, centroids, metric="euclidean") def assign_clusters(data, centroids): # Compute distances between each data point and the set of centroids: # Fill in the blank (RHS only) distances_from_centroids = centroid_pairwise_dist(data, centroids) # Compute cluster assignments for each data point: # Fill in the blank (RHS only) cluster_assignment = np.argmin(distances_from_centroids, axis=1) return cluster_assignment def revise_centroids(data, k, cluster_assignment): new_centroids = [] for i in range(k): # Select all data points that belong to cluster i. Fill in the blank (RHS only) member_data_points = data[cluster_assignment == i] # Compute the mean of the data points. Fill in the blank (RHS only) centroid = member_data_points.mean(axis=0) new_centroids.append(centroid) new_centroids = np.array(new_centroids) return new_centroids def compute_heterogeneity(data, k, centroids, cluster_assignment): heterogeneity = 0.0 for i in range(k): # Select all data points that belong to cluster i. Fill in the blank (RHS only) member_data_points = data[cluster_assignment == i, :] if member_data_points.shape[0] > 0: # check if i-th cluster is non-empty # Compute distances from centroid to data points (RHS only) distances = pairwise_distances( member_data_points, [centroids[i]], metric="euclidean" ) squared_distances = distances**2 heterogeneity += np.sum(squared_distances) return heterogeneity def plot_heterogeneity(heterogeneity, k): plt.figure(figsize=(7, 4)) plt.plot(heterogeneity, linewidth=4) plt.xlabel("# Iterations") plt.ylabel("Heterogeneity") plt.title(f"Heterogeneity of clustering over time, K={k:d}") plt.rcParams.update({"font.size": 16}) plt.show() def kmeans( data, k, initial_centroids, maxiter=500, record_heterogeneity=None, verbose=False ): """This function runs k-means on given data and initial set of centroids. maxiter: maximum number of iterations to run.(default=500) record_heterogeneity: (optional) a list, to store the history of heterogeneity as function of iterations if None, do not store the history. verbose: if True, print how many data points changed their cluster labels in each iteration""" centroids = initial_centroids[:] prev_cluster_assignment = None for itr in range(maxiter): if verbose: print(itr, end="") # 1. Make cluster assignments using nearest centroids cluster_assignment = assign_clusters(data, centroids) # 2. Compute a new centroid for each of the k clusters, averaging all data # points assigned to that cluster. centroids = revise_centroids(data, k, cluster_assignment) # Check for convergence: if none of the assignments changed, stop if ( prev_cluster_assignment is not None and (prev_cluster_assignment == cluster_assignment).all() ): break # Print number of new assignments if prev_cluster_assignment is not None: num_changed = np.sum(prev_cluster_assignment != cluster_assignment) if verbose: print( f" {num_changed:5d} elements changed their cluster assignment." ) # Record heterogeneity convergence metric if record_heterogeneity is not None: # YOUR CODE HERE score = compute_heterogeneity(data, k, centroids, cluster_assignment) record_heterogeneity.append(score) prev_cluster_assignment = cluster_assignment[:] return centroids, cluster_assignment # Mock test below if False: # change to true to run this test case. from sklearn import datasets as ds dataset = ds.load_iris() k = 3 heterogeneity = [] initial_centroids = get_initial_centroids(dataset["data"], k, seed=0) centroids, cluster_assignment = kmeans( dataset["data"], k, initial_centroids, maxiter=400, record_heterogeneity=heterogeneity, verbose=True, ) plot_heterogeneity(heterogeneity, k) def ReportGenerator( df: pd.DataFrame, ClusteringVariables: np.ndarray, FillMissingReport=None ) -> pd.DataFrame: """ Function generates easy-erading clustering report. It takes 2 arguments as an input: DataFrame - dataframe with predicted cluester column; FillMissingReport - dictionary of rules how we are going to fill missing values of for final report generate (not included in modeling); in order to run the function following libraries must be imported: import pandas as pd import numpy as np >>> data = pd.DataFrame() >>> data['numbers'] = [1, 2, 3] >>> data['col1'] = [0.5, 2.5, 4.5] >>> data['col2'] = [100, 200, 300] >>> data['col3'] = [10, 20, 30] >>> data['Cluster'] = [1, 1, 2] >>> ReportGenerator(data, ['col1', 'col2'], 0) Features Type Mark 1 2 0 # of Customers ClusterSize False 2.000000 1.000000 1 % of Customers ClusterProportion False 0.666667 0.333333 2 col1 mean_with_zeros True 1.500000 4.500000 3 col2 mean_with_zeros True 150.000000 300.000000 4 numbers mean_with_zeros False 1.500000 3.000000 .. ... ... ... ... ... 99 dummy 5% False 1.000000 1.000000 100 dummy 95% False 1.000000 1.000000 101 dummy stdev False 0.000000 NaN 102 dummy mode False 1.000000 1.000000 103 dummy median False 1.000000 1.000000 <BLANKLINE> [104 rows x 5 columns] """ # Fill missing values with given rules if FillMissingReport: df.fillna(value=FillMissingReport, inplace=True) df["dummy"] = 1 numeric_cols = df.select_dtypes(np.number).columns report = ( df.groupby(["Cluster"])[ # construct report dataframe numeric_cols ] # group by cluster number .agg( [ ("sum", np.sum), ("mean_with_zeros", lambda x: np.mean(np.nan_to_num(x))), ("mean_without_zeros", lambda x: x.replace(0, np.NaN).mean()), ( "mean_25-75", lambda x: np.mean( np.nan_to_num( sorted(x)[ round(len(x) * 25 / 100) : round(len(x) * 75 / 100) ] ) ), ), ("mean_with_na", np.mean), ("min", lambda x: x.min()), ("5%", lambda x: x.quantile(0.05)), ("25%", lambda x: x.quantile(0.25)), ("50%", lambda x: x.quantile(0.50)), ("75%", lambda x: x.quantile(0.75)), ("95%", lambda x: x.quantile(0.95)), ("max", lambda x: x.max()), ("count", lambda x: x.count()), ("stdev", lambda x: x.std()), ("mode", lambda x: x.mode()[0]), ("median", lambda x: x.median()), ("# > 0", lambda x: (x > 0).sum()), ] ) .T.reset_index() .rename(index=str, columns={"level_0": "Features", "level_1": "Type"}) ) # rename columns # calculate the size of cluster(count of clientID's) clustersize = report[ (report["Features"] == "dummy") & (report["Type"] == "count") ].copy() # avoid SettingWithCopyWarning clustersize.Type = ( "ClusterSize" # rename created cluster df to match report column names ) clustersize.Features = "# of Customers" clusterproportion = pd.DataFrame( clustersize.iloc[:, 2:].values / clustersize.iloc[:, 2:].values.sum() # calculating the proportion of cluster ) clusterproportion[ "Type" ] = "% of Customers" # rename created cluster df to match report column names clusterproportion["Features"] = "ClusterProportion" cols = clusterproportion.columns.tolist() cols = cols[-2:] + cols[:-2] clusterproportion = clusterproportion[cols] # rearrange columns to match report clusterproportion.columns = report.columns a = pd.DataFrame( abs( report[report["Type"] == "count"].iloc[:, 2:].values - clustersize.iloc[:, 2:].values ) ) # generating df with count of nan values a["Features"] = 0 a["Type"] = "# of nan" a.Features = report[ report["Type"] == "count" ].Features.tolist() # filling values in order to match report cols = a.columns.tolist() cols = cols[-2:] + cols[:-2] a = a[cols] # rearrange columns to match report a.columns = report.columns # rename columns to match report report = report.drop( report[report.Type == "count"].index ) # drop count values except cluster size report = pd.concat( [report, a, clustersize, clusterproportion], axis=0 ) # concat report with clustert size and nan values report["Mark"] = report["Features"].isin(ClusteringVariables) cols = report.columns.tolist() cols = cols[0:2] + cols[-1:] + cols[2:-1] report = report[cols] sorter1 = { "ClusterSize": 9, "ClusterProportion": 8, "mean_with_zeros": 7, "mean_with_na": 6, "max": 5, "50%": 4, "min": 3, "25%": 2, "75%": 1, "# of nan": 0, "# > 0": -1, "sum_with_na": -2, } report = ( report.assign( Sorter1=lambda x: x.Type.map(sorter1), Sorter2=lambda x: list(reversed(range(len(x)))), ) .sort_values(["Sorter1", "Mark", "Sorter2"], ascending=False) .drop(["Sorter1", "Sorter2"], axis=1) ) report.columns.name = "" report = report.reset_index() report.drop(columns=["index"], inplace=True) return report if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
""" Linear regression is the most basic type of regression commonly used for predictive analysis. The idea is pretty simple: we have a dataset and we have features associated with it. Features should be chosen very cautiously as they determine how much our model will be able to make future predictions. We try to set the weight of these features, over many iterations, so that they best fit our dataset. In this particular code, I had used a CSGO dataset (ADR vs Rating). We try to best fit a line through dataset and estimate the parameters. """ import numpy as np import requests def collect_dataset(): """Collect dataset of CSGO The dataset contains ADR vs Rating of a Player :return : dataset obtained from the link, as matrix """ response = requests.get( "https://raw.githubusercontent.com/yashLadha/" + "The_Math_of_Intelligence/master/Week1/ADRvs" + "Rating.csv" ) lines = response.text.splitlines() data = [] for item in lines: item = item.split(",") data.append(item) data.pop(0) # This is for removing the labels from the list dataset = np.matrix(data) return dataset def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta): """Run steep gradient descent and updates the Feature vector accordingly_ :param data_x : contains the dataset :param data_y : contains the output associated with each data-entry :param len_data : length of the data_ :param alpha : Learning rate of the model :param theta : Feature vector (weight's for our model) ;param return : Updated Feature's, using curr_features - alpha_ * gradient(w.r.t. feature) """ n = len_data prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_grad = np.dot(prod, data_x) theta = theta - (alpha / n) * sum_grad return theta def sum_of_square_error(data_x, data_y, len_data, theta): """Return sum of square error for error calculation :param data_x : contains our dataset :param data_y : contains the output (result vector) :param len_data : len of the dataset :param theta : contains the feature vector :return : sum of square error computed from given feature's """ prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_elem = np.sum(np.square(prod)) error = sum_elem / (2 * len_data) return error def run_linear_regression(data_x, data_y): """Implement Linear regression over the dataset :param data_x : contains our dataset :param data_y : contains the output (result vector) :return : feature for line of best fit (Feature vector) """ iterations = 100000 alpha = 0.0001550 no_features = data_x.shape[1] len_data = data_x.shape[0] - 1 theta = np.zeros((1, no_features)) for i in range(0, iterations): theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta) error = sum_of_square_error(data_x, data_y, len_data, theta) print("At Iteration %d - Error is %.5f " % (i + 1, error)) return theta def main(): """Driver function""" data = collect_dataset() len_data = data.shape[0] data_x = np.c_[np.ones(len_data), data[:, :-1]].astype(float) data_y = data[:, -1].astype(float) theta = run_linear_regression(data_x, data_y) len_result = theta.shape[1] print("Resultant Feature vector : ") for i in range(0, len_result): print("%.5f" % (theta[0, i])) if __name__ == "__main__": main()
""" Linear regression is the most basic type of regression commonly used for predictive analysis. The idea is pretty simple: we have a dataset and we have features associated with it. Features should be chosen very cautiously as they determine how much our model will be able to make future predictions. We try to set the weight of these features, over many iterations, so that they best fit our dataset. In this particular code, I had used a CSGO dataset (ADR vs Rating). We try to best fit a line through dataset and estimate the parameters. """ import numpy as np import requests def collect_dataset(): """Collect dataset of CSGO The dataset contains ADR vs Rating of a Player :return : dataset obtained from the link, as matrix """ response = requests.get( "https://raw.githubusercontent.com/yashLadha/" + "The_Math_of_Intelligence/master/Week1/ADRvs" + "Rating.csv" ) lines = response.text.splitlines() data = [] for item in lines: item = item.split(",") data.append(item) data.pop(0) # This is for removing the labels from the list dataset = np.matrix(data) return dataset def run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta): """Run steep gradient descent and updates the Feature vector accordingly_ :param data_x : contains the dataset :param data_y : contains the output associated with each data-entry :param len_data : length of the data_ :param alpha : Learning rate of the model :param theta : Feature vector (weight's for our model) ;param return : Updated Feature's, using curr_features - alpha_ * gradient(w.r.t. feature) """ n = len_data prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_grad = np.dot(prod, data_x) theta = theta - (alpha / n) * sum_grad return theta def sum_of_square_error(data_x, data_y, len_data, theta): """Return sum of square error for error calculation :param data_x : contains our dataset :param data_y : contains the output (result vector) :param len_data : len of the dataset :param theta : contains the feature vector :return : sum of square error computed from given feature's """ prod = np.dot(theta, data_x.transpose()) prod -= data_y.transpose() sum_elem = np.sum(np.square(prod)) error = sum_elem / (2 * len_data) return error def run_linear_regression(data_x, data_y): """Implement Linear regression over the dataset :param data_x : contains our dataset :param data_y : contains the output (result vector) :return : feature for line of best fit (Feature vector) """ iterations = 100000 alpha = 0.0001550 no_features = data_x.shape[1] len_data = data_x.shape[0] - 1 theta = np.zeros((1, no_features)) for i in range(0, iterations): theta = run_steep_gradient_descent(data_x, data_y, len_data, alpha, theta) error = sum_of_square_error(data_x, data_y, len_data, theta) print("At Iteration %d - Error is %.5f " % (i + 1, error)) return theta def main(): """Driver function""" data = collect_dataset() len_data = data.shape[0] data_x = np.c_[np.ones(len_data), data[:, :-1]].astype(float) data_y = data[:, -1].astype(float) theta = run_linear_regression(data_x, data_y) len_result = theta.shape[1] print("Resultant Feature vector : ") for i in range(0, len_result): print(f"{theta[0, i]:.5f}") if __name__ == "__main__": main()
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
class Matrix: """ <class Matrix> Matrix structure. """ def __init__(self, row: int, column: int, default_value: float = 0): """ <method Matrix.__init__> Initialize matrix with given size and default value. Example: >>> a = Matrix(2, 3, 1) >>> a Matrix consist of 2 rows and 3 columns [1, 1, 1] [1, 1, 1] """ self.row, self.column = row, column self.array = [[default_value for c in range(column)] for r in range(row)] def __str__(self): """ <method Matrix.__str__> Return string representation of this matrix. """ # Prefix s = "Matrix consist of %d rows and %d columns\n" % (self.row, self.column) # Make string identifier max_element_length = 0 for row_vector in self.array: for obj in row_vector: max_element_length = max(max_element_length, len(str(obj))) string_format_identifier = "%%%ds" % (max_element_length,) # Make string and return def single_line(row_vector): nonlocal string_format_identifier line = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector) line += "]" return line s += "\n".join(single_line(row_vector) for row_vector in self.array) return s def __repr__(self): return str(self) def validateIndices(self, loc: tuple): """ <method Matrix.validateIndices> Check if given indices are valid to pick element from matrix. Example: >>> a = Matrix(2, 6, 0) >>> a.validateIndices((2, 7)) False >>> a.validateIndices((0, 0)) True """ if not (isinstance(loc, (list, tuple)) and len(loc) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__(self, loc: tuple): """ <method Matrix.__getitem__> Return array[row][column] where loc = (row, column). Example: >>> a = Matrix(3, 2, 7) >>> a[1, 0] 7 """ assert self.validateIndices(loc) return self.array[loc[0]][loc[1]] def __setitem__(self, loc: tuple, value: float): """ <method Matrix.__setitem__> Set array[row][column] = value where loc = (row, column). Example: >>> a = Matrix(2, 3, 1) >>> a[1, 2] = 51 >>> a Matrix consist of 2 rows and 3 columns [ 1, 1, 1] [ 1, 1, 51] """ assert self.validateIndices(loc) self.array[loc[0]][loc[1]] = value def __add__(self, another): """ <method Matrix.__add__> Return self + another. Example: >>> a = Matrix(2, 1, -4) >>> b = Matrix(2, 1, 3) >>> a+b Matrix consist of 2 rows and 1 columns [-1] [-1] """ # Validation assert isinstance(another, Matrix) assert self.row == another.row and self.column == another.column # Add result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] + another[r, c] return result def __neg__(self): """ <method Matrix.__neg__> Return -self. Example: >>> a = Matrix(2, 2, 3) >>> a[0, 1] = a[1, 0] = -2 >>> -a Matrix consist of 2 rows and 2 columns [-3, 2] [ 2, -3] """ result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = -self[r, c] return result def __sub__(self, another): return self + (-another) def __mul__(self, another): """ <method Matrix.__mul__> Return self * another. Example: >>> a = Matrix(2, 3, 1) >>> a[0,2] = a[1,2] = 3 >>> a * -2 Matrix consist of 2 rows and 3 columns [-2, -2, -6] [-2, -2, -6] """ if isinstance(another, (int, float)): # Scalar multiplication result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] * another return result elif isinstance(another, Matrix): # Matrix multiplication assert self.column == another.row result = Matrix(self.row, another.column) for r in range(self.row): for c in range(another.column): for i in range(self.column): result[r, c] += self[r, i] * another[i, c] return result else: raise TypeError(f"Unsupported type given for another ({type(another)})") def transpose(self): """ <method Matrix.transpose> Return self^T. Example: >>> a = Matrix(2, 3) >>> for r in range(2): ... for c in range(3): ... a[r,c] = r*c ... >>> a.transpose() Matrix consist of 3 rows and 2 columns [0, 0] [0, 1] [0, 2] """ result = Matrix(self.column, self.row) for r in range(self.row): for c in range(self.column): result[c, r] = self[r, c] return result def ShermanMorrison(self, u, v): """ <method Matrix.ShermanMorrison> Apply Sherman-Morrison formula in O(n^2). To learn this formula, please look this: https://en.wikipedia.org/wiki/Sherman%E2%80%93Morrison_formula This method returns (A + uv^T)^(-1) where A^(-1) is self. Returns None if it's impossible to calculate. Warning: This method doesn't check if self is invertible. Make sure self is invertible before execute this method. Example: >>> ainv = Matrix(3, 3, 0) >>> for i in range(3): ainv[i,i] = 1 ... >>> u = Matrix(3, 1, 0) >>> u[0,0], u[1,0], u[2,0] = 1, 2, -3 >>> v = Matrix(3, 1, 0) >>> v[0,0], v[1,0], v[2,0] = 4, -2, 5 >>> ainv.ShermanMorrison(u, v) Matrix consist of 3 rows and 3 columns [ 1.2857142857142856, -0.14285714285714285, 0.3571428571428571] [ 0.5714285714285714, 0.7142857142857143, 0.7142857142857142] [ -0.8571428571428571, 0.42857142857142855, -0.0714285714285714] """ # Size validation assert isinstance(u, Matrix) and isinstance(v, Matrix) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate vT = v.transpose() numerator_factor = (vT * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (vT * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def test1(): # a^(-1) ainv = Matrix(3, 3, 0) for i in range(3): ainv[i, i] = 1 print(f"a^(-1) is {ainv}") # u, v u = Matrix(3, 1, 0) u[0, 0], u[1, 0], u[2, 0] = 1, 2, -3 v = Matrix(3, 1, 0) v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5 print(f"u is {u}") print(f"v is {v}") print("uv^T is %s" % (u * v.transpose())) # Sherman Morrison print(f"(a + uv^T)^(-1) is {ainv.ShermanMorrison(u, v)}") def test2(): import doctest doctest.testmod() test2()
class Matrix: """ <class Matrix> Matrix structure. """ def __init__(self, row: int, column: int, default_value: float = 0): """ <method Matrix.__init__> Initialize matrix with given size and default value. Example: >>> a = Matrix(2, 3, 1) >>> a Matrix consist of 2 rows and 3 columns [1, 1, 1] [1, 1, 1] """ self.row, self.column = row, column self.array = [[default_value for c in range(column)] for r in range(row)] def __str__(self): """ <method Matrix.__str__> Return string representation of this matrix. """ # Prefix s = "Matrix consist of %d rows and %d columns\n" % (self.row, self.column) # Make string identifier max_element_length = 0 for row_vector in self.array: for obj in row_vector: max_element_length = max(max_element_length, len(str(obj))) string_format_identifier = "%%%ds" % (max_element_length,) # Make string and return def single_line(row_vector): nonlocal string_format_identifier line = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector) line += "]" return line s += "\n".join(single_line(row_vector) for row_vector in self.array) return s def __repr__(self): return str(self) def validateIndices(self, loc: tuple): """ <method Matrix.validateIndices> Check if given indices are valid to pick element from matrix. Example: >>> a = Matrix(2, 6, 0) >>> a.validateIndices((2, 7)) False >>> a.validateIndices((0, 0)) True """ if not (isinstance(loc, (list, tuple)) and len(loc) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__(self, loc: tuple): """ <method Matrix.__getitem__> Return array[row][column] where loc = (row, column). Example: >>> a = Matrix(3, 2, 7) >>> a[1, 0] 7 """ assert self.validateIndices(loc) return self.array[loc[0]][loc[1]] def __setitem__(self, loc: tuple, value: float): """ <method Matrix.__setitem__> Set array[row][column] = value where loc = (row, column). Example: >>> a = Matrix(2, 3, 1) >>> a[1, 2] = 51 >>> a Matrix consist of 2 rows and 3 columns [ 1, 1, 1] [ 1, 1, 51] """ assert self.validateIndices(loc) self.array[loc[0]][loc[1]] = value def __add__(self, another): """ <method Matrix.__add__> Return self + another. Example: >>> a = Matrix(2, 1, -4) >>> b = Matrix(2, 1, 3) >>> a+b Matrix consist of 2 rows and 1 columns [-1] [-1] """ # Validation assert isinstance(another, Matrix) assert self.row == another.row and self.column == another.column # Add result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] + another[r, c] return result def __neg__(self): """ <method Matrix.__neg__> Return -self. Example: >>> a = Matrix(2, 2, 3) >>> a[0, 1] = a[1, 0] = -2 >>> -a Matrix consist of 2 rows and 2 columns [-3, 2] [ 2, -3] """ result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = -self[r, c] return result def __sub__(self, another): return self + (-another) def __mul__(self, another): """ <method Matrix.__mul__> Return self * another. Example: >>> a = Matrix(2, 3, 1) >>> a[0,2] = a[1,2] = 3 >>> a * -2 Matrix consist of 2 rows and 3 columns [-2, -2, -6] [-2, -2, -6] """ if isinstance(another, (int, float)): # Scalar multiplication result = Matrix(self.row, self.column) for r in range(self.row): for c in range(self.column): result[r, c] = self[r, c] * another return result elif isinstance(another, Matrix): # Matrix multiplication assert self.column == another.row result = Matrix(self.row, another.column) for r in range(self.row): for c in range(another.column): for i in range(self.column): result[r, c] += self[r, i] * another[i, c] return result else: raise TypeError(f"Unsupported type given for another ({type(another)})") def transpose(self): """ <method Matrix.transpose> Return self^T. Example: >>> a = Matrix(2, 3) >>> for r in range(2): ... for c in range(3): ... a[r,c] = r*c ... >>> a.transpose() Matrix consist of 3 rows and 2 columns [0, 0] [0, 1] [0, 2] """ result = Matrix(self.column, self.row) for r in range(self.row): for c in range(self.column): result[c, r] = self[r, c] return result def ShermanMorrison(self, u, v): """ <method Matrix.ShermanMorrison> Apply Sherman-Morrison formula in O(n^2). To learn this formula, please look this: https://en.wikipedia.org/wiki/Sherman%E2%80%93Morrison_formula This method returns (A + uv^T)^(-1) where A^(-1) is self. Returns None if it's impossible to calculate. Warning: This method doesn't check if self is invertible. Make sure self is invertible before execute this method. Example: >>> ainv = Matrix(3, 3, 0) >>> for i in range(3): ainv[i,i] = 1 ... >>> u = Matrix(3, 1, 0) >>> u[0,0], u[1,0], u[2,0] = 1, 2, -3 >>> v = Matrix(3, 1, 0) >>> v[0,0], v[1,0], v[2,0] = 4, -2, 5 >>> ainv.ShermanMorrison(u, v) Matrix consist of 3 rows and 3 columns [ 1.2857142857142856, -0.14285714285714285, 0.3571428571428571] [ 0.5714285714285714, 0.7142857142857143, 0.7142857142857142] [ -0.8571428571428571, 0.42857142857142855, -0.0714285714285714] """ # Size validation assert isinstance(u, Matrix) and isinstance(v, Matrix) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate vT = v.transpose() numerator_factor = (vT * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (vT * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def test1(): # a^(-1) ainv = Matrix(3, 3, 0) for i in range(3): ainv[i, i] = 1 print(f"a^(-1) is {ainv}") # u, v u = Matrix(3, 1, 0) u[0, 0], u[1, 0], u[2, 0] = 1, 2, -3 v = Matrix(3, 1, 0) v[0, 0], v[1, 0], v[2, 0] = 4, -2, 5 print(f"u is {u}") print(f"v is {v}") print(f"uv^T is {u * v.transpose()}") # Sherman Morrison print(f"(a + uv^T)^(-1) is {ainv.ShermanMorrison(u, v)}") def test2(): import doctest doctest.testmod() test2()
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
""" - - - - - -- - - - - - - - - - - - - - - - - - - - - - - Name - - CNN - Convolution Neural Network For Photo Recognizing Goal - - Recognize Handing Writing Word Photo Detail:Total 5 layers neural network * Convolution layer * Pooling layer * Input layer layer of BP * Hidden layer of BP * Output layer of BP Author: Stephen Lee Github: [email protected] Date: 2017.9.20 - - - - - -- - - - - - - - - - - - - - - - - - - - - - - """ import pickle import numpy as np from matplotlib import pyplot as plt class CNN: def __init__( self, conv1_get, size_p1, bp_num1, bp_num2, bp_num3, rate_w=0.2, rate_t=0.2 ): """ :param conv1_get: [a,c,d],size, number, step of convolution kernel :param size_p1: pooling size :param bp_num1: units number of flatten layer :param bp_num2: units number of hidden layer :param bp_num3: units number of output layer :param rate_w: rate of weight learning :param rate_t: rate of threshold learning """ self.num_bp1 = bp_num1 self.num_bp2 = bp_num2 self.num_bp3 = bp_num3 self.conv1 = conv1_get[:2] self.step_conv1 = conv1_get[2] self.size_pooling1 = size_p1 self.rate_weight = rate_w self.rate_thre = rate_t self.w_conv1 = [ np.mat(-1 * np.random.rand(self.conv1[0], self.conv1[0]) + 0.5) for i in range(self.conv1[1]) ] self.wkj = np.mat(-1 * np.random.rand(self.num_bp3, self.num_bp2) + 0.5) self.vji = np.mat(-1 * np.random.rand(self.num_bp2, self.num_bp1) + 0.5) self.thre_conv1 = -2 * np.random.rand(self.conv1[1]) + 1 self.thre_bp2 = -2 * np.random.rand(self.num_bp2) + 1 self.thre_bp3 = -2 * np.random.rand(self.num_bp3) + 1 def save_model(self, save_path): # save model dict with pickle model_dic = { "num_bp1": self.num_bp1, "num_bp2": self.num_bp2, "num_bp3": self.num_bp3, "conv1": self.conv1, "step_conv1": self.step_conv1, "size_pooling1": self.size_pooling1, "rate_weight": self.rate_weight, "rate_thre": self.rate_thre, "w_conv1": self.w_conv1, "wkj": self.wkj, "vji": self.vji, "thre_conv1": self.thre_conv1, "thre_bp2": self.thre_bp2, "thre_bp3": self.thre_bp3, } with open(save_path, "wb") as f: pickle.dump(model_dic, f) print("Model saved: %s" % save_path) @classmethod def ReadModel(cls, model_path): # read saved model with open(model_path, "rb") as f: model_dic = pickle.load(f) conv_get = model_dic.get("conv1") conv_get.append(model_dic.get("step_conv1")) size_p1 = model_dic.get("size_pooling1") bp1 = model_dic.get("num_bp1") bp2 = model_dic.get("num_bp2") bp3 = model_dic.get("num_bp3") r_w = model_dic.get("rate_weight") r_t = model_dic.get("rate_thre") # create model instance conv_ins = CNN(conv_get, size_p1, bp1, bp2, bp3, r_w, r_t) # modify model parameter conv_ins.w_conv1 = model_dic.get("w_conv1") conv_ins.wkj = model_dic.get("wkj") conv_ins.vji = model_dic.get("vji") conv_ins.thre_conv1 = model_dic.get("thre_conv1") conv_ins.thre_bp2 = model_dic.get("thre_bp2") conv_ins.thre_bp3 = model_dic.get("thre_bp3") return conv_ins def sig(self, x): return 1 / (1 + np.exp(-1 * x)) def do_round(self, x): return round(x, 3) def convolute(self, data, convs, w_convs, thre_convs, conv_step): # convolution process size_conv = convs[0] num_conv = convs[1] size_data = np.shape(data)[0] # get the data slice of original image data, data_focus data_focus = [] for i_focus in range(0, size_data - size_conv + 1, conv_step): for j_focus in range(0, size_data - size_conv + 1, conv_step): focus = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(focus) # calculate the feature map of every single kernel, and saved as list of matrix data_featuremap = [] Size_FeatureMap = int((size_data - size_conv) / conv_step + 1) for i_map in range(num_conv): featuremap = [] for i_focus in range(len(data_focus)): net_focus = ( np.sum(np.multiply(data_focus[i_focus], w_convs[i_map])) - thre_convs[i_map] ) featuremap.append(self.sig(net_focus)) featuremap = np.asmatrix(featuremap).reshape( Size_FeatureMap, Size_FeatureMap ) data_featuremap.append(featuremap) # expanding the data slice to One dimenssion focus1_list = [] for each_focus in data_focus: focus1_list.extend(self.Expand_Mat(each_focus)) focus_list = np.asarray(focus1_list) return focus_list, data_featuremap def pooling(self, featuremaps, size_pooling, type="average_pool"): # pooling process size_map = len(featuremaps[0]) size_pooled = int(size_map / size_pooling) featuremap_pooled = [] for i_map in range(len(featuremaps)): map = featuremaps[i_map] map_pooled = [] for i_focus in range(0, size_map, size_pooling): for j_focus in range(0, size_map, size_pooling): focus = map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if type == "average_pool": # average pooling map_pooled.append(np.average(focus)) elif type == "max_pooling": # max pooling map_pooled.append(np.max(focus)) map_pooled = np.asmatrix(map_pooled).reshape(size_pooled, size_pooled) featuremap_pooled.append(map_pooled) return featuremap_pooled def _expand(self, data): # expanding three dimension data to one dimension list data_expanded = [] for i in range(len(data)): shapes = np.shape(data[i]) data_listed = data[i].reshape(1, shapes[0] * shapes[1]) data_listed = data_listed.getA().tolist()[0] data_expanded.extend(data_listed) data_expanded = np.asarray(data_expanded) return data_expanded def _expand_mat(self, data_mat): # expanding matrix to one dimension list data_mat = np.asarray(data_mat) shapes = np.shape(data_mat) data_expanded = data_mat.reshape(1, shapes[0] * shapes[1]) return data_expanded def _calculate_gradient_from_pool( self, out_map, pd_pool, num_map, size_map, size_pooling ): """ calculate the gradient from the data slice of pool layer pd_pool: list of matrix out_map: the shape of data slice(size_map*size_map) return: pd_all: list of matrix, [num, size_map, size_map] """ pd_all = [] i_pool = 0 for i_map in range(num_map): pd_conv1 = np.ones((size_map, size_map)) for i in range(0, size_map, size_pooling): for j in range(0, size_map, size_pooling): pd_conv1[i : i + size_pooling, j : j + size_pooling] = pd_pool[ i_pool ] i_pool = i_pool + 1 pd_conv2 = np.multiply( pd_conv1, np.multiply(out_map[i_map], (1 - out_map[i_map])) ) pd_all.append(pd_conv2) return pd_all def train( self, patterns, datas_train, datas_teach, n_repeat, error_accuracy, draw_e=bool ): # model traning print("----------------------Start Training-------------------------") print((" - - Shape: Train_Data ", np.shape(datas_train))) print((" - - Shape: Teach_Data ", np.shape(datas_teach))) rp = 0 all_mse = [] mse = 10000 while rp < n_repeat and mse >= error_accuracy: error_count = 0 print("-------------Learning Time %d--------------" % rp) for p in range(len(datas_train)): # print('------------Learning Image: %d--------------'%p) data_train = np.asmatrix(datas_train[p]) data_teach = np.asarray(datas_teach[p]) data_focus1, data_conved1 = self.convolute( data_train, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) shape_featuremap1 = np.shape(data_conved1) """ print(' -----original shape ', np.shape(data_train)) print(' ---- after convolution ',np.shape(data_conv1)) print(' -----after pooling ',np.shape(data_pooled1)) """ data_bp_input = self._expand(data_pooled1) bp_out1 = data_bp_input bp_net_j = np.dot(bp_out1, self.vji.T) - self.thre_bp2 bp_out2 = self.sig(bp_net_j) bp_net_k = np.dot(bp_out2, self.wkj.T) - self.thre_bp3 bp_out3 = self.sig(bp_net_k) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- pd_k_all = np.multiply( (data_teach - bp_out3), np.multiply(bp_out3, (1 - bp_out3)) ) pd_j_all = np.multiply( np.dot(pd_k_all, self.wkj), np.multiply(bp_out2, (1 - bp_out2)) ) pd_i_all = np.dot(pd_j_all, self.vji) pd_conv1_pooled = pd_i_all / (self.size_pooling1 * self.size_pooling1) pd_conv1_pooled = pd_conv1_pooled.T.getA().tolist() pd_conv1_all = self._calculate_gradient_from_pool( data_conved1, pd_conv1_pooled, shape_featuremap1[0], shape_featuremap1[1], self.size_pooling1, ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conv1[1]): pd_conv_list = self._expand_mat(pd_conv1_all[k_conv]) delta_w = self.rate_weight * np.dot(pd_conv_list, data_focus1) self.w_conv1[k_conv] = self.w_conv1[k_conv] + delta_w.reshape( (self.conv1[0], self.conv1[0]) ) self.thre_conv1[k_conv] = ( self.thre_conv1[k_conv] - np.sum(pd_conv1_all[k_conv]) * self.rate_thre ) # all connected layer self.wkj = self.wkj + pd_k_all.T * bp_out2 * self.rate_weight self.vji = self.vji + pd_j_all.T * bp_out1 * self.rate_weight self.thre_bp3 = self.thre_bp3 - pd_k_all * self.rate_thre self.thre_bp2 = self.thre_bp2 - pd_j_all * self.rate_thre # calculate the sum error of all single image errors = np.sum(abs(data_teach - bp_out3)) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) rp = rp + 1 mse = error_count / patterns all_mse.append(mse) def draw_error(): yplot = [error_accuracy for i in range(int(n_repeat * 1.2))] plt.plot(all_mse, "+-") plt.plot(yplot, "r--") plt.xlabel("Learning Times") plt.ylabel("All_mse") plt.grid(True, alpha=0.5) plt.show() print("------------------Training Complished---------------------") print((" - - Training epoch: ", rp, " - - Mse: %.6f" % mse)) if draw_e: draw_error() return mse def predict(self, datas_test): # model predict produce_out = [] print("-------------------Start Testing-------------------------") print((" - - Shape: Test_Data ", np.shape(datas_test))) for p in range(len(datas_test)): data_test = np.asmatrix(datas_test[p]) data_focus1, data_conved1 = self.convolute( data_test, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) data_bp_input = self._expand(data_pooled1) bp_out1 = data_bp_input bp_net_j = bp_out1 * self.vji.T - self.thre_bp2 bp_out2 = self.sig(bp_net_j) bp_net_k = bp_out2 * self.wkj.T - self.thre_bp3 bp_out3 = self.sig(bp_net_k) produce_out.extend(bp_out3.getA().tolist()) res = [list(map(self.do_round, each)) for each in produce_out] return np.asarray(res) def convolution(self, data): # return the data of image after convoluting process so we can check it out data_test = np.asmatrix(data) data_focus1, data_conved1 = self.convolute( data_test, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) return data_conved1, data_pooled1 if __name__ == "__main__": """ I will put the example on other file """
""" - - - - - -- - - - - - - - - - - - - - - - - - - - - - - Name - - CNN - Convolution Neural Network For Photo Recognizing Goal - - Recognize Handing Writing Word Photo Detail:Total 5 layers neural network * Convolution layer * Pooling layer * Input layer layer of BP * Hidden layer of BP * Output layer of BP Author: Stephen Lee Github: [email protected] Date: 2017.9.20 - - - - - -- - - - - - - - - - - - - - - - - - - - - - - """ import pickle import numpy as np from matplotlib import pyplot as plt class CNN: def __init__( self, conv1_get, size_p1, bp_num1, bp_num2, bp_num3, rate_w=0.2, rate_t=0.2 ): """ :param conv1_get: [a,c,d],size, number, step of convolution kernel :param size_p1: pooling size :param bp_num1: units number of flatten layer :param bp_num2: units number of hidden layer :param bp_num3: units number of output layer :param rate_w: rate of weight learning :param rate_t: rate of threshold learning """ self.num_bp1 = bp_num1 self.num_bp2 = bp_num2 self.num_bp3 = bp_num3 self.conv1 = conv1_get[:2] self.step_conv1 = conv1_get[2] self.size_pooling1 = size_p1 self.rate_weight = rate_w self.rate_thre = rate_t self.w_conv1 = [ np.mat(-1 * np.random.rand(self.conv1[0], self.conv1[0]) + 0.5) for i in range(self.conv1[1]) ] self.wkj = np.mat(-1 * np.random.rand(self.num_bp3, self.num_bp2) + 0.5) self.vji = np.mat(-1 * np.random.rand(self.num_bp2, self.num_bp1) + 0.5) self.thre_conv1 = -2 * np.random.rand(self.conv1[1]) + 1 self.thre_bp2 = -2 * np.random.rand(self.num_bp2) + 1 self.thre_bp3 = -2 * np.random.rand(self.num_bp3) + 1 def save_model(self, save_path): # save model dict with pickle model_dic = { "num_bp1": self.num_bp1, "num_bp2": self.num_bp2, "num_bp3": self.num_bp3, "conv1": self.conv1, "step_conv1": self.step_conv1, "size_pooling1": self.size_pooling1, "rate_weight": self.rate_weight, "rate_thre": self.rate_thre, "w_conv1": self.w_conv1, "wkj": self.wkj, "vji": self.vji, "thre_conv1": self.thre_conv1, "thre_bp2": self.thre_bp2, "thre_bp3": self.thre_bp3, } with open(save_path, "wb") as f: pickle.dump(model_dic, f) print(f"Model saved: {save_path}") @classmethod def ReadModel(cls, model_path): # read saved model with open(model_path, "rb") as f: model_dic = pickle.load(f) conv_get = model_dic.get("conv1") conv_get.append(model_dic.get("step_conv1")) size_p1 = model_dic.get("size_pooling1") bp1 = model_dic.get("num_bp1") bp2 = model_dic.get("num_bp2") bp3 = model_dic.get("num_bp3") r_w = model_dic.get("rate_weight") r_t = model_dic.get("rate_thre") # create model instance conv_ins = CNN(conv_get, size_p1, bp1, bp2, bp3, r_w, r_t) # modify model parameter conv_ins.w_conv1 = model_dic.get("w_conv1") conv_ins.wkj = model_dic.get("wkj") conv_ins.vji = model_dic.get("vji") conv_ins.thre_conv1 = model_dic.get("thre_conv1") conv_ins.thre_bp2 = model_dic.get("thre_bp2") conv_ins.thre_bp3 = model_dic.get("thre_bp3") return conv_ins def sig(self, x): return 1 / (1 + np.exp(-1 * x)) def do_round(self, x): return round(x, 3) def convolute(self, data, convs, w_convs, thre_convs, conv_step): # convolution process size_conv = convs[0] num_conv = convs[1] size_data = np.shape(data)[0] # get the data slice of original image data, data_focus data_focus = [] for i_focus in range(0, size_data - size_conv + 1, conv_step): for j_focus in range(0, size_data - size_conv + 1, conv_step): focus = data[ i_focus : i_focus + size_conv, j_focus : j_focus + size_conv ] data_focus.append(focus) # calculate the feature map of every single kernel, and saved as list of matrix data_featuremap = [] Size_FeatureMap = int((size_data - size_conv) / conv_step + 1) for i_map in range(num_conv): featuremap = [] for i_focus in range(len(data_focus)): net_focus = ( np.sum(np.multiply(data_focus[i_focus], w_convs[i_map])) - thre_convs[i_map] ) featuremap.append(self.sig(net_focus)) featuremap = np.asmatrix(featuremap).reshape( Size_FeatureMap, Size_FeatureMap ) data_featuremap.append(featuremap) # expanding the data slice to One dimenssion focus1_list = [] for each_focus in data_focus: focus1_list.extend(self.Expand_Mat(each_focus)) focus_list = np.asarray(focus1_list) return focus_list, data_featuremap def pooling(self, featuremaps, size_pooling, type="average_pool"): # pooling process size_map = len(featuremaps[0]) size_pooled = int(size_map / size_pooling) featuremap_pooled = [] for i_map in range(len(featuremaps)): map = featuremaps[i_map] map_pooled = [] for i_focus in range(0, size_map, size_pooling): for j_focus in range(0, size_map, size_pooling): focus = map[ i_focus : i_focus + size_pooling, j_focus : j_focus + size_pooling, ] if type == "average_pool": # average pooling map_pooled.append(np.average(focus)) elif type == "max_pooling": # max pooling map_pooled.append(np.max(focus)) map_pooled = np.asmatrix(map_pooled).reshape(size_pooled, size_pooled) featuremap_pooled.append(map_pooled) return featuremap_pooled def _expand(self, data): # expanding three dimension data to one dimension list data_expanded = [] for i in range(len(data)): shapes = np.shape(data[i]) data_listed = data[i].reshape(1, shapes[0] * shapes[1]) data_listed = data_listed.getA().tolist()[0] data_expanded.extend(data_listed) data_expanded = np.asarray(data_expanded) return data_expanded def _expand_mat(self, data_mat): # expanding matrix to one dimension list data_mat = np.asarray(data_mat) shapes = np.shape(data_mat) data_expanded = data_mat.reshape(1, shapes[0] * shapes[1]) return data_expanded def _calculate_gradient_from_pool( self, out_map, pd_pool, num_map, size_map, size_pooling ): """ calculate the gradient from the data slice of pool layer pd_pool: list of matrix out_map: the shape of data slice(size_map*size_map) return: pd_all: list of matrix, [num, size_map, size_map] """ pd_all = [] i_pool = 0 for i_map in range(num_map): pd_conv1 = np.ones((size_map, size_map)) for i in range(0, size_map, size_pooling): for j in range(0, size_map, size_pooling): pd_conv1[i : i + size_pooling, j : j + size_pooling] = pd_pool[ i_pool ] i_pool = i_pool + 1 pd_conv2 = np.multiply( pd_conv1, np.multiply(out_map[i_map], (1 - out_map[i_map])) ) pd_all.append(pd_conv2) return pd_all def train( self, patterns, datas_train, datas_teach, n_repeat, error_accuracy, draw_e=bool ): # model traning print("----------------------Start Training-------------------------") print((" - - Shape: Train_Data ", np.shape(datas_train))) print((" - - Shape: Teach_Data ", np.shape(datas_teach))) rp = 0 all_mse = [] mse = 10000 while rp < n_repeat and mse >= error_accuracy: error_count = 0 print("-------------Learning Time %d--------------" % rp) for p in range(len(datas_train)): # print('------------Learning Image: %d--------------'%p) data_train = np.asmatrix(datas_train[p]) data_teach = np.asarray(datas_teach[p]) data_focus1, data_conved1 = self.convolute( data_train, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) shape_featuremap1 = np.shape(data_conved1) """ print(' -----original shape ', np.shape(data_train)) print(' ---- after convolution ',np.shape(data_conv1)) print(' -----after pooling ',np.shape(data_pooled1)) """ data_bp_input = self._expand(data_pooled1) bp_out1 = data_bp_input bp_net_j = np.dot(bp_out1, self.vji.T) - self.thre_bp2 bp_out2 = self.sig(bp_net_j) bp_net_k = np.dot(bp_out2, self.wkj.T) - self.thre_bp3 bp_out3 = self.sig(bp_net_k) # --------------Model Leaning ------------------------ # calculate error and gradient--------------- pd_k_all = np.multiply( (data_teach - bp_out3), np.multiply(bp_out3, (1 - bp_out3)) ) pd_j_all = np.multiply( np.dot(pd_k_all, self.wkj), np.multiply(bp_out2, (1 - bp_out2)) ) pd_i_all = np.dot(pd_j_all, self.vji) pd_conv1_pooled = pd_i_all / (self.size_pooling1 * self.size_pooling1) pd_conv1_pooled = pd_conv1_pooled.T.getA().tolist() pd_conv1_all = self._calculate_gradient_from_pool( data_conved1, pd_conv1_pooled, shape_featuremap1[0], shape_featuremap1[1], self.size_pooling1, ) # weight and threshold learning process--------- # convolution layer for k_conv in range(self.conv1[1]): pd_conv_list = self._expand_mat(pd_conv1_all[k_conv]) delta_w = self.rate_weight * np.dot(pd_conv_list, data_focus1) self.w_conv1[k_conv] = self.w_conv1[k_conv] + delta_w.reshape( (self.conv1[0], self.conv1[0]) ) self.thre_conv1[k_conv] = ( self.thre_conv1[k_conv] - np.sum(pd_conv1_all[k_conv]) * self.rate_thre ) # all connected layer self.wkj = self.wkj + pd_k_all.T * bp_out2 * self.rate_weight self.vji = self.vji + pd_j_all.T * bp_out1 * self.rate_weight self.thre_bp3 = self.thre_bp3 - pd_k_all * self.rate_thre self.thre_bp2 = self.thre_bp2 - pd_j_all * self.rate_thre # calculate the sum error of all single image errors = np.sum(abs(data_teach - bp_out3)) error_count += errors # print(' ----Teach ',data_teach) # print(' ----BP_output ',bp_out3) rp = rp + 1 mse = error_count / patterns all_mse.append(mse) def draw_error(): yplot = [error_accuracy for i in range(int(n_repeat * 1.2))] plt.plot(all_mse, "+-") plt.plot(yplot, "r--") plt.xlabel("Learning Times") plt.ylabel("All_mse") plt.grid(True, alpha=0.5) plt.show() print("------------------Training Complished---------------------") print((" - - Training epoch: ", rp, f" - - Mse: {mse:.6f}")) if draw_e: draw_error() return mse def predict(self, datas_test): # model predict produce_out = [] print("-------------------Start Testing-------------------------") print((" - - Shape: Test_Data ", np.shape(datas_test))) for p in range(len(datas_test)): data_test = np.asmatrix(datas_test[p]) data_focus1, data_conved1 = self.convolute( data_test, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) data_bp_input = self._expand(data_pooled1) bp_out1 = data_bp_input bp_net_j = bp_out1 * self.vji.T - self.thre_bp2 bp_out2 = self.sig(bp_net_j) bp_net_k = bp_out2 * self.wkj.T - self.thre_bp3 bp_out3 = self.sig(bp_net_k) produce_out.extend(bp_out3.getA().tolist()) res = [list(map(self.do_round, each)) for each in produce_out] return np.asarray(res) def convolution(self, data): # return the data of image after convoluting process so we can check it out data_test = np.asmatrix(data) data_focus1, data_conved1 = self.convolute( data_test, self.conv1, self.w_conv1, self.thre_conv1, conv_step=self.step_conv1, ) data_pooled1 = self.pooling(data_conved1, self.size_pooling1) return data_conved1, data_pooled1 if __name__ == "__main__": """ I will put the example on other file """
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 __future__ import annotations from typing import Callable, Generic, TypeVar T = TypeVar("T") U = TypeVar("U") class DoubleLinkedListNode(Generic[T, U]): """ Double Linked List Node built specifically for LRU Cache >>> DoubleLinkedListNode(1,1) Node: key: 1, val: 1, has next: False, has prev: False """ def __init__(self, key: T | None, val: U | None): self.key = key self.val = val self.next: DoubleLinkedListNode[T, U] | None = None self.prev: DoubleLinkedListNode[T, U] | None = None def __repr__(self) -> str: return "Node: key: {}, val: {}, has next: {}, has prev: {}".format( self.key, self.val, self.next is not None, self.prev is not None ) class DoubleLinkedList(Generic[T, U]): """ Double Linked List built specifically for LRU Cache >>> dll: DoubleLinkedList = DoubleLinkedList() >>> dll DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: None, val: None, has next: False, has prev: True >>> first_node = DoubleLinkedListNode(1,10) >>> first_node Node: key: 1, val: 10, has next: False, has prev: False >>> dll.add(first_node) >>> dll DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 1, val: 10, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> # node is mutated >>> first_node Node: key: 1, val: 10, has next: True, has prev: True >>> second_node = DoubleLinkedListNode(2,20) >>> second_node Node: key: 2, val: 20, has next: False, has prev: False >>> dll.add(second_node) >>> dll DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 1, val: 10, has next: True, has prev: True, Node: key: 2, val: 20, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> removed_node = dll.remove(first_node) >>> assert removed_node == first_node >>> dll DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 2, val: 20, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> # Attempt to remove node not on list >>> removed_node = dll.remove(first_node) >>> removed_node is None True >>> # Attempt to remove head or rear >>> dll.head Node: key: None, val: None, has next: True, has prev: False >>> dll.remove(dll.head) is None True >>> # Attempt to remove head or rear >>> dll.rear Node: key: None, val: None, has next: False, has prev: True >>> dll.remove(dll.rear) is None True """ def __init__(self) -> None: self.head: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.rear: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.head.next, self.rear.prev = self.rear, self.head def __repr__(self) -> str: rep = ["DoubleLinkedList"] node = self.head while node.next is not None: rep.append(str(node)) node = node.next rep.append(str(self.rear)) return ",\n ".join(rep) def add(self, node: DoubleLinkedListNode[T, U]) -> None: """ Adds the given node to the end of the list (before rear) """ previous = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None previous.next = node node.prev = previous self.rear.prev = node node.next = self.rear def remove( self, node: DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: """ Removes and returns the given node from the list Returns None if node.prev or node.next is None """ if node.prev is None or node.next is None: return None node.prev.next = node.next node.next.prev = node.prev node.prev = None node.next = None return node class LRUCache(Generic[T, U]): """ LRU Cache to store a given capacity of data. Can be used as a stand-alone object or as a function decorator. >>> cache = LRUCache(2) >>> cache.set(1, 1) >>> cache.set(2, 2) >>> cache.get(1) 1 >>> cache.list DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 2, val: 2, has next: True, has prev: True, Node: key: 1, val: 1, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> cache.cache # doctest: +NORMALIZE_WHITESPACE {1: Node: key: 1, val: 1, has next: True, has prev: True, \ 2: Node: key: 2, val: 2, has next: True, has prev: True} >>> cache.set(3, 3) >>> cache.list DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 1, val: 1, has next: True, has prev: True, Node: key: 3, val: 3, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> cache.cache # doctest: +NORMALIZE_WHITESPACE {1: Node: key: 1, val: 1, has next: True, has prev: True, \ 3: Node: key: 3, val: 3, has next: True, has prev: True} >>> cache.get(2) is None True >>> cache.set(4, 4) >>> cache.get(1) is None True >>> cache.get(3) 3 >>> cache.get(4) 4 >>> cache CacheInfo(hits=3, misses=2, capacity=2, current size=2) >>> @LRUCache.decorator(100) ... def fib(num): ... if num in (1, 2): ... return 1 ... return fib(num - 1) + fib(num - 2) >>> for i in range(1, 100): ... res = fib(i) >>> fib.cache_info() CacheInfo(hits=194, misses=99, capacity=100, current size=99) """ # class variable to map the decorator functions to their respective instance decorator_function_to_instance_map: dict[Callable[[T], U], LRUCache[T, U]] = {} def __init__(self, capacity: int): self.list: DoubleLinkedList[T, U] = DoubleLinkedList() self.capacity = capacity self.num_keys = 0 self.hits = 0 self.miss = 0 self.cache: dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__(self) -> str: """ Return the details for the cache instance [hits, misses, capacity, current_size] """ return ( f"CacheInfo(hits={self.hits}, misses={self.miss}, " f"capacity={self.capacity}, current size={self.num_keys})" ) def __contains__(self, key: T) -> bool: """ >>> cache = LRUCache(1) >>> 1 in cache False >>> cache.set(1, 1) >>> 1 in cache True """ return key in self.cache def get(self, key: T) -> U | None: """ Returns the value for the input key and updates the Double Linked List. Returns None if key is not present in cache """ # Note: pythonic interface would throw KeyError rather than return None if key in self.cache: self.hits += 1 value_node: DoubleLinkedListNode[T, U] = self.cache[key] node = self.list.remove(self.cache[key]) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(node) return node.val self.miss += 1 return None def set(self, key: T, value: U) -> None: """ Sets the value for the input key and updates the Double Linked List """ if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity first_node = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(first_node) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 self.cache[key] = DoubleLinkedListNode(key, value) self.list.add(self.cache[key]) self.num_keys += 1 else: # bump node to the end of the list, update value node = self.list.remove(self.cache[key]) assert node is not None # node guaranteed to be in list node.val = value self.list.add(node) @classmethod def decorator( cls, size: int = 128 ) -> Callable[[Callable[[T], U]], Callable[..., U]]: """ Decorator version of LRU Cache Decorated function must be function of T -> U """ def cache_decorator_inner(func: Callable[[T], U]) -> Callable[..., U]: def cache_decorator_wrapper(*args: T) -> U: if func not in cls.decorator_function_to_instance_map: cls.decorator_function_to_instance_map[func] = LRUCache(size) result = cls.decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) cls.decorator_function_to_instance_map[func].set(args[0], result) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(cache_decorator_wrapper, "cache_info", cache_info) return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations from typing import Callable, Generic, TypeVar T = TypeVar("T") U = TypeVar("U") class DoubleLinkedListNode(Generic[T, U]): """ Double Linked List Node built specifically for LRU Cache >>> DoubleLinkedListNode(1,1) Node: key: 1, val: 1, has next: False, has prev: False """ def __init__(self, key: T | None, val: U | None): self.key = key self.val = val self.next: DoubleLinkedListNode[T, U] | None = None self.prev: DoubleLinkedListNode[T, U] | None = None def __repr__(self) -> str: return ( f"Node: key: {self.key}, val: {self.val}, " f"has next: {bool(self.next)}, has prev: {bool(self.prev)}" ) class DoubleLinkedList(Generic[T, U]): """ Double Linked List built specifically for LRU Cache >>> dll: DoubleLinkedList = DoubleLinkedList() >>> dll DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: None, val: None, has next: False, has prev: True >>> first_node = DoubleLinkedListNode(1,10) >>> first_node Node: key: 1, val: 10, has next: False, has prev: False >>> dll.add(first_node) >>> dll DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 1, val: 10, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> # node is mutated >>> first_node Node: key: 1, val: 10, has next: True, has prev: True >>> second_node = DoubleLinkedListNode(2,20) >>> second_node Node: key: 2, val: 20, has next: False, has prev: False >>> dll.add(second_node) >>> dll DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 1, val: 10, has next: True, has prev: True, Node: key: 2, val: 20, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> removed_node = dll.remove(first_node) >>> assert removed_node == first_node >>> dll DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 2, val: 20, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> # Attempt to remove node not on list >>> removed_node = dll.remove(first_node) >>> removed_node is None True >>> # Attempt to remove head or rear >>> dll.head Node: key: None, val: None, has next: True, has prev: False >>> dll.remove(dll.head) is None True >>> # Attempt to remove head or rear >>> dll.rear Node: key: None, val: None, has next: False, has prev: True >>> dll.remove(dll.rear) is None True """ def __init__(self) -> None: self.head: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.rear: DoubleLinkedListNode[T, U] = DoubleLinkedListNode(None, None) self.head.next, self.rear.prev = self.rear, self.head def __repr__(self) -> str: rep = ["DoubleLinkedList"] node = self.head while node.next is not None: rep.append(str(node)) node = node.next rep.append(str(self.rear)) return ",\n ".join(rep) def add(self, node: DoubleLinkedListNode[T, U]) -> None: """ Adds the given node to the end of the list (before rear) """ previous = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None previous.next = node node.prev = previous self.rear.prev = node node.next = self.rear def remove( self, node: DoubleLinkedListNode[T, U] ) -> DoubleLinkedListNode[T, U] | None: """ Removes and returns the given node from the list Returns None if node.prev or node.next is None """ if node.prev is None or node.next is None: return None node.prev.next = node.next node.next.prev = node.prev node.prev = None node.next = None return node class LRUCache(Generic[T, U]): """ LRU Cache to store a given capacity of data. Can be used as a stand-alone object or as a function decorator. >>> cache = LRUCache(2) >>> cache.set(1, 1) >>> cache.set(2, 2) >>> cache.get(1) 1 >>> cache.list DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 2, val: 2, has next: True, has prev: True, Node: key: 1, val: 1, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> cache.cache # doctest: +NORMALIZE_WHITESPACE {1: Node: key: 1, val: 1, has next: True, has prev: True, \ 2: Node: key: 2, val: 2, has next: True, has prev: True} >>> cache.set(3, 3) >>> cache.list DoubleLinkedList, Node: key: None, val: None, has next: True, has prev: False, Node: key: 1, val: 1, has next: True, has prev: True, Node: key: 3, val: 3, has next: True, has prev: True, Node: key: None, val: None, has next: False, has prev: True >>> cache.cache # doctest: +NORMALIZE_WHITESPACE {1: Node: key: 1, val: 1, has next: True, has prev: True, \ 3: Node: key: 3, val: 3, has next: True, has prev: True} >>> cache.get(2) is None True >>> cache.set(4, 4) >>> cache.get(1) is None True >>> cache.get(3) 3 >>> cache.get(4) 4 >>> cache CacheInfo(hits=3, misses=2, capacity=2, current size=2) >>> @LRUCache.decorator(100) ... def fib(num): ... if num in (1, 2): ... return 1 ... return fib(num - 1) + fib(num - 2) >>> for i in range(1, 100): ... res = fib(i) >>> fib.cache_info() CacheInfo(hits=194, misses=99, capacity=100, current size=99) """ # class variable to map the decorator functions to their respective instance decorator_function_to_instance_map: dict[Callable[[T], U], LRUCache[T, U]] = {} def __init__(self, capacity: int): self.list: DoubleLinkedList[T, U] = DoubleLinkedList() self.capacity = capacity self.num_keys = 0 self.hits = 0 self.miss = 0 self.cache: dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__(self) -> str: """ Return the details for the cache instance [hits, misses, capacity, current_size] """ return ( f"CacheInfo(hits={self.hits}, misses={self.miss}, " f"capacity={self.capacity}, current size={self.num_keys})" ) def __contains__(self, key: T) -> bool: """ >>> cache = LRUCache(1) >>> 1 in cache False >>> cache.set(1, 1) >>> 1 in cache True """ return key in self.cache def get(self, key: T) -> U | None: """ Returns the value for the input key and updates the Double Linked List. Returns None if key is not present in cache """ # Note: pythonic interface would throw KeyError rather than return None if key in self.cache: self.hits += 1 value_node: DoubleLinkedListNode[T, U] = self.cache[key] node = self.list.remove(self.cache[key]) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(node) return node.val self.miss += 1 return None def set(self, key: T, value: U) -> None: """ Sets the value for the input key and updates the Double Linked List """ if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity first_node = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(first_node) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 self.cache[key] = DoubleLinkedListNode(key, value) self.list.add(self.cache[key]) self.num_keys += 1 else: # bump node to the end of the list, update value node = self.list.remove(self.cache[key]) assert node is not None # node guaranteed to be in list node.val = value self.list.add(node) @classmethod def decorator( cls, size: int = 128 ) -> Callable[[Callable[[T], U]], Callable[..., U]]: """ Decorator version of LRU Cache Decorated function must be function of T -> U """ def cache_decorator_inner(func: Callable[[T], U]) -> Callable[..., U]: def cache_decorator_wrapper(*args: T) -> U: if func not in cls.decorator_function_to_instance_map: cls.decorator_function_to_instance_map[func] = LRUCache(size) result = cls.decorator_function_to_instance_map[func].get(args[0]) if result is None: result = func(*args) cls.decorator_function_to_instance_map[func].set(args[0], result) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(cache_decorator_wrapper, "cache_info", cache_info) return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
""" developed by: markmelnic original repo: https://github.com/markmelnic/Scoring-Algorithm Analyse data using a range based percentual proximity algorithm and calculate the linear maximum likelihood estimation. The basic principle is that all values supplied will be broken down to a range from 0 to 1 and each column's score will be added up to get the total score. ========== Example for data of vehicles price|mileage|registration_year 20k |60k |2012 22k |50k |2011 23k |90k |2015 16k |210k |2010 We want the vehicle with the lowest price, lowest mileage but newest registration year. Thus the weights for each column are as follows: [0, 0, 1] """ def procentual_proximity( source_data: list[list[float]], weights: list[int] ) -> list[list[float]]: """ weights - int list possible values - 0 / 1 0 if lower values have higher weight in the data set 1 if higher values have higher weight in the data set >>> procentual_proximity([[20, 60, 2012],[23, 90, 2015],[22, 50, 2011]], [0, 0, 1]) [[20, 60, 2012, 2.0], [23, 90, 2015, 1.0], [22, 50, 2011, 1.3333333333333335]] """ # getting data data_lists: list[list[float]] = [] for data in source_data: for i, el in enumerate(data): if len(data_lists) < i + 1: data_lists.append([]) data_lists[i].append(float(el)) score_lists: list[list[float]] = [] # calculating each score for dlist, weight in zip(data_lists, weights): mind = min(dlist) maxd = max(dlist) score: list[float] = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind))) except ZeroDivisionError: score.append(1) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind)) except ZeroDivisionError: score.append(0) # weight not 0 or 1 else: raise ValueError("Invalid weight of %f provided" % (weight)) score_lists.append(score) # initialize final scores final_scores: list[float] = [0 for i in range(len(score_lists[0]))] # generate final scores for i, slist in enumerate(score_lists): for j, ele in enumerate(slist): final_scores[j] = final_scores[j] + ele # append scores to source data for i, ele in enumerate(final_scores): source_data[i].append(ele) return source_data
""" developed by: markmelnic original repo: https://github.com/markmelnic/Scoring-Algorithm Analyse data using a range based percentual proximity algorithm and calculate the linear maximum likelihood estimation. The basic principle is that all values supplied will be broken down to a range from 0 to 1 and each column's score will be added up to get the total score. ========== Example for data of vehicles price|mileage|registration_year 20k |60k |2012 22k |50k |2011 23k |90k |2015 16k |210k |2010 We want the vehicle with the lowest price, lowest mileage but newest registration year. Thus the weights for each column are as follows: [0, 0, 1] """ def procentual_proximity( source_data: list[list[float]], weights: list[int] ) -> list[list[float]]: """ weights - int list possible values - 0 / 1 0 if lower values have higher weight in the data set 1 if higher values have higher weight in the data set >>> procentual_proximity([[20, 60, 2012],[23, 90, 2015],[22, 50, 2011]], [0, 0, 1]) [[20, 60, 2012, 2.0], [23, 90, 2015, 1.0], [22, 50, 2011, 1.3333333333333335]] """ # getting data data_lists: list[list[float]] = [] for data in source_data: for i, el in enumerate(data): if len(data_lists) < i + 1: data_lists.append([]) data_lists[i].append(float(el)) score_lists: list[list[float]] = [] # calculating each score for dlist, weight in zip(data_lists, weights): mind = min(dlist) maxd = max(dlist) score: list[float] = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind))) except ZeroDivisionError: score.append(1) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind)) except ZeroDivisionError: score.append(0) # weight not 0 or 1 else: raise ValueError(f"Invalid weight of {weight:f} provided") score_lists.append(score) # initialize final scores final_scores: list[float] = [0 for i in range(len(score_lists[0]))] # generate final scores for i, slist in enumerate(score_lists): for j, ele in enumerate(slist): final_scores[j] = final_scores[j] + ele # append scores to source data for i, ele in enumerate(final_scores): source_data[i].append(ele) return source_data
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
""" Shortest job remaining first Please note arrival time and burst Please use spaces to separate times entered. """ from __future__ import annotations import pandas as pd def calculate_waitingtime( arrival_time: list[int], burst_time: list[int], no_of_processes: int ) -> list[int]: """ Calculate the waiting time of each processes Return: List of waiting times. >>> calculate_waitingtime([1,2,3,4],[3,3,5,1],4) [0, 3, 5, 0] >>> calculate_waitingtime([1,2,3],[2,5,1],3) [0, 2, 0] >>> calculate_waitingtime([2,3],[5,1],2) [1, 0] """ remaining_time = [0] * no_of_processes waiting_time = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(no_of_processes): remaining_time[i] = burst_time[i] complete = 0 increment_time = 0 minm = 999999999 short = 0 check = False # Process until all processes are completed while complete != no_of_processes: for j in range(no_of_processes): if arrival_time[j] <= increment_time: if remaining_time[j] > 0: if remaining_time[j] < minm: minm = remaining_time[j] short = j check = True if not check: increment_time += 1 continue remaining_time[short] -= 1 minm = remaining_time[short] if minm == 0: minm = 999999999 if remaining_time[short] == 0: complete += 1 check = False # Find finish time of current process finish_time = increment_time + 1 # Calculate waiting time finar = finish_time - arrival_time[short] waiting_time[short] = finar - burst_time[short] if waiting_time[short] < 0: waiting_time[short] = 0 # Increment time increment_time += 1 return waiting_time def calculate_turnaroundtime( burst_time: list[int], no_of_processes: int, waiting_time: list[int] ) -> list[int]: """ Calculate the turn around time of each Processes Return: list of turn around times. >>> calculate_turnaroundtime([3,3,5,1], 4, [0,3,5,0]) [3, 6, 10, 1] >>> calculate_turnaroundtime([3,3], 2, [0,3]) [3, 6] >>> calculate_turnaroundtime([8,10,1], 3, [1,0,3]) [9, 10, 4] """ turn_around_time = [0] * no_of_processes for i in range(no_of_processes): turn_around_time[i] = burst_time[i] + waiting_time[i] return turn_around_time def calculate_average_times( waiting_time: list[int], turn_around_time: list[int], no_of_processes: int ) -> None: """ This function calculates the average of the waiting & turnaround times Prints: Average Waiting time & Average Turn Around Time >>> calculate_average_times([0,3,5,0],[3,6,10,1],4) Average waiting time = 2.00000 Average turn around time = 5.0 >>> calculate_average_times([2,3],[3,6],2) Average waiting time = 2.50000 Average turn around time = 4.5 >>> calculate_average_times([10,4,3],[2,7,6],3) Average waiting time = 5.66667 Average turn around time = 5.0 """ total_waiting_time = 0 total_turn_around_time = 0 for i in range(no_of_processes): total_waiting_time = total_waiting_time + waiting_time[i] total_turn_around_time = total_turn_around_time + turn_around_time[i] print("Average waiting time = %.5f" % (total_waiting_time / no_of_processes)) print("Average turn around time =", total_turn_around_time / no_of_processes) if __name__ == "__main__": print("Enter how many process you want to analyze") no_of_processes = int(input()) burst_time = [0] * no_of_processes arrival_time = [0] * no_of_processes processes = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print("Enter the arrival time and burst time for process:--" + str(i + 1)) arrival_time[i], burst_time[i] = map(int, input().split()) waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes) bt = burst_time n = no_of_processes wt = waiting_time turn_around_time = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) fcfs = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ "Process", "BurstTime", "ArrivalTime", "WaitingTime", "TurnAroundTime", ], ) # Printing the dataFrame pd.set_option("display.max_rows", fcfs.shape[0] + 1) print(fcfs)
""" Shortest job remaining first Please note arrival time and burst Please use spaces to separate times entered. """ from __future__ import annotations import pandas as pd def calculate_waitingtime( arrival_time: list[int], burst_time: list[int], no_of_processes: int ) -> list[int]: """ Calculate the waiting time of each processes Return: List of waiting times. >>> calculate_waitingtime([1,2,3,4],[3,3,5,1],4) [0, 3, 5, 0] >>> calculate_waitingtime([1,2,3],[2,5,1],3) [0, 2, 0] >>> calculate_waitingtime([2,3],[5,1],2) [1, 0] """ remaining_time = [0] * no_of_processes waiting_time = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(no_of_processes): remaining_time[i] = burst_time[i] complete = 0 increment_time = 0 minm = 999999999 short = 0 check = False # Process until all processes are completed while complete != no_of_processes: for j in range(no_of_processes): if arrival_time[j] <= increment_time: if remaining_time[j] > 0: if remaining_time[j] < minm: minm = remaining_time[j] short = j check = True if not check: increment_time += 1 continue remaining_time[short] -= 1 minm = remaining_time[short] if minm == 0: minm = 999999999 if remaining_time[short] == 0: complete += 1 check = False # Find finish time of current process finish_time = increment_time + 1 # Calculate waiting time finar = finish_time - arrival_time[short] waiting_time[short] = finar - burst_time[short] if waiting_time[short] < 0: waiting_time[short] = 0 # Increment time increment_time += 1 return waiting_time def calculate_turnaroundtime( burst_time: list[int], no_of_processes: int, waiting_time: list[int] ) -> list[int]: """ Calculate the turn around time of each Processes Return: list of turn around times. >>> calculate_turnaroundtime([3,3,5,1], 4, [0,3,5,0]) [3, 6, 10, 1] >>> calculate_turnaroundtime([3,3], 2, [0,3]) [3, 6] >>> calculate_turnaroundtime([8,10,1], 3, [1,0,3]) [9, 10, 4] """ turn_around_time = [0] * no_of_processes for i in range(no_of_processes): turn_around_time[i] = burst_time[i] + waiting_time[i] return turn_around_time def calculate_average_times( waiting_time: list[int], turn_around_time: list[int], no_of_processes: int ) -> None: """ This function calculates the average of the waiting & turnaround times Prints: Average Waiting time & Average Turn Around Time >>> calculate_average_times([0,3,5,0],[3,6,10,1],4) Average waiting time = 2.00000 Average turn around time = 5.0 >>> calculate_average_times([2,3],[3,6],2) Average waiting time = 2.50000 Average turn around time = 4.5 >>> calculate_average_times([10,4,3],[2,7,6],3) Average waiting time = 5.66667 Average turn around time = 5.0 """ total_waiting_time = 0 total_turn_around_time = 0 for i in range(no_of_processes): total_waiting_time = total_waiting_time + waiting_time[i] total_turn_around_time = total_turn_around_time + turn_around_time[i] print(f"Average waiting time = {total_waiting_time / no_of_processes:.5f}") print("Average turn around time =", total_turn_around_time / no_of_processes) if __name__ == "__main__": print("Enter how many process you want to analyze") no_of_processes = int(input()) burst_time = [0] * no_of_processes arrival_time = [0] * no_of_processes processes = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print("Enter the arrival time and burst time for process:--" + str(i + 1)) arrival_time[i], burst_time[i] = map(int, input().split()) waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes) bt = burst_time n = no_of_processes wt = waiting_time turn_around_time = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) fcfs = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ "Process", "BurstTime", "ArrivalTime", "WaitingTime", "TurnAroundTime", ], ) # Printing the dataFrame pd.set_option("display.max_rows", fcfs.shape[0] + 1) print(fcfs)
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
# flake8: noqa """ This is pure Python implementation of tree traversal algorithms """ from __future__ import annotations import queue class TreeNode: def __init__(self, data): self.data = data self.right = None self.left = None def build_tree(): print("\n********Press N to stop entering at any point of time********\n") check = input("Enter the value of the root node: ").strip().lower() or "n" if check == "n": return None q: queue.Queue = queue.Queue() tree_node = TreeNode(int(check)) q.put(tree_node) while not q.empty(): node_found = q.get() msg = "Enter the left node of %s: " % node_found.data check = input(msg).strip().lower() or "n" if check == "n": return tree_node left_node = TreeNode(int(check)) node_found.left = left_node q.put(left_node) msg = "Enter the right node of %s: " % node_found.data check = input(msg).strip().lower() or "n" if check == "n": return tree_node right_node = TreeNode(int(check)) node_found.right = right_node q.put(right_node) def pre_order(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> pre_order(root) 1,2,4,5,3,6,7, """ if not isinstance(node, TreeNode) or not node: return print(node.data, end=",") pre_order(node.left) pre_order(node.right) def in_order(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> in_order(root) 4,2,5,1,6,3,7, """ if not isinstance(node, TreeNode) or not node: return in_order(node.left) print(node.data, end=",") in_order(node.right) def post_order(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> post_order(root) 4,5,2,6,7,3,1, """ if not isinstance(node, TreeNode) or not node: return post_order(node.left) post_order(node.right) print(node.data, end=",") def level_order(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> level_order(root) 1,2,3,4,5,6,7, """ if not isinstance(node, TreeNode) or not node: return q: queue.Queue = queue.Queue() q.put(node) while not q.empty(): node_dequeued = q.get() print(node_dequeued.data, end=",") if node_dequeued.left: q.put(node_dequeued.left) if node_dequeued.right: q.put(node_dequeued.right) def level_order_actual(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> level_order_actual(root) 1, 2,3, 4,5,6,7, """ if not isinstance(node, TreeNode) or not node: return q: queue.Queue = queue.Queue() q.put(node) while not q.empty(): list = [] while not q.empty(): node_dequeued = q.get() print(node_dequeued.data, end=",") if node_dequeued.left: list.append(node_dequeued.left) if node_dequeued.right: list.append(node_dequeued.right) print() for node in list: q.put(node) # iteration version def pre_order_iter(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> pre_order_iter(root) 1,2,4,5,3,6,7, """ if not isinstance(node, TreeNode) or not node: return stack: list[TreeNode] = [] n = node while n or stack: while n: # start from root node, find its left child print(n.data, end=",") stack.append(n) n = n.left # end of while means current node doesn't have left child n = stack.pop() # start to traverse its right child n = n.right def in_order_iter(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> in_order_iter(root) 4,2,5,1,6,3,7, """ if not isinstance(node, TreeNode) or not node: return stack: list[TreeNode] = [] n = node while n or stack: while n: stack.append(n) n = n.left n = stack.pop() print(n.data, end=",") n = n.right def post_order_iter(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> post_order_iter(root) 4,5,2,6,7,3,1, """ if not isinstance(node, TreeNode) or not node: return stack1, stack2 = [], [] n = node stack1.append(n) while stack1: # to find the reversed order of post order, store it in stack2 n = stack1.pop() if n.left: stack1.append(n.left) if n.right: stack1.append(n.right) stack2.append(n) while stack2: # pop up from stack2 will be the post order print(stack2.pop().data, end=",") def prompt(s: str = "", width=50, char="*") -> str: if not s: return "\n" + width * char left, extra = divmod(width - len(s) - 2, 2) return f"{left * char} {s} {(left + extra) * char}" if __name__ == "__main__": import doctest doctest.testmod() print(prompt("Binary Tree Traversals")) node = build_tree() print(prompt("Pre Order Traversal")) pre_order(node) print(prompt() + "\n") print(prompt("In Order Traversal")) in_order(node) print(prompt() + "\n") print(prompt("Post Order Traversal")) post_order(node) print(prompt() + "\n") print(prompt("Level Order Traversal")) level_order(node) print(prompt() + "\n") print(prompt("Actual Level Order Traversal")) level_order_actual(node) print("*" * 50 + "\n") print(prompt("Pre Order Traversal - Iteration Version")) pre_order_iter(node) print(prompt() + "\n") print(prompt("In Order Traversal - Iteration Version")) in_order_iter(node) print(prompt() + "\n") print(prompt("Post Order Traversal - Iteration Version")) post_order_iter(node) print(prompt())
# flake8: noqa """ This is pure Python implementation of tree traversal algorithms """ from __future__ import annotations import queue class TreeNode: def __init__(self, data): self.data = data self.right = None self.left = None def build_tree(): print("\n********Press N to stop entering at any point of time********\n") check = input("Enter the value of the root node: ").strip().lower() or "n" if check == "n": return None q: queue.Queue = queue.Queue() tree_node = TreeNode(int(check)) q.put(tree_node) while not q.empty(): node_found = q.get() msg = f"Enter the left node of {node_found.data}: " check = input(msg).strip().lower() or "n" if check == "n": return tree_node left_node = TreeNode(int(check)) node_found.left = left_node q.put(left_node) msg = f"Enter the right node of {node_found.data}: " check = input(msg).strip().lower() or "n" if check == "n": return tree_node right_node = TreeNode(int(check)) node_found.right = right_node q.put(right_node) def pre_order(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> pre_order(root) 1,2,4,5,3,6,7, """ if not isinstance(node, TreeNode) or not node: return print(node.data, end=",") pre_order(node.left) pre_order(node.right) def in_order(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> in_order(root) 4,2,5,1,6,3,7, """ if not isinstance(node, TreeNode) or not node: return in_order(node.left) print(node.data, end=",") in_order(node.right) def post_order(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> post_order(root) 4,5,2,6,7,3,1, """ if not isinstance(node, TreeNode) or not node: return post_order(node.left) post_order(node.right) print(node.data, end=",") def level_order(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> level_order(root) 1,2,3,4,5,6,7, """ if not isinstance(node, TreeNode) or not node: return q: queue.Queue = queue.Queue() q.put(node) while not q.empty(): node_dequeued = q.get() print(node_dequeued.data, end=",") if node_dequeued.left: q.put(node_dequeued.left) if node_dequeued.right: q.put(node_dequeued.right) def level_order_actual(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> level_order_actual(root) 1, 2,3, 4,5,6,7, """ if not isinstance(node, TreeNode) or not node: return q: queue.Queue = queue.Queue() q.put(node) while not q.empty(): list = [] while not q.empty(): node_dequeued = q.get() print(node_dequeued.data, end=",") if node_dequeued.left: list.append(node_dequeued.left) if node_dequeued.right: list.append(node_dequeued.right) print() for node in list: q.put(node) # iteration version def pre_order_iter(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> pre_order_iter(root) 1,2,4,5,3,6,7, """ if not isinstance(node, TreeNode) or not node: return stack: list[TreeNode] = [] n = node while n or stack: while n: # start from root node, find its left child print(n.data, end=",") stack.append(n) n = n.left # end of while means current node doesn't have left child n = stack.pop() # start to traverse its right child n = n.right def in_order_iter(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> in_order_iter(root) 4,2,5,1,6,3,7, """ if not isinstance(node, TreeNode) or not node: return stack: list[TreeNode] = [] n = node while n or stack: while n: stack.append(n) n = n.left n = stack.pop() print(n.data, end=",") n = n.right def post_order_iter(node: TreeNode) -> None: """ >>> root = TreeNode(1) >>> tree_node2 = TreeNode(2) >>> tree_node3 = TreeNode(3) >>> tree_node4 = TreeNode(4) >>> tree_node5 = TreeNode(5) >>> tree_node6 = TreeNode(6) >>> tree_node7 = TreeNode(7) >>> root.left, root.right = tree_node2, tree_node3 >>> tree_node2.left, tree_node2.right = tree_node4 , tree_node5 >>> tree_node3.left, tree_node3.right = tree_node6 , tree_node7 >>> post_order_iter(root) 4,5,2,6,7,3,1, """ if not isinstance(node, TreeNode) or not node: return stack1, stack2 = [], [] n = node stack1.append(n) while stack1: # to find the reversed order of post order, store it in stack2 n = stack1.pop() if n.left: stack1.append(n.left) if n.right: stack1.append(n.right) stack2.append(n) while stack2: # pop up from stack2 will be the post order print(stack2.pop().data, end=",") def prompt(s: str = "", width=50, char="*") -> str: if not s: return "\n" + width * char left, extra = divmod(width - len(s) - 2, 2) return f"{left * char} {s} {(left + extra) * char}" if __name__ == "__main__": import doctest doctest.testmod() print(prompt("Binary Tree Traversals")) node = build_tree() print(prompt("Pre Order Traversal")) pre_order(node) print(prompt() + "\n") print(prompt("In Order Traversal")) in_order(node) print(prompt() + "\n") print(prompt("Post Order Traversal")) post_order(node) print(prompt() + "\n") print(prompt("Level Order Traversal")) level_order(node) print(prompt() + "\n") print(prompt("Actual Level Order Traversal")) level_order_actual(node) print("*" * 50 + "\n") print(prompt("Pre Order Traversal - Iteration Version")) pre_order_iter(node) print(prompt() + "\n") print(prompt("In Order Traversal - Iteration Version")) in_order_iter(node) print(prompt() + "\n") print(prompt("Post Order Traversal - Iteration Version")) post_order_iter(node) print(prompt())
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
""" Algorithm for calculating the most cost-efficient sequence for converting one string into another. The only allowed operations are --- Cost to copy a character is copy_cost --- Cost to replace a character is replace_cost --- Cost to delete a character is delete_cost --- Cost to insert a character is insert_cost """ def compute_transform_tables( source_string: str, destination_string: str, copy_cost: int, replace_cost: int, delete_cost: int, insert_cost: int, ) -> tuple[list[list[int]], list[list[str]]]: source_seq = list(source_string) destination_seq = list(destination_string) len_source_seq = len(source_seq) len_destination_seq = len(destination_seq) costs = [ [0 for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1) ] ops = [ ["0" for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1) ] for i in range(1, len_source_seq + 1): costs[i][0] = i * delete_cost ops[i][0] = "D%c" % source_seq[i - 1] for i in range(1, len_destination_seq + 1): costs[0][i] = i * insert_cost ops[0][i] = "I%c" % destination_seq[i - 1] for i in range(1, len_source_seq + 1): for j in range(1, len_destination_seq + 1): if source_seq[i - 1] == destination_seq[j - 1]: costs[i][j] = costs[i - 1][j - 1] + copy_cost ops[i][j] = "C%c" % source_seq[i - 1] else: costs[i][j] = costs[i - 1][j - 1] + replace_cost ops[i][j] = "R%c" % source_seq[i - 1] + str(destination_seq[j - 1]) if costs[i - 1][j] + delete_cost < costs[i][j]: costs[i][j] = costs[i - 1][j] + delete_cost ops[i][j] = "D%c" % source_seq[i - 1] if costs[i][j - 1] + insert_cost < costs[i][j]: costs[i][j] = costs[i][j - 1] + insert_cost ops[i][j] = "I%c" % destination_seq[j - 1] return costs, ops def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]: if i == 0 and j == 0: return [] else: if ops[i][j][0] == "C" or ops[i][j][0] == "R": seq = assemble_transformation(ops, i - 1, j - 1) seq.append(ops[i][j]) return seq elif ops[i][j][0] == "D": seq = assemble_transformation(ops, i - 1, j) seq.append(ops[i][j]) return seq else: seq = assemble_transformation(ops, i, j - 1) seq.append(ops[i][j]) return seq if __name__ == "__main__": _, operations = compute_transform_tables("Python", "Algorithms", -1, 1, 2, 2) m = len(operations) n = len(operations[0]) sequence = assemble_transformation(operations, m - 1, n - 1) string = list("Python") i = 0 cost = 0 with open("min_cost.txt", "w") as file: for op in sequence: print("".join(string)) if op[0] == "C": file.write("%-16s" % "Copy %c" % op[1]) file.write("\t\t\t" + "".join(string)) file.write("\r\n") cost -= 1 elif op[0] == "R": string[i] = op[2] file.write("%-16s" % ("Replace %c" % op[1] + " with " + str(op[2]))) file.write("\t\t" + "".join(string)) file.write("\r\n") cost += 1 elif op[0] == "D": string.pop(i) file.write("%-16s" % "Delete %c" % op[1]) file.write("\t\t\t" + "".join(string)) file.write("\r\n") cost += 2 else: string.insert(i, op[1]) file.write("%-16s" % "Insert %c" % op[1]) file.write("\t\t\t" + "".join(string)) file.write("\r\n") cost += 2 i += 1 print("".join(string)) print("Cost: ", cost) file.write("\r\nMinimum cost: " + str(cost))
""" Algorithm for calculating the most cost-efficient sequence for converting one string into another. The only allowed operations are --- Cost to copy a character is copy_cost --- Cost to replace a character is replace_cost --- Cost to delete a character is delete_cost --- Cost to insert a character is insert_cost """ def compute_transform_tables( source_string: str, destination_string: str, copy_cost: int, replace_cost: int, delete_cost: int, insert_cost: int, ) -> tuple[list[list[int]], list[list[str]]]: source_seq = list(source_string) destination_seq = list(destination_string) len_source_seq = len(source_seq) len_destination_seq = len(destination_seq) costs = [ [0 for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1) ] ops = [ ["0" for _ in range(len_destination_seq + 1)] for _ in range(len_source_seq + 1) ] for i in range(1, len_source_seq + 1): costs[i][0] = i * delete_cost ops[i][0] = f"D{source_seq[i - 1]:c}" for i in range(1, len_destination_seq + 1): costs[0][i] = i * insert_cost ops[0][i] = f"I{destination_seq[i - 1]:c}" for i in range(1, len_source_seq + 1): for j in range(1, len_destination_seq + 1): if source_seq[i - 1] == destination_seq[j - 1]: costs[i][j] = costs[i - 1][j - 1] + copy_cost ops[i][j] = f"C{source_seq[i - 1]:c}" else: costs[i][j] = costs[i - 1][j - 1] + replace_cost ops[i][j] = f"R{source_seq[i - 1]:c}" + str(destination_seq[j - 1]) if costs[i - 1][j] + delete_cost < costs[i][j]: costs[i][j] = costs[i - 1][j] + delete_cost ops[i][j] = f"D{source_seq[i - 1]:c}" if costs[i][j - 1] + insert_cost < costs[i][j]: costs[i][j] = costs[i][j - 1] + insert_cost ops[i][j] = f"I{destination_seq[j - 1]:c}" return costs, ops def assemble_transformation(ops: list[list[str]], i: int, j: int) -> list[str]: if i == 0 and j == 0: return [] else: if ops[i][j][0] == "C" or ops[i][j][0] == "R": seq = assemble_transformation(ops, i - 1, j - 1) seq.append(ops[i][j]) return seq elif ops[i][j][0] == "D": seq = assemble_transformation(ops, i - 1, j) seq.append(ops[i][j]) return seq else: seq = assemble_transformation(ops, i, j - 1) seq.append(ops[i][j]) return seq if __name__ == "__main__": _, operations = compute_transform_tables("Python", "Algorithms", -1, 1, 2, 2) m = len(operations) n = len(operations[0]) sequence = assemble_transformation(operations, m - 1, n - 1) string = list("Python") i = 0 cost = 0 with open("min_cost.txt", "w") as file: for op in sequence: print("".join(string)) if op[0] == "C": file.write("%-16s" % "Copy %c" % op[1]) file.write("\t\t\t" + "".join(string)) file.write("\r\n") cost -= 1 elif op[0] == "R": string[i] = op[2] file.write("%-16s" % ("Replace %c" % op[1] + " with " + str(op[2]))) file.write("\t\t" + "".join(string)) file.write("\r\n") cost += 1 elif op[0] == "D": string.pop(i) file.write("%-16s" % "Delete %c" % op[1]) file.write("\t\t\t" + "".join(string)) file.write("\r\n") cost += 2 else: string.insert(i, op[1]) file.write("%-16s" % "Insert %c" % op[1]) file.write("\t\t\t" + "".join(string)) file.write("\r\n") cost += 2 i += 1 print("".join(string)) print("Cost: ", cost) file.write("\r\nMinimum cost: " + str(cost))
1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 simple bare-minimum quantum circuit that starts with a single qubit (by default, in state 0), runs the experiment 1000 times, and finally prints the total count of the states finally observed. Qiskit Docs: https://qiskit.org/documentation/getting_started.html """ import qiskit as q def single_qubit_measure(qubits: int, classical_bits: int) -> q.result.counts.Counts: """ >>> single_qubit_measure(1, 1) {'0': 1000} """ # Use Aer's qasm_simulator simulator = q.Aer.get_backend("qasm_simulator") # Create a Quantum Circuit acting on the q register circuit = q.QuantumCircuit(qubits, classical_bits) # Map the quantum measurement to the classical bits circuit.measure([0], [0]) # Execute the circuit on the qasm simulator job = q.execute(circuit, simulator, shots=1000) # Return the histogram data of the results of the experiment. return job.result().get_counts(circuit) if __name__ == "__main__": print(f"Total count for various states are: {single_qubit_measure(1, 1)}")
#!/usr/bin/env python3 """ Build a simple bare-minimum quantum circuit that starts with a single qubit (by default, in state 0), runs the experiment 1000 times, and finally prints the total count of the states finally observed. Qiskit Docs: https://qiskit.org/documentation/getting_started.html """ import qiskit as q def single_qubit_measure(qubits: int, classical_bits: int) -> q.result.counts.Counts: """ >>> single_qubit_measure(1, 1) {'0': 1000} """ # Use Aer's qasm_simulator simulator = q.Aer.get_backend("qasm_simulator") # Create a Quantum Circuit acting on the q register circuit = q.QuantumCircuit(qubits, classical_bits) # Map the quantum measurement to the classical bits circuit.measure([0], [0]) # Execute the circuit on the qasm simulator job = q.execute(circuit, simulator, shots=1000) # Return the histogram data of the results of the experiment. return job.result().get_counts(circuit) if __name__ == "__main__": print(f"Total count for various states are: {single_qubit_measure(1, 1)}")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
""" This is a python3 implementation of binary search tree using recursion To run tests: python -m unittest binary_search_tree_recursive.py To run an example: python binary_search_tree_recursive.py """ from __future__ import annotations import unittest from typing import Iterator class Node: def __init__(self, label: int, parent: Node | None) -> None: self.label = label self.parent = parent self.left: Node | None = None self.right: Node | None = None class BinarySearchTree: def __init__(self) -> None: self.root: Node | None = None def empty(self) -> None: """ Empties the tree >>> t = BinarySearchTree() >>> assert t.root is None >>> t.put(8) >>> assert t.root is not None """ self.root = None def is_empty(self) -> bool: """ Checks if the tree is empty >>> t = BinarySearchTree() >>> t.is_empty() True >>> t.put(8) >>> t.is_empty() False """ return self.root is None def put(self, label: int) -> None: """ Put a new node in the tree >>> t = BinarySearchTree() >>> t.put(8) >>> assert t.root.parent is None >>> assert t.root.label == 8 >>> t.put(10) >>> assert t.root.right.parent == t.root >>> assert t.root.right.label == 10 >>> t.put(3) >>> assert t.root.left.parent == t.root >>> assert t.root.left.label == 3 """ self.root = self._put(self.root, label) def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Node: if node is None: node = Node(label, parent) else: if label < node.label: node.left = self._put(node.left, label, node) elif label > node.label: node.right = self._put(node.right, label, node) else: raise Exception(f"Node with label {label} already exists") return node def search(self, label: int) -> Node: """ Searches a node in the tree >>> t = BinarySearchTree() >>> t.put(8) >>> t.put(10) >>> node = t.search(8) >>> assert node.label == 8 >>> node = t.search(3) Traceback (most recent call last): ... Exception: Node with label 3 does not exist """ return self._search(self.root, label) def _search(self, node: Node | None, label: int) -> Node: if node is None: raise Exception(f"Node with label {label} does not exist") else: if label < node.label: node = self._search(node.left, label) elif label > node.label: node = self._search(node.right, label) return node def remove(self, label: int) -> None: """ Removes a node in the tree >>> t = BinarySearchTree() >>> t.put(8) >>> t.put(10) >>> t.remove(8) >>> assert t.root.label == 10 >>> t.remove(3) Traceback (most recent call last): ... Exception: Node with label 3 does not exist """ node = self.search(label) if node.right and node.left: lowest_node = self._get_lowest_node(node.right) lowest_node.left = node.left lowest_node.right = node.right node.left.parent = lowest_node if node.right: node.right.parent = lowest_node self._reassign_nodes(node, lowest_node) elif not node.right and node.left: self._reassign_nodes(node, node.left) elif node.right and not node.left: self._reassign_nodes(node, node.right) else: self._reassign_nodes(node, None) def _reassign_nodes(self, node: Node, new_children: Node | None) -> None: if new_children: new_children.parent = node.parent if node.parent: if node.parent.right == node: node.parent.right = new_children else: node.parent.left = new_children else: self.root = new_children def _get_lowest_node(self, node: Node) -> Node: if node.left: lowest_node = self._get_lowest_node(node.left) else: lowest_node = node self._reassign_nodes(node, node.right) return lowest_node def exists(self, label: int) -> bool: """ Checks if a node exists in the tree >>> t = BinarySearchTree() >>> t.put(8) >>> t.put(10) >>> t.exists(8) True >>> t.exists(3) False """ try: self.search(label) return True except Exception: return False def get_max_label(self) -> int: """ Gets the max label inserted in the tree >>> t = BinarySearchTree() >>> t.get_max_label() Traceback (most recent call last): ... Exception: Binary search tree is empty >>> t.put(8) >>> t.put(10) >>> t.get_max_label() 10 """ if self.root is None: raise Exception("Binary search tree is empty") node = self.root while node.right is not None: node = node.right return node.label def get_min_label(self) -> int: """ Gets the min label inserted in the tree >>> t = BinarySearchTree() >>> t.get_min_label() Traceback (most recent call last): ... Exception: Binary search tree is empty >>> t.put(8) >>> t.put(10) >>> t.get_min_label() 8 """ if self.root is None: raise Exception("Binary search tree is empty") node = self.root while node.left is not None: node = node.left return node.label def inorder_traversal(self) -> Iterator[Node]: """ Return the inorder traversal of the tree >>> t = BinarySearchTree() >>> [i.label for i in t.inorder_traversal()] [] >>> t.put(8) >>> t.put(10) >>> t.put(9) >>> [i.label for i in t.inorder_traversal()] [8, 9, 10] """ return self._inorder_traversal(self.root) def _inorder_traversal(self, node: Node | None) -> Iterator[Node]: if node is not None: yield from self._inorder_traversal(node.left) yield node yield from self._inorder_traversal(node.right) def preorder_traversal(self) -> Iterator[Node]: """ Return the preorder traversal of the tree >>> t = BinarySearchTree() >>> [i.label for i in t.preorder_traversal()] [] >>> t.put(8) >>> t.put(10) >>> t.put(9) >>> [i.label for i in t.preorder_traversal()] [8, 10, 9] """ return self._preorder_traversal(self.root) def _preorder_traversal(self, node: Node | None) -> Iterator[Node]: if node is not None: yield node yield from self._preorder_traversal(node.left) yield from self._preorder_traversal(node.right) class BinarySearchTreeTest(unittest.TestCase): @staticmethod def _get_binary_search_tree() -> BinarySearchTree: r""" 8 / \ 3 10 / \ \ 1 6 14 / \ / 4 7 13 \ 5 """ t = BinarySearchTree() t.put(8) t.put(3) t.put(6) t.put(1) t.put(10) t.put(14) t.put(13) t.put(4) t.put(7) t.put(5) return t def test_put(self) -> None: t = BinarySearchTree() assert t.is_empty() t.put(8) r""" 8 """ assert t.root is not None assert t.root.parent is None assert t.root.label == 8 t.put(10) r""" 8 \ 10 """ assert t.root.right is not None assert t.root.right.parent == t.root assert t.root.right.label == 10 t.put(3) r""" 8 / \ 3 10 """ assert t.root.left is not None assert t.root.left.parent == t.root assert t.root.left.label == 3 t.put(6) r""" 8 / \ 3 10 \ 6 """ assert t.root.left.right is not None assert t.root.left.right.parent == t.root.left assert t.root.left.right.label == 6 t.put(1) r""" 8 / \ 3 10 / \ 1 6 """ assert t.root.left.left is not None assert t.root.left.left.parent == t.root.left assert t.root.left.left.label == 1 with self.assertRaises(Exception): t.put(1) def test_search(self) -> None: t = self._get_binary_search_tree() node = t.search(6) assert node.label == 6 node = t.search(13) assert node.label == 13 with self.assertRaises(Exception): t.search(2) def test_remove(self) -> None: t = self._get_binary_search_tree() t.remove(13) r""" 8 / \ 3 10 / \ \ 1 6 14 / \ 4 7 \ 5 """ assert t.root is not None assert t.root.right is not None assert t.root.right.right is not None assert t.root.right.right.right is None assert t.root.right.right.left is None t.remove(7) r""" 8 / \ 3 10 / \ \ 1 6 14 / 4 \ 5 """ assert t.root.left is not None assert t.root.left.right is not None assert t.root.left.right.left is not None assert t.root.left.right.right is None assert t.root.left.right.left.label == 4 t.remove(6) r""" 8 / \ 3 10 / \ \ 1 4 14 \ 5 """ assert t.root.left.left is not None assert t.root.left.right.right is not None assert t.root.left.left.label == 1 assert t.root.left.right.label == 4 assert t.root.left.right.right.label == 5 assert t.root.left.right.left is None assert t.root.left.left.parent == t.root.left assert t.root.left.right.parent == t.root.left t.remove(3) r""" 8 / \ 4 10 / \ \ 1 5 14 """ assert t.root is not None assert t.root.left.label == 4 assert t.root.left.right.label == 5 assert t.root.left.left.label == 1 assert t.root.left.parent == t.root assert t.root.left.left.parent == t.root.left assert t.root.left.right.parent == t.root.left t.remove(4) r""" 8 / \ 5 10 / \ 1 14 """ assert t.root.left is not None assert t.root.left.left is not None assert t.root.left.label == 5 assert t.root.left.right is None assert t.root.left.left.label == 1 assert t.root.left.parent == t.root assert t.root.left.left.parent == t.root.left def test_remove_2(self) -> None: t = self._get_binary_search_tree() t.remove(3) r""" 8 / \ 4 10 / \ \ 1 6 14 / \ / 5 7 13 """ assert t.root is not None assert t.root.left is not None assert t.root.left.left is not None assert t.root.left.right is not None assert t.root.left.right.left is not None assert t.root.left.right.right is not None assert t.root.left.label == 4 assert t.root.left.right.label == 6 assert t.root.left.left.label == 1 assert t.root.left.right.right.label == 7 assert t.root.left.right.left.label == 5 assert t.root.left.parent == t.root assert t.root.left.right.parent == t.root.left assert t.root.left.left.parent == t.root.left assert t.root.left.right.left.parent == t.root.left.right def test_empty(self) -> None: t = self._get_binary_search_tree() t.empty() assert t.root is None def test_is_empty(self) -> None: t = self._get_binary_search_tree() assert not t.is_empty() t.empty() assert t.is_empty() def test_exists(self) -> None: t = self._get_binary_search_tree() assert t.exists(6) assert not t.exists(-1) def test_get_max_label(self) -> None: t = self._get_binary_search_tree() assert t.get_max_label() == 14 t.empty() with self.assertRaises(Exception): t.get_max_label() def test_get_min_label(self) -> None: t = self._get_binary_search_tree() assert t.get_min_label() == 1 t.empty() with self.assertRaises(Exception): t.get_min_label() def test_inorder_traversal(self) -> None: t = self._get_binary_search_tree() inorder_traversal_nodes = [i.label for i in t.inorder_traversal()] assert inorder_traversal_nodes == [1, 3, 4, 5, 6, 7, 8, 10, 13, 14] def test_preorder_traversal(self) -> None: t = self._get_binary_search_tree() preorder_traversal_nodes = [i.label for i in t.preorder_traversal()] assert preorder_traversal_nodes == [8, 3, 1, 6, 4, 5, 7, 10, 14, 13] def binary_search_tree_example() -> None: r""" Example 8 / \ 3 10 / \ \ 1 6 14 / \ / 4 7 13 \ 5 Example After Deletion 4 / \ 1 7 \ 5 """ t = BinarySearchTree() t.put(8) t.put(3) t.put(6) t.put(1) t.put(10) t.put(14) t.put(13) t.put(4) t.put(7) t.put(5) print( """ 8 / \\ 3 10 / \\ \\ 1 6 14 / \\ / 4 7 13 \\ 5 """ ) print("Label 6 exists:", t.exists(6)) print("Label 13 exists:", t.exists(13)) print("Label -1 exists:", t.exists(-1)) print("Label 12 exists:", t.exists(12)) # Prints all the elements of the list in inorder traversal inorder_traversal_nodes = [i.label for i in t.inorder_traversal()] print("Inorder traversal:", inorder_traversal_nodes) # Prints all the elements of the list in preorder traversal preorder_traversal_nodes = [i.label for i in t.preorder_traversal()] print("Preorder traversal:", preorder_traversal_nodes) print("Max. label:", t.get_max_label()) print("Min. label:", t.get_min_label()) # Delete elements print("\nDeleting elements 13, 10, 8, 3, 6, 14") print( """ 4 / \\ 1 7 \\ 5 """ ) t.remove(13) t.remove(10) t.remove(8) t.remove(3) t.remove(6) t.remove(14) # Prints all the elements of the list in inorder traversal after delete inorder_traversal_nodes = [i.label for i in t.inorder_traversal()] print("Inorder traversal after delete:", inorder_traversal_nodes) # Prints all the elements of the list in preorder traversal after delete preorder_traversal_nodes = [i.label for i in t.preorder_traversal()] print("Preorder traversal after delete:", preorder_traversal_nodes) print("Max. label:", t.get_max_label()) print("Min. label:", t.get_min_label()) if __name__ == "__main__": binary_search_tree_example()
""" This is a python3 implementation of binary search tree using recursion To run tests: python -m unittest binary_search_tree_recursive.py To run an example: python binary_search_tree_recursive.py """ from __future__ import annotations import unittest from typing import Iterator class Node: def __init__(self, label: int, parent: Node | None) -> None: self.label = label self.parent = parent self.left: Node | None = None self.right: Node | None = None class BinarySearchTree: def __init__(self) -> None: self.root: Node | None = None def empty(self) -> None: """ Empties the tree >>> t = BinarySearchTree() >>> assert t.root is None >>> t.put(8) >>> assert t.root is not None """ self.root = None def is_empty(self) -> bool: """ Checks if the tree is empty >>> t = BinarySearchTree() >>> t.is_empty() True >>> t.put(8) >>> t.is_empty() False """ return self.root is None def put(self, label: int) -> None: """ Put a new node in the tree >>> t = BinarySearchTree() >>> t.put(8) >>> assert t.root.parent is None >>> assert t.root.label == 8 >>> t.put(10) >>> assert t.root.right.parent == t.root >>> assert t.root.right.label == 10 >>> t.put(3) >>> assert t.root.left.parent == t.root >>> assert t.root.left.label == 3 """ self.root = self._put(self.root, label) def _put(self, node: Node | None, label: int, parent: Node | None = None) -> Node: if node is None: node = Node(label, parent) else: if label < node.label: node.left = self._put(node.left, label, node) elif label > node.label: node.right = self._put(node.right, label, node) else: raise Exception(f"Node with label {label} already exists") return node def search(self, label: int) -> Node: """ Searches a node in the tree >>> t = BinarySearchTree() >>> t.put(8) >>> t.put(10) >>> node = t.search(8) >>> assert node.label == 8 >>> node = t.search(3) Traceback (most recent call last): ... Exception: Node with label 3 does not exist """ return self._search(self.root, label) def _search(self, node: Node | None, label: int) -> Node: if node is None: raise Exception(f"Node with label {label} does not exist") else: if label < node.label: node = self._search(node.left, label) elif label > node.label: node = self._search(node.right, label) return node def remove(self, label: int) -> None: """ Removes a node in the tree >>> t = BinarySearchTree() >>> t.put(8) >>> t.put(10) >>> t.remove(8) >>> assert t.root.label == 10 >>> t.remove(3) Traceback (most recent call last): ... Exception: Node with label 3 does not exist """ node = self.search(label) if node.right and node.left: lowest_node = self._get_lowest_node(node.right) lowest_node.left = node.left lowest_node.right = node.right node.left.parent = lowest_node if node.right: node.right.parent = lowest_node self._reassign_nodes(node, lowest_node) elif not node.right and node.left: self._reassign_nodes(node, node.left) elif node.right and not node.left: self._reassign_nodes(node, node.right) else: self._reassign_nodes(node, None) def _reassign_nodes(self, node: Node, new_children: Node | None) -> None: if new_children: new_children.parent = node.parent if node.parent: if node.parent.right == node: node.parent.right = new_children else: node.parent.left = new_children else: self.root = new_children def _get_lowest_node(self, node: Node) -> Node: if node.left: lowest_node = self._get_lowest_node(node.left) else: lowest_node = node self._reassign_nodes(node, node.right) return lowest_node def exists(self, label: int) -> bool: """ Checks if a node exists in the tree >>> t = BinarySearchTree() >>> t.put(8) >>> t.put(10) >>> t.exists(8) True >>> t.exists(3) False """ try: self.search(label) return True except Exception: return False def get_max_label(self) -> int: """ Gets the max label inserted in the tree >>> t = BinarySearchTree() >>> t.get_max_label() Traceback (most recent call last): ... Exception: Binary search tree is empty >>> t.put(8) >>> t.put(10) >>> t.get_max_label() 10 """ if self.root is None: raise Exception("Binary search tree is empty") node = self.root while node.right is not None: node = node.right return node.label def get_min_label(self) -> int: """ Gets the min label inserted in the tree >>> t = BinarySearchTree() >>> t.get_min_label() Traceback (most recent call last): ... Exception: Binary search tree is empty >>> t.put(8) >>> t.put(10) >>> t.get_min_label() 8 """ if self.root is None: raise Exception("Binary search tree is empty") node = self.root while node.left is not None: node = node.left return node.label def inorder_traversal(self) -> Iterator[Node]: """ Return the inorder traversal of the tree >>> t = BinarySearchTree() >>> [i.label for i in t.inorder_traversal()] [] >>> t.put(8) >>> t.put(10) >>> t.put(9) >>> [i.label for i in t.inorder_traversal()] [8, 9, 10] """ return self._inorder_traversal(self.root) def _inorder_traversal(self, node: Node | None) -> Iterator[Node]: if node is not None: yield from self._inorder_traversal(node.left) yield node yield from self._inorder_traversal(node.right) def preorder_traversal(self) -> Iterator[Node]: """ Return the preorder traversal of the tree >>> t = BinarySearchTree() >>> [i.label for i in t.preorder_traversal()] [] >>> t.put(8) >>> t.put(10) >>> t.put(9) >>> [i.label for i in t.preorder_traversal()] [8, 10, 9] """ return self._preorder_traversal(self.root) def _preorder_traversal(self, node: Node | None) -> Iterator[Node]: if node is not None: yield node yield from self._preorder_traversal(node.left) yield from self._preorder_traversal(node.right) class BinarySearchTreeTest(unittest.TestCase): @staticmethod def _get_binary_search_tree() -> BinarySearchTree: r""" 8 / \ 3 10 / \ \ 1 6 14 / \ / 4 7 13 \ 5 """ t = BinarySearchTree() t.put(8) t.put(3) t.put(6) t.put(1) t.put(10) t.put(14) t.put(13) t.put(4) t.put(7) t.put(5) return t def test_put(self) -> None: t = BinarySearchTree() assert t.is_empty() t.put(8) r""" 8 """ assert t.root is not None assert t.root.parent is None assert t.root.label == 8 t.put(10) r""" 8 \ 10 """ assert t.root.right is not None assert t.root.right.parent == t.root assert t.root.right.label == 10 t.put(3) r""" 8 / \ 3 10 """ assert t.root.left is not None assert t.root.left.parent == t.root assert t.root.left.label == 3 t.put(6) r""" 8 / \ 3 10 \ 6 """ assert t.root.left.right is not None assert t.root.left.right.parent == t.root.left assert t.root.left.right.label == 6 t.put(1) r""" 8 / \ 3 10 / \ 1 6 """ assert t.root.left.left is not None assert t.root.left.left.parent == t.root.left assert t.root.left.left.label == 1 with self.assertRaises(Exception): t.put(1) def test_search(self) -> None: t = self._get_binary_search_tree() node = t.search(6) assert node.label == 6 node = t.search(13) assert node.label == 13 with self.assertRaises(Exception): t.search(2) def test_remove(self) -> None: t = self._get_binary_search_tree() t.remove(13) r""" 8 / \ 3 10 / \ \ 1 6 14 / \ 4 7 \ 5 """ assert t.root is not None assert t.root.right is not None assert t.root.right.right is not None assert t.root.right.right.right is None assert t.root.right.right.left is None t.remove(7) r""" 8 / \ 3 10 / \ \ 1 6 14 / 4 \ 5 """ assert t.root.left is not None assert t.root.left.right is not None assert t.root.left.right.left is not None assert t.root.left.right.right is None assert t.root.left.right.left.label == 4 t.remove(6) r""" 8 / \ 3 10 / \ \ 1 4 14 \ 5 """ assert t.root.left.left is not None assert t.root.left.right.right is not None assert t.root.left.left.label == 1 assert t.root.left.right.label == 4 assert t.root.left.right.right.label == 5 assert t.root.left.right.left is None assert t.root.left.left.parent == t.root.left assert t.root.left.right.parent == t.root.left t.remove(3) r""" 8 / \ 4 10 / \ \ 1 5 14 """ assert t.root is not None assert t.root.left.label == 4 assert t.root.left.right.label == 5 assert t.root.left.left.label == 1 assert t.root.left.parent == t.root assert t.root.left.left.parent == t.root.left assert t.root.left.right.parent == t.root.left t.remove(4) r""" 8 / \ 5 10 / \ 1 14 """ assert t.root.left is not None assert t.root.left.left is not None assert t.root.left.label == 5 assert t.root.left.right is None assert t.root.left.left.label == 1 assert t.root.left.parent == t.root assert t.root.left.left.parent == t.root.left def test_remove_2(self) -> None: t = self._get_binary_search_tree() t.remove(3) r""" 8 / \ 4 10 / \ \ 1 6 14 / \ / 5 7 13 """ assert t.root is not None assert t.root.left is not None assert t.root.left.left is not None assert t.root.left.right is not None assert t.root.left.right.left is not None assert t.root.left.right.right is not None assert t.root.left.label == 4 assert t.root.left.right.label == 6 assert t.root.left.left.label == 1 assert t.root.left.right.right.label == 7 assert t.root.left.right.left.label == 5 assert t.root.left.parent == t.root assert t.root.left.right.parent == t.root.left assert t.root.left.left.parent == t.root.left assert t.root.left.right.left.parent == t.root.left.right def test_empty(self) -> None: t = self._get_binary_search_tree() t.empty() assert t.root is None def test_is_empty(self) -> None: t = self._get_binary_search_tree() assert not t.is_empty() t.empty() assert t.is_empty() def test_exists(self) -> None: t = self._get_binary_search_tree() assert t.exists(6) assert not t.exists(-1) def test_get_max_label(self) -> None: t = self._get_binary_search_tree() assert t.get_max_label() == 14 t.empty() with self.assertRaises(Exception): t.get_max_label() def test_get_min_label(self) -> None: t = self._get_binary_search_tree() assert t.get_min_label() == 1 t.empty() with self.assertRaises(Exception): t.get_min_label() def test_inorder_traversal(self) -> None: t = self._get_binary_search_tree() inorder_traversal_nodes = [i.label for i in t.inorder_traversal()] assert inorder_traversal_nodes == [1, 3, 4, 5, 6, 7, 8, 10, 13, 14] def test_preorder_traversal(self) -> None: t = self._get_binary_search_tree() preorder_traversal_nodes = [i.label for i in t.preorder_traversal()] assert preorder_traversal_nodes == [8, 3, 1, 6, 4, 5, 7, 10, 14, 13] def binary_search_tree_example() -> None: r""" Example 8 / \ 3 10 / \ \ 1 6 14 / \ / 4 7 13 \ 5 Example After Deletion 4 / \ 1 7 \ 5 """ t = BinarySearchTree() t.put(8) t.put(3) t.put(6) t.put(1) t.put(10) t.put(14) t.put(13) t.put(4) t.put(7) t.put(5) print( """ 8 / \\ 3 10 / \\ \\ 1 6 14 / \\ / 4 7 13 \\ 5 """ ) print("Label 6 exists:", t.exists(6)) print("Label 13 exists:", t.exists(13)) print("Label -1 exists:", t.exists(-1)) print("Label 12 exists:", t.exists(12)) # Prints all the elements of the list in inorder traversal inorder_traversal_nodes = [i.label for i in t.inorder_traversal()] print("Inorder traversal:", inorder_traversal_nodes) # Prints all the elements of the list in preorder traversal preorder_traversal_nodes = [i.label for i in t.preorder_traversal()] print("Preorder traversal:", preorder_traversal_nodes) print("Max. label:", t.get_max_label()) print("Min. label:", t.get_min_label()) # Delete elements print("\nDeleting elements 13, 10, 8, 3, 6, 14") print( """ 4 / \\ 1 7 \\ 5 """ ) t.remove(13) t.remove(10) t.remove(8) t.remove(3) t.remove(6) t.remove(14) # Prints all the elements of the list in inorder traversal after delete inorder_traversal_nodes = [i.label for i in t.inorder_traversal()] print("Inorder traversal after delete:", inorder_traversal_nodes) # Prints all the elements of the list in preorder traversal after delete preorder_traversal_nodes = [i.label for i in t.preorder_traversal()] print("Preorder traversal after delete:", preorder_traversal_nodes) print("Max. label:", t.get_max_label()) print("Min. label:", t.get_min_label()) if __name__ == "__main__": binary_search_tree_example()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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/black : True """ from __future__ import annotations def prime_factors(n: int) -> list[int]: """ Returns prime factors of n as a list. >>> prime_factors(0) [] >>> prime_factors(100) [2, 2, 5, 5] >>> prime_factors(2560) [2, 2, 2, 2, 2, 2, 2, 2, 2, 5] >>> prime_factors(10**-2) [] >>> prime_factors(0.02) [] >>> x = prime_factors(10**241) # doctest: +NORMALIZE_WHITESPACE >>> x == [2]*241 + [5]*241 True >>> prime_factors(10**-354) [] >>> prime_factors('hello') Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'str' >>> prime_factors([1,2,'hello']) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'list' """ i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors if __name__ == "__main__": import doctest doctest.testmod()
""" python/black : True """ from __future__ import annotations def prime_factors(n: int) -> list[int]: """ Returns prime factors of n as a list. >>> prime_factors(0) [] >>> prime_factors(100) [2, 2, 5, 5] >>> prime_factors(2560) [2, 2, 2, 2, 2, 2, 2, 2, 2, 5] >>> prime_factors(10**-2) [] >>> prime_factors(0.02) [] >>> x = prime_factors(10**241) # doctest: +NORMALIZE_WHITESPACE >>> x == [2]*241 + [5]*241 True >>> prime_factors(10**-354) [] >>> prime_factors('hello') Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'str' >>> prime_factors([1,2,'hello']) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'list' """ i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 203: https://projecteuler.net/problem=203 The binomial coefficients (n k) can be arranged in triangular form, Pascal's triangle, like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 ......... It can be seen that the first eight rows of Pascal's triangle contain twelve distinct numbers: 1, 2, 3, 4, 5, 6, 7, 10, 15, 20, 21 and 35. A positive integer n is called squarefree if no square of a prime divides n. Of the twelve distinct numbers in the first eight rows of Pascal's triangle, all except 4 and 20 are squarefree. The sum of the distinct squarefree numbers in the first eight rows is 105. Find the sum of the distinct squarefree numbers in the first 51 rows of Pascal's triangle. References: - https://en.wikipedia.org/wiki/Pascal%27s_triangle """ from __future__ import annotations import math def get_pascal_triangle_unique_coefficients(depth: int) -> set[int]: """ Returns the unique coefficients of a Pascal's triangle of depth "depth". The coefficients of this triangle are symmetric. A further improvement to this method could be to calculate the coefficients once per level. Nonetheless, the current implementation is fast enough for the original problem. >>> get_pascal_triangle_unique_coefficients(1) {1} >>> get_pascal_triangle_unique_coefficients(2) {1} >>> get_pascal_triangle_unique_coefficients(3) {1, 2} >>> get_pascal_triangle_unique_coefficients(8) {1, 2, 3, 4, 5, 6, 7, 35, 10, 15, 20, 21} """ coefficients = {1} previous_coefficients = [1] for step in range(2, depth + 1): coefficients_begins_one = previous_coefficients + [0] coefficients_ends_one = [0] + previous_coefficients previous_coefficients = [] for x, y in zip(coefficients_begins_one, coefficients_ends_one): coefficients.add(x + y) previous_coefficients.append(x + y) return coefficients def get_primes_squared(max_number: int) -> list[int]: """ Calculates all primes between 2 and round(sqrt(max_number)) and returns them squared up. >>> get_primes_squared(2) [] >>> get_primes_squared(4) [4] >>> get_primes_squared(10) [4, 9] >>> get_primes_squared(100) [4, 9, 25, 49] """ max_prime = math.isqrt(max_number) non_primes = [False] * (max_prime + 1) primes = [] for num in range(2, max_prime + 1): if non_primes[num]: continue for num_counter in range(num**2, max_prime + 1, num): non_primes[num_counter] = True primes.append(num**2) return primes def get_squared_primes_to_use( num_to_look: int, squared_primes: list[int], previous_index: int ) -> int: """ Returns an int indicating the last index on which squares of primes in primes are lower than num_to_look. This method supposes that squared_primes is sorted in ascending order and that each num_to_look is provided in ascending order as well. Under these assumptions, it needs a previous_index parameter that tells what was the index returned by the method for the previous num_to_look. If all the elements in squared_primes are greater than num_to_look, then the method returns -1. >>> get_squared_primes_to_use(1, [4, 9, 16, 25], 0) -1 >>> get_squared_primes_to_use(4, [4, 9, 16, 25], 0) 1 >>> get_squared_primes_to_use(16, [4, 9, 16, 25], 1) 3 """ idx = max(previous_index, 0) while idx < len(squared_primes) and squared_primes[idx] <= num_to_look: idx += 1 if idx == 0 and squared_primes[idx] > num_to_look: return -1 if idx == len(squared_primes) and squared_primes[-1] > num_to_look: return -1 return idx def get_squarefree( unique_coefficients: set[int], squared_primes: list[int] ) -> set[int]: """ Calculates the squarefree numbers inside unique_coefficients given a list of square of primes. Based on the definition of a non-squarefree number, then any non-squarefree n can be decomposed as n = p*p*r, where p is positive prime number and r is a positive integer. Under the previous formula, any coefficient that is lower than p*p is squarefree as r cannot be negative. On the contrary, if any r exists such that n = p*p*r, then the number is non-squarefree. >>> get_squarefree({1}, []) set() >>> get_squarefree({1, 2}, []) set() >>> get_squarefree({1, 2, 3, 4, 5, 6, 7, 35, 10, 15, 20, 21}, [4, 9, 25]) {1, 2, 3, 5, 6, 7, 35, 10, 15, 21} """ if len(squared_primes) == 0: return set() non_squarefrees = set() prime_squared_idx = 0 for num in sorted(unique_coefficients): prime_squared_idx = get_squared_primes_to_use( num, squared_primes, prime_squared_idx ) if prime_squared_idx == -1: continue if any(num % prime == 0 for prime in squared_primes[:prime_squared_idx]): non_squarefrees.add(num) return unique_coefficients.difference(non_squarefrees) def solution(n: int = 51) -> int: """ Returns the sum of squarefrees for a given Pascal's Triangle of depth n. >>> solution(1) 0 >>> solution(8) 105 >>> solution(9) 175 """ unique_coefficients = get_pascal_triangle_unique_coefficients(n) primes = get_primes_squared(max(unique_coefficients)) squarefrees = get_squarefree(unique_coefficients, primes) return sum(squarefrees) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 203: https://projecteuler.net/problem=203 The binomial coefficients (n k) can be arranged in triangular form, Pascal's triangle, like this: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 ......... It can be seen that the first eight rows of Pascal's triangle contain twelve distinct numbers: 1, 2, 3, 4, 5, 6, 7, 10, 15, 20, 21 and 35. A positive integer n is called squarefree if no square of a prime divides n. Of the twelve distinct numbers in the first eight rows of Pascal's triangle, all except 4 and 20 are squarefree. The sum of the distinct squarefree numbers in the first eight rows is 105. Find the sum of the distinct squarefree numbers in the first 51 rows of Pascal's triangle. References: - https://en.wikipedia.org/wiki/Pascal%27s_triangle """ from __future__ import annotations import math def get_pascal_triangle_unique_coefficients(depth: int) -> set[int]: """ Returns the unique coefficients of a Pascal's triangle of depth "depth". The coefficients of this triangle are symmetric. A further improvement to this method could be to calculate the coefficients once per level. Nonetheless, the current implementation is fast enough for the original problem. >>> get_pascal_triangle_unique_coefficients(1) {1} >>> get_pascal_triangle_unique_coefficients(2) {1} >>> get_pascal_triangle_unique_coefficients(3) {1, 2} >>> get_pascal_triangle_unique_coefficients(8) {1, 2, 3, 4, 5, 6, 7, 35, 10, 15, 20, 21} """ coefficients = {1} previous_coefficients = [1] for step in range(2, depth + 1): coefficients_begins_one = previous_coefficients + [0] coefficients_ends_one = [0] + previous_coefficients previous_coefficients = [] for x, y in zip(coefficients_begins_one, coefficients_ends_one): coefficients.add(x + y) previous_coefficients.append(x + y) return coefficients def get_primes_squared(max_number: int) -> list[int]: """ Calculates all primes between 2 and round(sqrt(max_number)) and returns them squared up. >>> get_primes_squared(2) [] >>> get_primes_squared(4) [4] >>> get_primes_squared(10) [4, 9] >>> get_primes_squared(100) [4, 9, 25, 49] """ max_prime = math.isqrt(max_number) non_primes = [False] * (max_prime + 1) primes = [] for num in range(2, max_prime + 1): if non_primes[num]: continue for num_counter in range(num**2, max_prime + 1, num): non_primes[num_counter] = True primes.append(num**2) return primes def get_squared_primes_to_use( num_to_look: int, squared_primes: list[int], previous_index: int ) -> int: """ Returns an int indicating the last index on which squares of primes in primes are lower than num_to_look. This method supposes that squared_primes is sorted in ascending order and that each num_to_look is provided in ascending order as well. Under these assumptions, it needs a previous_index parameter that tells what was the index returned by the method for the previous num_to_look. If all the elements in squared_primes are greater than num_to_look, then the method returns -1. >>> get_squared_primes_to_use(1, [4, 9, 16, 25], 0) -1 >>> get_squared_primes_to_use(4, [4, 9, 16, 25], 0) 1 >>> get_squared_primes_to_use(16, [4, 9, 16, 25], 1) 3 """ idx = max(previous_index, 0) while idx < len(squared_primes) and squared_primes[idx] <= num_to_look: idx += 1 if idx == 0 and squared_primes[idx] > num_to_look: return -1 if idx == len(squared_primes) and squared_primes[-1] > num_to_look: return -1 return idx def get_squarefree( unique_coefficients: set[int], squared_primes: list[int] ) -> set[int]: """ Calculates the squarefree numbers inside unique_coefficients given a list of square of primes. Based on the definition of a non-squarefree number, then any non-squarefree n can be decomposed as n = p*p*r, where p is positive prime number and r is a positive integer. Under the previous formula, any coefficient that is lower than p*p is squarefree as r cannot be negative. On the contrary, if any r exists such that n = p*p*r, then the number is non-squarefree. >>> get_squarefree({1}, []) set() >>> get_squarefree({1, 2}, []) set() >>> get_squarefree({1, 2, 3, 4, 5, 6, 7, 35, 10, 15, 20, 21}, [4, 9, 25]) {1, 2, 3, 5, 6, 7, 35, 10, 15, 21} """ if len(squared_primes) == 0: return set() non_squarefrees = set() prime_squared_idx = 0 for num in sorted(unique_coefficients): prime_squared_idx = get_squared_primes_to_use( num, squared_primes, prime_squared_idx ) if prime_squared_idx == -1: continue if any(num % prime == 0 for prime in squared_primes[:prime_squared_idx]): non_squarefrees.add(num) return unique_coefficients.difference(non_squarefrees) def solution(n: int = 51) -> int: """ Returns the sum of squarefrees for a given Pascal's Triangle of depth n. >>> solution(1) 0 >>> solution(8) 105 >>> solution(9) 175 """ unique_coefficients = get_pascal_triangle_unique_coefficients(n) primes = get_primes_squared(max(unique_coefficients)) squarefrees = get_squarefree(unique_coefficients, primes) return sum(squarefrees) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter """ Create 2nd-order IIR filters with Butterworth design. Code based on https://webaudio.github.io/Audio-EQ-Cookbook/audio-eq-cookbook.html Alternatively you can use scipy.signal.butter, which should yield the same results. """ def make_lowpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: """ Creates a low-pass filter >>> filter = make_lowpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.004277569313094809, 0.008555138626189618, 0.004277569313094809] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = (1 - _cos) / 2 b1 = 1 - _cos a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b0]) return filt def make_highpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: """ Creates a high-pass filter >>> filter = make_highpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.9957224306869052, -1.9914448613738105, 0.9957224306869052] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = (1 + _cos) / 2 b1 = -1 - _cos a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b0]) return filt def make_bandpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: """ Creates a band-pass filter >>> filter = make_bandpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.06526309611002579, 0, -0.06526309611002579] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = _sin / 2 b1 = 0 b2 = -b0 a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_allpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: """ Creates an all-pass filter >>> filter = make_allpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.9077040443587427, -1.9828897227476208, 1.0922959556412573] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = 1 - alpha b1 = -2 * _cos b2 = 1 + alpha filt = IIRFilter(2) filt.set_coefficients([b2, b1, b0], [b0, b1, b2]) return filt def make_peak( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: """ Creates a peak filter >>> filter = make_peak(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0653405327119334, -1.9828897227476208, 0.9346594672880666, 1.1303715025601122, -1.9828897227476208, 0.8696284974398878] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) b0 = 1 + alpha * big_a b1 = -2 * _cos b2 = 1 - alpha * big_a a0 = 1 + alpha / big_a a1 = -2 * _cos a2 = 1 - alpha / big_a filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_lowshelf( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: """ Creates a low-shelf filter >>> filter = make_lowshelf(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [3.0409336710888786, -5.608870992220748, 2.602157875636628, 3.139954022810743, -5.591841778072785, 2.5201667380627257] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) pmc = (big_a + 1) - (big_a - 1) * _cos ppmc = (big_a + 1) + (big_a - 1) * _cos mpc = (big_a - 1) - (big_a + 1) * _cos pmpc = (big_a - 1) + (big_a + 1) * _cos aa2 = 2 * sqrt(big_a) * alpha b0 = big_a * (pmc + aa2) b1 = 2 * big_a * mpc b2 = big_a * (pmc - aa2) a0 = ppmc + aa2 a1 = -2 * pmpc a2 = ppmc - aa2 filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_highshelf( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: """ Creates a high-shelf filter >>> filter = make_highshelf(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [2.2229172136088806, -3.9587208137297303, 1.7841414181566304, 4.295432981120543, -7.922740859457287, 3.6756456963725253] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) pmc = (big_a + 1) - (big_a - 1) * _cos ppmc = (big_a + 1) + (big_a - 1) * _cos mpc = (big_a - 1) - (big_a + 1) * _cos pmpc = (big_a - 1) + (big_a + 1) * _cos aa2 = 2 * sqrt(big_a) * alpha b0 = big_a * (ppmc + aa2) b1 = -2 * big_a * pmpc b2 = big_a * (ppmc - aa2) a0 = pmc + aa2 a1 = 2 * mpc a2 = pmc - aa2 filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt
from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter """ Create 2nd-order IIR filters with Butterworth design. Code based on https://webaudio.github.io/Audio-EQ-Cookbook/audio-eq-cookbook.html Alternatively you can use scipy.signal.butter, which should yield the same results. """ def make_lowpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: """ Creates a low-pass filter >>> filter = make_lowpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.004277569313094809, 0.008555138626189618, 0.004277569313094809] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = (1 - _cos) / 2 b1 = 1 - _cos a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b0]) return filt def make_highpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: """ Creates a high-pass filter >>> filter = make_highpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.9957224306869052, -1.9914448613738105, 0.9957224306869052] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = (1 + _cos) / 2 b1 = -1 - _cos a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b0]) return filt def make_bandpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: """ Creates a band-pass filter >>> filter = make_bandpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.06526309611002579, 0, -0.06526309611002579] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = _sin / 2 b1 = 0 b2 = -b0 a0 = 1 + alpha a1 = -2 * _cos a2 = 1 - alpha filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_allpass( frequency: int, samplerate: int, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: """ Creates an all-pass filter >>> filter = make_allpass(1000, 48000) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0922959556412573, -1.9828897227476208, 0.9077040443587427, 0.9077040443587427, -1.9828897227476208, 1.0922959556412573] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) b0 = 1 - alpha b1 = -2 * _cos b2 = 1 + alpha filt = IIRFilter(2) filt.set_coefficients([b2, b1, b0], [b0, b1, b2]) return filt def make_peak( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: """ Creates a peak filter >>> filter = make_peak(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [1.0653405327119334, -1.9828897227476208, 0.9346594672880666, 1.1303715025601122, -1.9828897227476208, 0.8696284974398878] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) b0 = 1 + alpha * big_a b1 = -2 * _cos b2 = 1 - alpha * big_a a0 = 1 + alpha / big_a a1 = -2 * _cos a2 = 1 - alpha / big_a filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_lowshelf( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: """ Creates a low-shelf filter >>> filter = make_lowshelf(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [3.0409336710888786, -5.608870992220748, 2.602157875636628, 3.139954022810743, -5.591841778072785, 2.5201667380627257] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) pmc = (big_a + 1) - (big_a - 1) * _cos ppmc = (big_a + 1) + (big_a - 1) * _cos mpc = (big_a - 1) - (big_a + 1) * _cos pmpc = (big_a - 1) + (big_a + 1) * _cos aa2 = 2 * sqrt(big_a) * alpha b0 = big_a * (pmc + aa2) b1 = 2 * big_a * mpc b2 = big_a * (pmc - aa2) a0 = ppmc + aa2 a1 = -2 * pmpc a2 = ppmc - aa2 filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt def make_highshelf( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: """ Creates a high-shelf filter >>> filter = make_highshelf(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [2.2229172136088806, -3.9587208137297303, 1.7841414181566304, 4.295432981120543, -7.922740859457287, 3.6756456963725253] """ w0 = tau * frequency / samplerate _sin = sin(w0) _cos = cos(w0) alpha = _sin / (2 * q_factor) big_a = 10 ** (gain_db / 40) pmc = (big_a + 1) - (big_a - 1) * _cos ppmc = (big_a + 1) + (big_a - 1) * _cos mpc = (big_a - 1) - (big_a + 1) * _cos pmpc = (big_a - 1) + (big_a + 1) * _cos aa2 = 2 * sqrt(big_a) * alpha b0 = big_a * (ppmc + aa2) b1 = -2 * big_a * pmpc b2 = big_a * (ppmc - aa2) a0 = pmc + aa2 a1 = 2 * mpc a2 = pmc - aa2 filt = IIRFilter(2) filt.set_coefficients([a0, a1, a2], [b0, b1, b2]) return filt
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
# 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
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
""" 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) gaussKer = get_gauss_kernel(kernel_size, spatial_variance) sizeX, sizeY = img.shape for i in range(kernel_size // 2, sizeX - kernel_size // 2): for j in range(kernel_size // 2, sizeY - kernel_size // 2): imgS = get_slice(img, i, j, kernel_size) imgI = imgS - imgS[kernel_size // 2, kernel_size // 2] imgIG = vec_gaussian(imgI, intensity_variance) weights = np.multiply(gaussKer, imgIG) vals = np.multiply(imgS, 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) gaussKer = get_gauss_kernel(kernel_size, spatial_variance) sizeX, sizeY = img.shape for i in range(kernel_size // 2, sizeX - kernel_size // 2): for j in range(kernel_size // 2, sizeY - kernel_size // 2): imgS = get_slice(img, i, j, kernel_size) imgI = imgS - imgS[kernel_size // 2, kernel_size // 2] imgIG = vec_gaussian(imgI, intensity_variance) weights = np.multiply(gaussKer, imgIG) vals = np.multiply(imgS, 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
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 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? """ import sys 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 """ largest_product = -sys.maxsize - 1 for i in range(len(n) - 12): product = 1 for j in range(13): product *= int(n[i + j]) if product > largest_product: largest_product = product return largest_product 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? """ import sys 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 """ largest_product = -sys.maxsize - 1 for i in range(len(n) - 12): product = 1 for j in range(13): product *= int(n[i + j]) if product > largest_product: largest_product = product return largest_product if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 __future__ import annotations # Divide and Conquer algorithm def find_max(nums: list[int | float], left: int, right: int) -> int | float: """ find max value in list :param nums: contains elements :param left: index of first element :param right: index of last element :return: max in nums >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_max(nums, 0, len(nums) - 1) == max(nums) True True True True >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] >>> find_max(nums, 0, len(nums) - 1) == max(nums) True >>> find_max([], 0, 0) Traceback (most recent call last): ... ValueError: find_max() arg is an empty sequence >>> find_max(nums, 0, len(nums)) == max(nums) Traceback (most recent call last): ... IndexError: list index out of range >>> find_max(nums, -len(nums), -1) == max(nums) True >>> find_max(nums, -len(nums) - 1, -1) == max(nums) Traceback (most recent call last): ... IndexError: list index out of range """ if len(nums) == 0: raise ValueError("find_max() arg is an empty sequence") if ( left >= len(nums) or left < -len(nums) or right >= len(nums) or right < -len(nums) ): raise IndexError("list index out of range") if left == right: return nums[left] mid = (left + right) >> 1 # the middle left_max = find_max(nums, left, mid) # find max in range[left, mid] right_max = find_max(nums, mid + 1, right) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
from __future__ import annotations # Divide and Conquer algorithm def find_max(nums: list[int | float], left: int, right: int) -> int | float: """ find max value in list :param nums: contains elements :param left: index of first element :param right: index of last element :return: max in nums >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1, 2.9]): ... find_max(nums, 0, len(nums) - 1) == max(nums) True True True True >>> nums = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10] >>> find_max(nums, 0, len(nums) - 1) == max(nums) True >>> find_max([], 0, 0) Traceback (most recent call last): ... ValueError: find_max() arg is an empty sequence >>> find_max(nums, 0, len(nums)) == max(nums) Traceback (most recent call last): ... IndexError: list index out of range >>> find_max(nums, -len(nums), -1) == max(nums) True >>> find_max(nums, -len(nums) - 1, -1) == max(nums) Traceback (most recent call last): ... IndexError: list index out of range """ if len(nums) == 0: raise ValueError("find_max() arg is an empty sequence") if ( left >= len(nums) or left < -len(nums) or right >= len(nums) or right < -len(nums) ): raise IndexError("list index out of range") if left == right: return nums[left] mid = (left + right) >> 1 # the middle left_max = find_max(nums, left, mid) # find max in range[left, mid] right_max = find_max(nums, mid + 1, right) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 random class Onepad: @staticmethod def encrypt(text: str) -> tuple[list[int], list[int]]: """Function to encrypt text using pseudo-random numbers""" plain = [ord(i) for i in text] key = [] cipher = [] for i in plain: k = random.randint(1, 300) c = (i + k) * k cipher.append(c) key.append(k) return cipher, key @staticmethod def decrypt(cipher: list[int], key: list[int]) -> str: """Function to decrypt text using pseudo-random numbers.""" plain = [] for i in range(len(key)): p = int((cipher[i] - (key[i]) ** 2) / key[i]) plain.append(chr(p)) return "".join([i for i in plain]) if __name__ == "__main__": c, k = Onepad().encrypt("Hello") print(c, k) print(Onepad().decrypt(c, k))
import random class Onepad: @staticmethod def encrypt(text: str) -> tuple[list[int], list[int]]: """Function to encrypt text using pseudo-random numbers""" plain = [ord(i) for i in text] key = [] cipher = [] for i in plain: k = random.randint(1, 300) c = (i + k) * k cipher.append(c) key.append(k) return cipher, key @staticmethod def decrypt(cipher: list[int], key: list[int]) -> str: """Function to decrypt text using pseudo-random numbers.""" plain = [] for i in range(len(key)): p = int((cipher[i] - (key[i]) ** 2) / key[i]) plain.append(chr(p)) return "".join([i for i in plain]) if __name__ == "__main__": c, k = Onepad().encrypt("Hello") print(c, k) print(Onepad().decrypt(c, k))
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
""" Author : Mehdi ALAOUI This is a pure Python implementation of Dynamic Programming solution to the longest increasing subsequence of a given sequence. The problem is : Given an array, to find the longest and increasing sub-array in that given array and return it. Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return [10, 22, 33, 41, 60, 80] as output """ from __future__ import annotations def longest_subsequence(array: list[int]) -> list[int]: # This function is recursive """ Some examples >>> longest_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80]) [10, 22, 33, 41, 60, 80] >>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9]) [1, 2, 3, 9] >>> longest_subsequence([9, 8, 7, 6, 5, 7]) [8] >>> longest_subsequence([1, 1, 1]) [1, 1, 1] >>> longest_subsequence([]) [] """ array_length = len(array) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else pivot = array[0] isFound = False i = 1 longest_subseq: list[int] = [] while not isFound and i < array_length: if array[i] < pivot: isFound = True temp_array = [element for element in array[i:] if element >= array[i]] temp_array = longest_subsequence(temp_array) if len(temp_array) > len(longest_subseq): longest_subseq = temp_array else: i += 1 temp_array = [element for element in array[1:] if element >= pivot] temp_array = [pivot] + longest_subsequence(temp_array) if len(temp_array) > len(longest_subseq): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
""" Author : Mehdi ALAOUI This is a pure Python implementation of Dynamic Programming solution to the longest increasing subsequence of a given sequence. The problem is : Given an array, to find the longest and increasing sub-array in that given array and return it. Example: [10, 22, 9, 33, 21, 50, 41, 60, 80] as input will return [10, 22, 33, 41, 60, 80] as output """ from __future__ import annotations def longest_subsequence(array: list[int]) -> list[int]: # This function is recursive """ Some examples >>> longest_subsequence([10, 22, 9, 33, 21, 50, 41, 60, 80]) [10, 22, 33, 41, 60, 80] >>> longest_subsequence([4, 8, 7, 5, 1, 12, 2, 3, 9]) [1, 2, 3, 9] >>> longest_subsequence([9, 8, 7, 6, 5, 7]) [8] >>> longest_subsequence([1, 1, 1]) [1, 1, 1] >>> longest_subsequence([]) [] """ array_length = len(array) # If the array contains only one element, we return it (it's the stop condition of # recursion) if array_length <= 1: return array # Else pivot = array[0] isFound = False i = 1 longest_subseq: list[int] = [] while not isFound and i < array_length: if array[i] < pivot: isFound = True temp_array = [element for element in array[i:] if element >= array[i]] temp_array = longest_subsequence(temp_array) if len(temp_array) > len(longest_subseq): longest_subseq = temp_array else: i += 1 temp_array = [element for element in array[1:] if element >= pivot] temp_array = [pivot] + longest_subsequence(temp_array) if len(temp_array) > len(longest_subseq): return temp_array else: return longest_subseq if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ total = 0 terms = (n - 1) // 3 total += ((terms) * (6 + (terms - 1) * 3)) // 2 # total of an A.P. terms = (n - 1) // 5 total += ((terms) * (10 + (terms - 1) * 5)) // 2 terms = (n - 1) // 15 total -= ((terms) * (30 + (terms - 1) * 15)) // 2 return total if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ total = 0 terms = (n - 1) // 3 total += ((terms) * (6 + (terms - 1) * 3)) // 2 # total of an A.P. terms = (n - 1) // 5 total += ((terms) * (10 + (terms - 1) * 5)) // 2 terms = (n - 1) // 15 total -= ((terms) * (30 + (terms - 1) * 15)) // 2 return total if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 """ This is pure Python implementation of binary search algorithms For doctests run following command: python3 -m doctest -v binary_search.py For manual testing run: python3 binary_search.py """ from __future__ import annotations import bisect def bisect_left( sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1 ) -> int: """ Locates the first element in a sorted array that is larger or equal to a given value. It has the same interface as https://docs.python.org/3/library/bisect.html#bisect.bisect_left . :param sorted_collection: some ascending sorted collection with comparable items :param item: item to bisect :param lo: lowest index to consider (as in sorted_collection[lo:hi]) :param hi: past the highest index to consider (as in sorted_collection[lo:hi]) :return: index i such that all values in sorted_collection[lo:i] are < item and all values in sorted_collection[i:hi] are >= item. Examples: >>> bisect_left([0, 5, 7, 10, 15], 0) 0 >>> bisect_left([0, 5, 7, 10, 15], 6) 2 >>> bisect_left([0, 5, 7, 10, 15], 20) 5 >>> bisect_left([0, 5, 7, 10, 15], 15, 1, 3) 3 >>> bisect_left([0, 5, 7, 10, 15], 6, 2) 2 """ if hi < 0: hi = len(sorted_collection) while lo < hi: mid = lo + (hi - lo) // 2 if sorted_collection[mid] < item: lo = mid + 1 else: hi = mid return lo def bisect_right( sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1 ) -> int: """ Locates the first element in a sorted array that is larger than a given value. It has the same interface as https://docs.python.org/3/library/bisect.html#bisect.bisect_right . :param sorted_collection: some ascending sorted collection with comparable items :param item: item to bisect :param lo: lowest index to consider (as in sorted_collection[lo:hi]) :param hi: past the highest index to consider (as in sorted_collection[lo:hi]) :return: index i such that all values in sorted_collection[lo:i] are <= item and all values in sorted_collection[i:hi] are > item. Examples: >>> bisect_right([0, 5, 7, 10, 15], 0) 1 >>> bisect_right([0, 5, 7, 10, 15], 15) 5 >>> bisect_right([0, 5, 7, 10, 15], 6) 2 >>> bisect_right([0, 5, 7, 10, 15], 15, 1, 3) 3 >>> bisect_right([0, 5, 7, 10, 15], 6, 2) 2 """ if hi < 0: hi = len(sorted_collection) while lo < hi: mid = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: lo = mid + 1 else: hi = mid return lo def insort_left( sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1 ) -> None: """ Inserts a given value into a sorted array before other values with the same value. It has the same interface as https://docs.python.org/3/library/bisect.html#bisect.insort_left . :param sorted_collection: some ascending sorted collection with comparable items :param item: item to insert :param lo: lowest index to consider (as in sorted_collection[lo:hi]) :param hi: past the highest index to consider (as in sorted_collection[lo:hi]) Examples: >>> sorted_collection = [0, 5, 7, 10, 15] >>> insort_left(sorted_collection, 6) >>> sorted_collection [0, 5, 6, 7, 10, 15] >>> sorted_collection = [(0, 0), (5, 5), (7, 7), (10, 10), (15, 15)] >>> item = (5, 5) >>> insort_left(sorted_collection, item) >>> sorted_collection [(0, 0), (5, 5), (5, 5), (7, 7), (10, 10), (15, 15)] >>> item is sorted_collection[1] True >>> item is sorted_collection[2] False >>> sorted_collection = [0, 5, 7, 10, 15] >>> insort_left(sorted_collection, 20) >>> sorted_collection [0, 5, 7, 10, 15, 20] >>> sorted_collection = [0, 5, 7, 10, 15] >>> insort_left(sorted_collection, 15, 1, 3) >>> sorted_collection [0, 5, 7, 15, 10, 15] """ sorted_collection.insert(bisect_left(sorted_collection, item, lo, hi), item) def insort_right( sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1 ) -> None: """ Inserts a given value into a sorted array after other values with the same value. It has the same interface as https://docs.python.org/3/library/bisect.html#bisect.insort_right . :param sorted_collection: some ascending sorted collection with comparable items :param item: item to insert :param lo: lowest index to consider (as in sorted_collection[lo:hi]) :param hi: past the highest index to consider (as in sorted_collection[lo:hi]) Examples: >>> sorted_collection = [0, 5, 7, 10, 15] >>> insort_right(sorted_collection, 6) >>> sorted_collection [0, 5, 6, 7, 10, 15] >>> sorted_collection = [(0, 0), (5, 5), (7, 7), (10, 10), (15, 15)] >>> item = (5, 5) >>> insort_right(sorted_collection, item) >>> sorted_collection [(0, 0), (5, 5), (5, 5), (7, 7), (10, 10), (15, 15)] >>> item is sorted_collection[1] False >>> item is sorted_collection[2] True >>> sorted_collection = [0, 5, 7, 10, 15] >>> insort_right(sorted_collection, 20) >>> sorted_collection [0, 5, 7, 10, 15, 20] >>> sorted_collection = [0, 5, 7, 10, 15] >>> insort_right(sorted_collection, 15, 1, 3) >>> sorted_collection [0, 5, 7, 15, 10, 15] """ sorted_collection.insert(bisect_right(sorted_collection, item, lo, hi), item) def binary_search(sorted_collection: list[int], item: int) -> int | None: """Pure implementation of binary search algorithm in Python Be careful collection must be ascending sorted, otherwise result will be unpredictable :param sorted_collection: some ascending sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found Examples: >>> binary_search([0, 5, 7, 10, 15], 0) 0 >>> binary_search([0, 5, 7, 10, 15], 15) 4 >>> binary_search([0, 5, 7, 10, 15], 5) 1 >>> binary_search([0, 5, 7, 10, 15], 6) """ left = 0 right = len(sorted_collection) - 1 while left <= right: midpoint = left + (right - left) // 2 current_item = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: right = midpoint - 1 else: left = midpoint + 1 return None def binary_search_std_lib(sorted_collection: list[int], item: int) -> int | None: """Pure implementation of binary search algorithm in Python using stdlib Be careful collection must be ascending sorted, otherwise result will be unpredictable :param sorted_collection: some ascending sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found Examples: >>> binary_search_std_lib([0, 5, 7, 10, 15], 0) 0 >>> binary_search_std_lib([0, 5, 7, 10, 15], 15) 4 >>> binary_search_std_lib([0, 5, 7, 10, 15], 5) 1 >>> binary_search_std_lib([0, 5, 7, 10, 15], 6) """ index = bisect.bisect_left(sorted_collection, item) if index != len(sorted_collection) and sorted_collection[index] == item: return index return None def binary_search_by_recursion( sorted_collection: list[int], item: int, left: int, right: int ) -> int | None: """Pure implementation of binary search algorithm in Python by recursion Be careful collection must be ascending sorted, otherwise result will be unpredictable First recursion should be started with left=0 and right=(len(sorted_collection)-1) :param sorted_collection: some ascending sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found Examples: >>> binary_search_by_recursion([0, 5, 7, 10, 15], 0, 0, 4) 0 >>> binary_search_by_recursion([0, 5, 7, 10, 15], 15, 0, 4) 4 >>> binary_search_by_recursion([0, 5, 7, 10, 15], 5, 0, 4) 1 >>> binary_search_by_recursion([0, 5, 7, 10, 15], 6, 0, 4) """ if right < left: return None midpoint = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(sorted_collection, item, left, midpoint - 1) else: return binary_search_by_recursion(sorted_collection, item, midpoint + 1, right) if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() collection = sorted(int(item) for item in user_input.split(",")) target = int(input("Enter a single number to be found in the list:\n")) result = binary_search(collection, target) if result is None: print(f"{target} was not found in {collection}.") else: print(f"{target} was found at position {result} in {collection}.")
#!/usr/bin/env python3 """ This is pure Python implementation of binary search algorithms For doctests run following command: python3 -m doctest -v binary_search.py For manual testing run: python3 binary_search.py """ from __future__ import annotations import bisect def bisect_left( sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1 ) -> int: """ Locates the first element in a sorted array that is larger or equal to a given value. It has the same interface as https://docs.python.org/3/library/bisect.html#bisect.bisect_left . :param sorted_collection: some ascending sorted collection with comparable items :param item: item to bisect :param lo: lowest index to consider (as in sorted_collection[lo:hi]) :param hi: past the highest index to consider (as in sorted_collection[lo:hi]) :return: index i such that all values in sorted_collection[lo:i] are < item and all values in sorted_collection[i:hi] are >= item. Examples: >>> bisect_left([0, 5, 7, 10, 15], 0) 0 >>> bisect_left([0, 5, 7, 10, 15], 6) 2 >>> bisect_left([0, 5, 7, 10, 15], 20) 5 >>> bisect_left([0, 5, 7, 10, 15], 15, 1, 3) 3 >>> bisect_left([0, 5, 7, 10, 15], 6, 2) 2 """ if hi < 0: hi = len(sorted_collection) while lo < hi: mid = lo + (hi - lo) // 2 if sorted_collection[mid] < item: lo = mid + 1 else: hi = mid return lo def bisect_right( sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1 ) -> int: """ Locates the first element in a sorted array that is larger than a given value. It has the same interface as https://docs.python.org/3/library/bisect.html#bisect.bisect_right . :param sorted_collection: some ascending sorted collection with comparable items :param item: item to bisect :param lo: lowest index to consider (as in sorted_collection[lo:hi]) :param hi: past the highest index to consider (as in sorted_collection[lo:hi]) :return: index i such that all values in sorted_collection[lo:i] are <= item and all values in sorted_collection[i:hi] are > item. Examples: >>> bisect_right([0, 5, 7, 10, 15], 0) 1 >>> bisect_right([0, 5, 7, 10, 15], 15) 5 >>> bisect_right([0, 5, 7, 10, 15], 6) 2 >>> bisect_right([0, 5, 7, 10, 15], 15, 1, 3) 3 >>> bisect_right([0, 5, 7, 10, 15], 6, 2) 2 """ if hi < 0: hi = len(sorted_collection) while lo < hi: mid = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: lo = mid + 1 else: hi = mid return lo def insort_left( sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1 ) -> None: """ Inserts a given value into a sorted array before other values with the same value. It has the same interface as https://docs.python.org/3/library/bisect.html#bisect.insort_left . :param sorted_collection: some ascending sorted collection with comparable items :param item: item to insert :param lo: lowest index to consider (as in sorted_collection[lo:hi]) :param hi: past the highest index to consider (as in sorted_collection[lo:hi]) Examples: >>> sorted_collection = [0, 5, 7, 10, 15] >>> insort_left(sorted_collection, 6) >>> sorted_collection [0, 5, 6, 7, 10, 15] >>> sorted_collection = [(0, 0), (5, 5), (7, 7), (10, 10), (15, 15)] >>> item = (5, 5) >>> insort_left(sorted_collection, item) >>> sorted_collection [(0, 0), (5, 5), (5, 5), (7, 7), (10, 10), (15, 15)] >>> item is sorted_collection[1] True >>> item is sorted_collection[2] False >>> sorted_collection = [0, 5, 7, 10, 15] >>> insort_left(sorted_collection, 20) >>> sorted_collection [0, 5, 7, 10, 15, 20] >>> sorted_collection = [0, 5, 7, 10, 15] >>> insort_left(sorted_collection, 15, 1, 3) >>> sorted_collection [0, 5, 7, 15, 10, 15] """ sorted_collection.insert(bisect_left(sorted_collection, item, lo, hi), item) def insort_right( sorted_collection: list[int], item: int, lo: int = 0, hi: int = -1 ) -> None: """ Inserts a given value into a sorted array after other values with the same value. It has the same interface as https://docs.python.org/3/library/bisect.html#bisect.insort_right . :param sorted_collection: some ascending sorted collection with comparable items :param item: item to insert :param lo: lowest index to consider (as in sorted_collection[lo:hi]) :param hi: past the highest index to consider (as in sorted_collection[lo:hi]) Examples: >>> sorted_collection = [0, 5, 7, 10, 15] >>> insort_right(sorted_collection, 6) >>> sorted_collection [0, 5, 6, 7, 10, 15] >>> sorted_collection = [(0, 0), (5, 5), (7, 7), (10, 10), (15, 15)] >>> item = (5, 5) >>> insort_right(sorted_collection, item) >>> sorted_collection [(0, 0), (5, 5), (5, 5), (7, 7), (10, 10), (15, 15)] >>> item is sorted_collection[1] False >>> item is sorted_collection[2] True >>> sorted_collection = [0, 5, 7, 10, 15] >>> insort_right(sorted_collection, 20) >>> sorted_collection [0, 5, 7, 10, 15, 20] >>> sorted_collection = [0, 5, 7, 10, 15] >>> insort_right(sorted_collection, 15, 1, 3) >>> sorted_collection [0, 5, 7, 15, 10, 15] """ sorted_collection.insert(bisect_right(sorted_collection, item, lo, hi), item) def binary_search(sorted_collection: list[int], item: int) -> int | None: """Pure implementation of binary search algorithm in Python Be careful collection must be ascending sorted, otherwise result will be unpredictable :param sorted_collection: some ascending sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found Examples: >>> binary_search([0, 5, 7, 10, 15], 0) 0 >>> binary_search([0, 5, 7, 10, 15], 15) 4 >>> binary_search([0, 5, 7, 10, 15], 5) 1 >>> binary_search([0, 5, 7, 10, 15], 6) """ left = 0 right = len(sorted_collection) - 1 while left <= right: midpoint = left + (right - left) // 2 current_item = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: right = midpoint - 1 else: left = midpoint + 1 return None def binary_search_std_lib(sorted_collection: list[int], item: int) -> int | None: """Pure implementation of binary search algorithm in Python using stdlib Be careful collection must be ascending sorted, otherwise result will be unpredictable :param sorted_collection: some ascending sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found Examples: >>> binary_search_std_lib([0, 5, 7, 10, 15], 0) 0 >>> binary_search_std_lib([0, 5, 7, 10, 15], 15) 4 >>> binary_search_std_lib([0, 5, 7, 10, 15], 5) 1 >>> binary_search_std_lib([0, 5, 7, 10, 15], 6) """ index = bisect.bisect_left(sorted_collection, item) if index != len(sorted_collection) and sorted_collection[index] == item: return index return None def binary_search_by_recursion( sorted_collection: list[int], item: int, left: int, right: int ) -> int | None: """Pure implementation of binary search algorithm in Python by recursion Be careful collection must be ascending sorted, otherwise result will be unpredictable First recursion should be started with left=0 and right=(len(sorted_collection)-1) :param sorted_collection: some ascending sorted collection with comparable items :param item: item value to search :return: index of found item or None if item is not found Examples: >>> binary_search_by_recursion([0, 5, 7, 10, 15], 0, 0, 4) 0 >>> binary_search_by_recursion([0, 5, 7, 10, 15], 15, 0, 4) 4 >>> binary_search_by_recursion([0, 5, 7, 10, 15], 5, 0, 4) 1 >>> binary_search_by_recursion([0, 5, 7, 10, 15], 6, 0, 4) """ if right < left: return None midpoint = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(sorted_collection, item, left, midpoint - 1) else: return binary_search_by_recursion(sorted_collection, item, midpoint + 1, right) if __name__ == "__main__": user_input = input("Enter numbers separated by comma:\n").strip() collection = sorted(int(item) for item in user_input.split(",")) target = int(input("Enter a single number to be found in the list:\n")) result = binary_search(collection, target) if result is None: print(f"{target} was not found in {collection}.") else: print(f"{target} was found at position {result} in {collection}.")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 __future__ import annotations def n31(a: int) -> tuple[list[int], int]: """ Returns the Collatz sequence and its length of any positive integer. >>> n31(4) ([4, 2, 1], 3) """ if not isinstance(a, int): raise TypeError(f"Must be int, not {type(a).__name__}") if a < 1: raise ValueError(f"Given integer must be greater than 1, not {a}") path = [a] while a != 1: if a % 2 == 0: a = a // 2 else: a = 3 * a + 1 path += [a] return path, len(path) def test_n31(): """ >>> test_n31() """ assert n31(4) == ([4, 2, 1], 3) assert n31(11) == ([11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1], 15) assert n31(31) == ( [ 31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, 412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593, 1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425, 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644, 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, 866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1, ], 107, ) if __name__ == "__main__": num = 4 path, length = n31(num) print(f"The Collatz sequence of {num} took {length} steps. \nPath: {path}")
from __future__ import annotations def n31(a: int) -> tuple[list[int], int]: """ Returns the Collatz sequence and its length of any positive integer. >>> n31(4) ([4, 2, 1], 3) """ if not isinstance(a, int): raise TypeError(f"Must be int, not {type(a).__name__}") if a < 1: raise ValueError(f"Given integer must be greater than 1, not {a}") path = [a] while a != 1: if a % 2 == 0: a = a // 2 else: a = 3 * a + 1 path += [a] return path, len(path) def test_n31(): """ >>> test_n31() """ assert n31(4) == ([4, 2, 1], 3) assert n31(11) == ([11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1], 15) assert n31(31) == ( [ 31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, 412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593, 1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425, 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644, 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, 866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1, ], 107, ) if __name__ == "__main__": num = 4 path, length = n31(num) print(f"The Collatz sequence of {num} took {length} steps. \nPath: {path}")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 number of partitions of a number n into at least k parts equals the number of partitions into exactly k parts plus the number of partitions into at least k-1 parts. Subtracting 1 from each part of a partition of n into k parts gives a partition of n-k into k parts. These two facts together are used for this algorithm. """ def partition(m: int) -> int: memo: list[list[int]] = [[0 for _ in range(m)] for _ in range(m + 1)] for i in range(m + 1): memo[i][0] = 1 for n in range(m + 1): for k in range(1, m): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: n = int(input("Enter a number: ").strip()) print(partition(n)) except ValueError: print("Please enter a number.") else: try: n = int(sys.argv[1]) print(partition(n)) except ValueError: print("Please pass a number.")
""" The number of partitions of a number n into at least k parts equals the number of partitions into exactly k parts plus the number of partitions into at least k-1 parts. Subtracting 1 from each part of a partition of n into k parts gives a partition of n-k into k parts. These two facts together are used for this algorithm. """ def partition(m: int) -> int: memo: list[list[int]] = [[0 for _ in range(m)] for _ in range(m + 1)] for i in range(m + 1): memo[i][0] = 1 for n in range(m + 1): for k in range(1, m): memo[n][k] += memo[n][k - 1] if n - k > 0: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] if __name__ == "__main__": import sys if len(sys.argv) == 1: try: n = int(input("Enter a number: ").strip()) print(partition(n)) except ValueError: print("Please enter a number.") else: try: n = int(sys.argv[1]) print(partition(n)) except ValueError: print("Please pass a number.")
-1
TheAlgorithms/Python
6,230
MAINT: Updated f-string method
### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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}`.
cyai
"2022-07-05T17:02:31Z"
"2022-07-07T14:34:08Z"
0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1
2d5dd6f132a25165473471bf83765ec50c9f14d6
MAINT: Updated f-string method. ### Describe your change: Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * [ ] 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 shutil import requests def get_apod_data(api_key: str, download: bool = False, path: str = ".") -> dict: """ Get the APOD(Astronomical Picture of the day) data Get your API Key from: https://api.nasa.gov/ """ url = "https://api.nasa.gov/planetary/apod" return requests.get(url, params={"api_key": api_key}).json() def save_apod(api_key: str, path: str = ".") -> dict: apod_data = get_apod_data(api_key) img_url = apod_data["url"] img_name = img_url.split("/")[-1] response = requests.get(img_url, stream=True) with open(f"{path}/{img_name}", "wb+") as img_file: shutil.copyfileobj(response.raw, img_file) del response return apod_data def get_archive_data(query: str) -> dict: """ Get the data of a particular query from NASA archives """ url = "https://images-api.nasa.gov/search" return requests.get(url, params={"q": query}).json() if __name__ == "__main__": print(save_apod("YOUR API KEY")) apollo_2011_items = get_archive_data("apollo 2011")["collection"]["items"] print(apollo_2011_items[0]["data"][0]["description"])
import shutil import requests def get_apod_data(api_key: str, download: bool = False, path: str = ".") -> dict: """ Get the APOD(Astronomical Picture of the day) data Get your API Key from: https://api.nasa.gov/ """ url = "https://api.nasa.gov/planetary/apod" return requests.get(url, params={"api_key": api_key}).json() def save_apod(api_key: str, path: str = ".") -> dict: apod_data = get_apod_data(api_key) img_url = apod_data["url"] img_name = img_url.split("/")[-1] response = requests.get(img_url, stream=True) with open(f"{path}/{img_name}", "wb+") as img_file: shutil.copyfileobj(response.raw, img_file) del response return apod_data def get_archive_data(query: str) -> dict: """ Get the data of a particular query from NASA archives """ url = "https://images-api.nasa.gov/search" return requests.get(url, params={"q": query}).json() if __name__ == "__main__": print(save_apod("YOUR API KEY")) apollo_2011_items = get_archive_data("apollo 2011")["collection"]["items"] print(apollo_2011_items[0]["data"][0]["description"])
-1