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
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" An IMPLY Gate is a logic gate in boolean algebra which results to 1 if either input 1 is 0, or if input 1 is 1, then the output is 1 only if input 2 is 1. It is true if input 1 implies input 2. Following is the truth table of an IMPLY Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 1 | | 0 | 1 | 1 | | 1 | 0 | 0 | | 1 | 1 | 1 | ------------------------------ Refer - https://en.wikipedia.org/wiki/IMPLY_gate """ def imply_gate(input_1: int, input_2: int) -> int: """ Calculate IMPLY of the input values >>> imply_gate(0, 0) 1 >>> imply_gate(0, 1) 1 >>> imply_gate(1, 0) 0 >>> imply_gate(1, 1) 1 """ return int(input_1 == 0 or input_2 == 1) if __name__ == "__main__": print(imply_gate(0, 0)) print(imply_gate(0, 1)) print(imply_gate(1, 0)) print(imply_gate(1, 1))
""" An IMPLY Gate is a logic gate in boolean algebra which results to 1 if either input 1 is 0, or if input 1 is 1, then the output is 1 only if input 2 is 1. It is true if input 1 implies input 2. Following is the truth table of an IMPLY Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 1 | | 0 | 1 | 1 | | 1 | 0 | 0 | | 1 | 1 | 1 | ------------------------------ Refer - https://en.wikipedia.org/wiki/IMPLY_gate """ def imply_gate(input_1: int, input_2: int) -> int: """ Calculate IMPLY of the input values >>> imply_gate(0, 0) 1 >>> imply_gate(0, 1) 1 >>> imply_gate(1, 0) 0 >>> imply_gate(1, 1) 1 """ return int(input_1 == 0 or input_2 == 1) if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" A NAND Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are 1, and 1 (True) otherwise. It's similar to adding a NOT gate along with an AND gate. Following is the truth table of a NAND Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 1 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 0 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def nand_gate(input_1: int, input_2: int) -> int: """ Calculate NAND of the input values >>> nand_gate(0, 0) 1 >>> nand_gate(0, 1) 1 >>> nand_gate(1, 0) 1 >>> nand_gate(1, 1) 0 """ return int((input_1, input_2).count(0) != 0) def test_nand_gate() -> None: """ Tests the nand_gate function """ assert nand_gate(0, 0) == 1 assert nand_gate(0, 1) == 1 assert nand_gate(1, 0) == 1 assert nand_gate(1, 1) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
""" A NAND Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are 1, and 1 (True) otherwise. It's similar to adding a NOT gate along with an AND gate. Following is the truth table of a NAND Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 1 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 0 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def nand_gate(input_1: int, input_2: int) -> int: """ Calculate NAND of the input values >>> nand_gate(0, 0) 1 >>> nand_gate(0, 1) 1 >>> nand_gate(1, 0) 1 >>> nand_gate(1, 1) 0 """ return int((input_1, input_2).count(0) != 0) if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" An NIMPLY Gate is a logic gate in boolean algebra which results to 0 if either input 1 is 0, or if input 1 is 1, then it is 0 only if input 2 is 1. It is false if input 1 implies input 2. It is the negated form of imply Following is the truth table of an NIMPLY Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 0 | | 0 | 1 | 0 | | 1 | 0 | 1 | | 1 | 1 | 0 | ------------------------------ Refer - https://en.wikipedia.org/wiki/NIMPLY_gate """ def nimply_gate(input_1: int, input_2: int) -> int: """ Calculate NIMPLY of the input values >>> nimply_gate(0, 0) 0 >>> nimply_gate(0, 1) 0 >>> nimply_gate(1, 0) 1 >>> nimply_gate(1, 1) 0 """ return int(input_1 == 1 and input_2 == 0) if __name__ == "__main__": print(nimply_gate(0, 0)) print(nimply_gate(0, 1)) print(nimply_gate(1, 0)) print(nimply_gate(1, 1))
""" An NIMPLY Gate is a logic gate in boolean algebra which results to 0 if either input 1 is 0, or if input 1 is 1, then it is 0 only if input 2 is 1. It is false if input 1 implies input 2. It is the negated form of imply Following is the truth table of an NIMPLY Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 0 | | 0 | 1 | 0 | | 1 | 0 | 1 | | 1 | 1 | 0 | ------------------------------ Refer - https://en.wikipedia.org/wiki/NIMPLY_gate """ def nimply_gate(input_1: int, input_2: int) -> int: """ Calculate NIMPLY of the input values >>> nimply_gate(0, 0) 0 >>> nimply_gate(0, 1) 0 >>> nimply_gate(1, 0) 1 >>> nimply_gate(1, 1) 0 """ return int(input_1 == 1 and input_2 == 0) if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" A NOT Gate is a logic gate in boolean algebra which results to 0 (False) if the input is high, and 1 (True) if the input is low. Following is the truth table of a XOR Gate: ------------------------------ | Input | Output | ------------------------------ | 0 | 1 | | 1 | 0 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def not_gate(input_1: int) -> int: """ Calculate NOT of the input values >>> not_gate(0) 1 >>> not_gate(1) 0 """ return 1 if input_1 == 0 else 0 def test_not_gate() -> None: """ Tests the not_gate function """ assert not_gate(0) == 1 assert not_gate(1) == 0 if __name__ == "__main__": print(not_gate(0)) print(not_gate(1))
""" A NOT Gate is a logic gate in boolean algebra which results to 0 (False) if the input is high, and 1 (True) if the input is low. Following is the truth table of a XOR Gate: ------------------------------ | Input | Output | ------------------------------ | 0 | 1 | | 1 | 0 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def not_gate(input_1: int) -> int: """ Calculate NOT of the input values >>> not_gate(0) 1 >>> not_gate(1) 0 """ return 1 if input_1 == 0 else 0 if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" An OR Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are 0, and 1 (True) otherwise. Following is the truth table of an AND Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 0 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 1 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def or_gate(input_1: int, input_2: int) -> int: """ Calculate OR of the input values >>> or_gate(0, 0) 0 >>> or_gate(0, 1) 1 >>> or_gate(1, 0) 1 >>> or_gate(1, 1) 1 """ return int((input_1, input_2).count(1) != 0) def test_or_gate() -> None: """ Tests the or_gate function """ assert or_gate(0, 0) == 0 assert or_gate(0, 1) == 1 assert or_gate(1, 0) == 1 assert or_gate(1, 1) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
""" An OR Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are 0, and 1 (True) otherwise. Following is the truth table of an AND Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 0 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 1 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def or_gate(input_1: int, input_2: int) -> int: """ Calculate OR of the input values >>> or_gate(0, 0) 0 >>> or_gate(0, 1) 1 >>> or_gate(1, 0) 1 >>> or_gate(1, 1) 1 """ return int((input_1, input_2).count(1) != 0) if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" A XNOR Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are different, and 1 (True), if the inputs are same. It's similar to adding a NOT gate to an XOR gate Following is the truth table of a XNOR Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 1 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 1 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def xnor_gate(input_1: int, input_2: int) -> int: """ Calculate XOR of the input values >>> xnor_gate(0, 0) 1 >>> xnor_gate(0, 1) 0 >>> xnor_gate(1, 0) 0 >>> xnor_gate(1, 1) 1 """ return 1 if input_1 == input_2 else 0 def test_xnor_gate() -> None: """ Tests the xnor_gate function """ assert xnor_gate(0, 0) == 1 assert xnor_gate(0, 1) == 0 assert xnor_gate(1, 0) == 0 assert xnor_gate(1, 1) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
""" A XNOR Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are different, and 1 (True), if the inputs are same. It's similar to adding a NOT gate to an XOR gate Following is the truth table of a XNOR Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 1 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 1 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def xnor_gate(input_1: int, input_2: int) -> int: """ Calculate XOR of the input values >>> xnor_gate(0, 0) 1 >>> xnor_gate(0, 1) 0 >>> xnor_gate(1, 0) 0 >>> xnor_gate(1, 1) 1 """ return 1 if input_1 == input_2 else 0 if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" A XOR Gate is a logic gate in boolean algebra which results to 1 (True) if only one of the two inputs is 1, and 0 (False) if an even number of inputs are 1. Following is the truth table of a XOR Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 0 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 0 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def xor_gate(input_1: int, input_2: int) -> int: """ calculate xor of the input values >>> xor_gate(0, 0) 0 >>> xor_gate(0, 1) 1 >>> xor_gate(1, 0) 1 >>> xor_gate(1, 1) 0 """ return (input_1, input_2).count(0) % 2 def test_xor_gate() -> None: """ Tests the xor_gate function """ assert xor_gate(0, 0) == 0 assert xor_gate(0, 1) == 1 assert xor_gate(1, 0) == 1 assert xor_gate(1, 1) == 0 if __name__ == "__main__": print(xor_gate(0, 0)) print(xor_gate(0, 1))
""" A XOR Gate is a logic gate in boolean algebra which results to 1 (True) if only one of the two inputs is 1, and 0 (False) if an even number of inputs are 1. Following is the truth table of a XOR Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 0 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 0 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def xor_gate(input_1: int, input_2: int) -> int: """ calculate xor of the input values >>> xor_gate(0, 0) 0 >>> xor_gate(0, 1) 1 >>> xor_gate(1, 0) 1 >>> xor_gate(1, 1) 0 """ return (input_1, input_2).count(0) % 2 if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" https://en.wikipedia.org/wiki/3SUM """ def three_sum(nums: list[int]) -> list[list[int]]: """ Find all unique triplets in a sorted array of integers that sum up to zero. Args: nums: A sorted list of integers. Returns: A list of lists containing unique triplets that sum up to zero. >>> three_sum([-1, 0, 1, 2, -1, -4]) [[-1, -1, 2], [-1, 0, 1]] >>> three_sum([1, 2, 3, 4]) [] """ nums.sort() ans = [] for i in range(len(nums) - 2): if i == 0 or (nums[i] != nums[i - 1]): low, high, c = i + 1, len(nums) - 1, 0 - nums[i] while low < high: if nums[low] + nums[high] == c: ans.append([nums[i], nums[low], nums[high]]) while low < high and nums[low] == nums[low + 1]: low += 1 while low < high and nums[high] == nums[high - 1]: high -= 1 low += 1 high -= 1 elif nums[low] + nums[high] < c: low += 1 else: high -= 1 return ans if __name__ == "__main__": import doctest doctest.testmod()
""" https://en.wikipedia.org/wiki/3SUM """ def three_sum(nums: list[int]) -> list[list[int]]: """ Find all unique triplets in a sorted array of integers that sum up to zero. Args: nums: A sorted list of integers. Returns: A list of lists containing unique triplets that sum up to zero. >>> three_sum([-1, 0, 1, 2, -1, -4]) [[-1, -1, 2], [-1, 0, 1]] >>> three_sum([1, 2, 3, 4]) [] """ nums.sort() ans = [] for i in range(len(nums) - 2): if i == 0 or (nums[i] != nums[i - 1]): low, high, c = i + 1, len(nums) - 1, 0 - nums[i] while low < high: if nums[low] + nums[high] == c: ans.append([nums[i], nums[low], nums[high]]) while low < high and nums[low] == nums[low + 1]: low += 1 while low < high and nums[high] == nums[high - 1]: high -= 1 low += 1 high -= 1 elif nums[low] + nums[high] < c: low += 1 else: high -= 1 return ans if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# A Python implementation of the Banker's Algorithm in Operating Systems using # Processes and Resources # { # "Author: "Biney Kingsley (bluedistro@github.io), bineykingsley36@gmail.com", # "Date": 28-10-2018 # } """ The Banker's algorithm is a resource allocation and deadlock avoidance algorithm developed by Edsger Dijkstra that tests for safety by simulating the allocation of predetermined maximum possible amounts of all resources, and then makes a "s-state" check to test for possible deadlock conditions for all other pending activities, before deciding whether allocation should be allowed to continue. [Source] Wikipedia [Credit] Rosetta Code C implementation helped very much. (https://rosettacode.org/wiki/Banker%27s_algorithm) """ from __future__ import annotations import time import numpy as np test_claim_vector = [8, 5, 9, 7] test_allocated_res_table = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] test_maximum_claim_table = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class BankersAlgorithm: def __init__( self, claim_vector: list[int], allocated_resources_table: list[list[int]], maximum_claim_table: list[list[int]], ) -> None: """ :param claim_vector: A nxn/nxm list depicting the amount of each resources (eg. memory, interface, semaphores, etc.) available. :param allocated_resources_table: A nxn/nxm list depicting the amount of each resource each process is currently holding :param maximum_claim_table: A nxn/nxm list depicting how much of each resource the system currently has available """ self.__claim_vector = claim_vector self.__allocated_resources_table = allocated_resources_table self.__maximum_claim_table = maximum_claim_table def __processes_resource_summation(self) -> list[int]: """ Check for allocated resources in line with each resource in the claim vector """ return [ sum(p_item[i] for p_item in self.__allocated_resources_table) for i in range(len(self.__allocated_resources_table[0])) ] def __available_resources(self) -> list[int]: """ Check for available resources in line with each resource in the claim vector """ return np.array(self.__claim_vector) - np.array( self.__processes_resource_summation() ) def __need(self) -> list[list[int]]: """ Implement safety checker that calculates the needs by ensuring that max_claim[i][j] - alloc_table[i][j] <= avail[j] """ return [ list(np.array(self.__maximum_claim_table[i]) - np.array(allocated_resource)) for i, allocated_resource in enumerate(self.__allocated_resources_table) ] def __need_index_manager(self) -> dict[int, list[int]]: """ This function builds an index control dictionary to track original ids/indices of processes when altered during execution of method "main" Return: {0: [a: int, b: int], 1: [c: int, d: int]} >>> (BankersAlgorithm(test_claim_vector, test_allocated_res_table, ... test_maximum_claim_table)._BankersAlgorithm__need_index_manager() ... ) # doctest: +NORMALIZE_WHITESPACE {0: [1, 2, 0, 3], 1: [0, 1, 3, 1], 2: [1, 1, 0, 2], 3: [1, 3, 2, 0], 4: [2, 0, 0, 3]} """ return {self.__need().index(i): i for i in self.__need()} def main(self, **kwargs) -> None: """ Utilize various methods in this class to simulate the Banker's algorithm Return: None >>> BankersAlgorithm(test_claim_vector, test_allocated_res_table, ... test_maximum_claim_table).main(describe=True) Allocated Resource Table P1 2 0 1 1 <BLANKLINE> P2 0 1 2 1 <BLANKLINE> P3 4 0 0 3 <BLANKLINE> P4 0 2 1 0 <BLANKLINE> P5 1 0 3 0 <BLANKLINE> System Resource Table P1 3 2 1 4 <BLANKLINE> P2 0 2 5 2 <BLANKLINE> P3 5 1 0 5 <BLANKLINE> P4 1 5 3 0 <BLANKLINE> P5 3 0 3 3 <BLANKLINE> Current Usage by Active Processes: 8 5 9 7 Initial Available Resources: 1 2 2 2 __________________________________________________ <BLANKLINE> Process 3 is executing. Updated available resource stack for processes: 5 2 2 5 The process is in a safe state. <BLANKLINE> Process 1 is executing. Updated available resource stack for processes: 7 2 3 6 The process is in a safe state. <BLANKLINE> Process 2 is executing. Updated available resource stack for processes: 7 3 5 7 The process is in a safe state. <BLANKLINE> Process 4 is executing. Updated available resource stack for processes: 7 5 6 7 The process is in a safe state. <BLANKLINE> Process 5 is executing. Updated available resource stack for processes: 8 5 9 7 The process is in a safe state. <BLANKLINE> """ need_list = self.__need() alloc_resources_table = self.__allocated_resources_table available_resources = self.__available_resources() need_index_manager = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("_" * 50 + "\n") while need_list: safe = False for each_need in need_list: execution = True for index, need in enumerate(each_need): if need > available_resources[index]: execution = False break if execution: safe = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: process_number = original_need_index print(f"Process {process_number + 1} is executing.") # remove the process run from stack need_list.remove(each_need) # update available/freed resources stack available_resources = np.array(available_resources) + np.array( alloc_resources_table[process_number] ) print( "Updated available resource stack for processes: " + " ".join([str(x) for x in available_resources]) ) break if safe: print("The process is in a safe state.\n") else: print("System in unsafe state. Aborting...\n") break def __pretty_data(self): """ Properly align display of the algorithm's solution """ print(" " * 9 + "Allocated Resource Table") for item in self.__allocated_resources_table: print( f"P{self.__allocated_resources_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print(" " * 9 + "System Resource Table") for item in self.__maximum_claim_table: print( f"P{self.__maximum_claim_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print( "Current Usage by Active Processes: " + " ".join(str(x) for x in self.__claim_vector) ) print( "Initial Available Resources: " + " ".join(str(x) for x in self.__available_resources()) ) time.sleep(1) if __name__ == "__main__": import doctest doctest.testmod()
# A Python implementation of the Banker's Algorithm in Operating Systems using # Processes and Resources # { # "Author: "Biney Kingsley (bluedistro@github.io), bineykingsley36@gmail.com", # "Date": 28-10-2018 # } """ The Banker's algorithm is a resource allocation and deadlock avoidance algorithm developed by Edsger Dijkstra that tests for safety by simulating the allocation of predetermined maximum possible amounts of all resources, and then makes a "s-state" check to test for possible deadlock conditions for all other pending activities, before deciding whether allocation should be allowed to continue. [Source] Wikipedia [Credit] Rosetta Code C implementation helped very much. (https://rosettacode.org/wiki/Banker%27s_algorithm) """ from __future__ import annotations import time import numpy as np test_claim_vector = [8, 5, 9, 7] test_allocated_res_table = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] test_maximum_claim_table = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class BankersAlgorithm: def __init__( self, claim_vector: list[int], allocated_resources_table: list[list[int]], maximum_claim_table: list[list[int]], ) -> None: """ :param claim_vector: A nxn/nxm list depicting the amount of each resources (eg. memory, interface, semaphores, etc.) available. :param allocated_resources_table: A nxn/nxm list depicting the amount of each resource each process is currently holding :param maximum_claim_table: A nxn/nxm list depicting how much of each resource the system currently has available """ self.__claim_vector = claim_vector self.__allocated_resources_table = allocated_resources_table self.__maximum_claim_table = maximum_claim_table def __processes_resource_summation(self) -> list[int]: """ Check for allocated resources in line with each resource in the claim vector """ return [ sum(p_item[i] for p_item in self.__allocated_resources_table) for i in range(len(self.__allocated_resources_table[0])) ] def __available_resources(self) -> list[int]: """ Check for available resources in line with each resource in the claim vector """ return np.array(self.__claim_vector) - np.array( self.__processes_resource_summation() ) def __need(self) -> list[list[int]]: """ Implement safety checker that calculates the needs by ensuring that max_claim[i][j] - alloc_table[i][j] <= avail[j] """ return [ list(np.array(self.__maximum_claim_table[i]) - np.array(allocated_resource)) for i, allocated_resource in enumerate(self.__allocated_resources_table) ] def __need_index_manager(self) -> dict[int, list[int]]: """ This function builds an index control dictionary to track original ids/indices of processes when altered during execution of method "main" Return: {0: [a: int, b: int], 1: [c: int, d: int]} >>> (BankersAlgorithm(test_claim_vector, test_allocated_res_table, ... test_maximum_claim_table)._BankersAlgorithm__need_index_manager() ... ) # doctest: +NORMALIZE_WHITESPACE {0: [1, 2, 0, 3], 1: [0, 1, 3, 1], 2: [1, 1, 0, 2], 3: [1, 3, 2, 0], 4: [2, 0, 0, 3]} """ return {self.__need().index(i): i for i in self.__need()} def main(self, **kwargs) -> None: """ Utilize various methods in this class to simulate the Banker's algorithm Return: None >>> BankersAlgorithm(test_claim_vector, test_allocated_res_table, ... test_maximum_claim_table).main(describe=True) Allocated Resource Table P1 2 0 1 1 <BLANKLINE> P2 0 1 2 1 <BLANKLINE> P3 4 0 0 3 <BLANKLINE> P4 0 2 1 0 <BLANKLINE> P5 1 0 3 0 <BLANKLINE> System Resource Table P1 3 2 1 4 <BLANKLINE> P2 0 2 5 2 <BLANKLINE> P3 5 1 0 5 <BLANKLINE> P4 1 5 3 0 <BLANKLINE> P5 3 0 3 3 <BLANKLINE> Current Usage by Active Processes: 8 5 9 7 Initial Available Resources: 1 2 2 2 __________________________________________________ <BLANKLINE> Process 3 is executing. Updated available resource stack for processes: 5 2 2 5 The process is in a safe state. <BLANKLINE> Process 1 is executing. Updated available resource stack for processes: 7 2 3 6 The process is in a safe state. <BLANKLINE> Process 2 is executing. Updated available resource stack for processes: 7 3 5 7 The process is in a safe state. <BLANKLINE> Process 4 is executing. Updated available resource stack for processes: 7 5 6 7 The process is in a safe state. <BLANKLINE> Process 5 is executing. Updated available resource stack for processes: 8 5 9 7 The process is in a safe state. <BLANKLINE> """ need_list = self.__need() alloc_resources_table = self.__allocated_resources_table available_resources = self.__available_resources() need_index_manager = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print("_" * 50 + "\n") while need_list: safe = False for each_need in need_list: execution = True for index, need in enumerate(each_need): if need > available_resources[index]: execution = False break if execution: safe = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: process_number = original_need_index print(f"Process {process_number + 1} is executing.") # remove the process run from stack need_list.remove(each_need) # update available/freed resources stack available_resources = np.array(available_resources) + np.array( alloc_resources_table[process_number] ) print( "Updated available resource stack for processes: " + " ".join([str(x) for x in available_resources]) ) break if safe: print("The process is in a safe state.\n") else: print("System in unsafe state. Aborting...\n") break def __pretty_data(self): """ Properly align display of the algorithm's solution """ print(" " * 9 + "Allocated Resource Table") for item in self.__allocated_resources_table: print( f"P{self.__allocated_resources_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print(" " * 9 + "System Resource Table") for item in self.__maximum_claim_table: print( f"P{self.__maximum_claim_table.index(item) + 1}" + " ".join(f"{it:>8}" for it in item) + "\n" ) print( "Current Usage by Active Processes: " + " ".join(str(x) for x in self.__claim_vector) ) print( "Initial Available Resources: " + " ".join(str(x) for x in self.__available_resources()) ) time.sleep(1) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_or(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, and return a binary number that is the result of a binary or operation on the integers provided. >>> binary_or(25, 32) '0b111001' >>> binary_or(37, 50) '0b110111' >>> binary_or(21, 30) '0b11111' >>> binary_or(58, 73) '0b1111011' >>> binary_or(0, 255) '0b11111111' >>> binary_or(0, 256) '0b100000000' >>> binary_or(0, -1) Traceback (most recent call last): ... ValueError: the value of both inputs must be positive >>> binary_or(0, 1.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binary_or("0", "1") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive") a_binary = str(bin(a))[2:] # remove the leading "0b" b_binary = str(bin(b))[2:] max_len = max(len(a_binary), len(b_binary)) return "0b" + "".join( str(int("1" in (char_a, char_b))) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) ) if __name__ == "__main__": import doctest doctest.testmod()
# https://www.tutorialspoint.com/python3/bitwise_operators_example.htm def binary_or(a: int, b: int) -> str: """ Take in 2 integers, convert them to binary, and return a binary number that is the result of a binary or operation on the integers provided. >>> binary_or(25, 32) '0b111001' >>> binary_or(37, 50) '0b110111' >>> binary_or(21, 30) '0b11111' >>> binary_or(58, 73) '0b1111011' >>> binary_or(0, 255) '0b11111111' >>> binary_or(0, 256) '0b100000000' >>> binary_or(0, -1) Traceback (most recent call last): ... ValueError: the value of both inputs must be positive >>> binary_or(0, 1.1) Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> binary_or("0", "1") Traceback (most recent call last): ... TypeError: '<' not supported between instances of 'str' and 'int' """ if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive") a_binary = str(bin(a))[2:] # remove the leading "0b" b_binary = str(bin(b))[2:] max_len = max(len(a_binary), len(b_binary)) return "0b" + "".join( str(int("1" in (char_a, char_b))) for char_a, char_b in zip(a_binary.zfill(max_len), b_binary.zfill(max_len)) ) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from __future__ import annotations import requests def get_hackernews_story(story_id: str) -> dict: url = f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(url).json() def hackernews_top_stories(max_stories: int = 10) -> list[dict]: """ Get the top max_stories posts from HackerNews - https://news.ycombinator.com/ """ url = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty" story_ids = requests.get(url).json()[:max_stories] return [get_hackernews_story(story_id) for story_id in story_ids] def hackernews_top_stories_as_markdown(max_stories: int = 10) -> str: stories = hackernews_top_stories(max_stories) return "\n".join("* [{title}]({url})".format(**story) for story in stories) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
from __future__ import annotations import requests def get_hackernews_story(story_id: str) -> dict: url = f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(url).json() def hackernews_top_stories(max_stories: int = 10) -> list[dict]: """ Get the top max_stories posts from HackerNews - https://news.ycombinator.com/ """ url = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty" story_ids = requests.get(url).json()[:max_stories] return [get_hackernews_story(story_id) for story_id in story_ids] def hackernews_top_stories_as_markdown(max_stories: int = 10) -> str: stories = hackernews_top_stories(max_stories) return "\n".join("* [{title}]({url})".format(**story) for story in stories) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from __future__ import annotations def dfs(u): global graph, reversed_graph, scc, component, visit, stack if visit[u]: return visit[u] = True for v in graph[u]: dfs(v) stack.append(u) def dfs2(u): global graph, reversed_graph, scc, component, visit, stack if visit[u]: return visit[u] = True component.append(u) for v in reversed_graph[u]: dfs2(v) def kosaraju(): global graph, reversed_graph, scc, component, visit, stack for i in range(n): dfs(i) visit = [False] * n for i in stack[::-1]: if visit[i]: continue component = [] dfs2(i) scc.append(component) return scc if __name__ == "__main__": # n - no of nodes, m - no of edges n, m = list(map(int, input().strip().split())) graph: list[list[int]] = [[] for _ in range(n)] # graph reversed_graph: list[list[int]] = [[] for i in range(n)] # reversed graph # input graph data (edges) for _ in range(m): u, v = list(map(int, input().strip().split())) graph[u].append(v) reversed_graph[v].append(u) stack: list[int] = [] visit: list[bool] = [False] * n scc: list[int] = [] component: list[int] = [] print(kosaraju())
from __future__ import annotations def dfs(u): global graph, reversed_graph, scc, component, visit, stack if visit[u]: return visit[u] = True for v in graph[u]: dfs(v) stack.append(u) def dfs2(u): global graph, reversed_graph, scc, component, visit, stack if visit[u]: return visit[u] = True component.append(u) for v in reversed_graph[u]: dfs2(v) def kosaraju(): global graph, reversed_graph, scc, component, visit, stack for i in range(n): dfs(i) visit = [False] * n for i in stack[::-1]: if visit[i]: continue component = [] dfs2(i) scc.append(component) return scc if __name__ == "__main__": # n - no of nodes, m - no of edges n, m = list(map(int, input().strip().split())) graph: list[list[int]] = [[] for _ in range(n)] # graph reversed_graph: list[list[int]] = [[] for i in range(n)] # reversed graph # input graph data (edges) for _ in range(m): u, v = list(map(int, input().strip().split())) graph[u].append(v) reversed_graph[v].append(u) stack: list[int] = [] visit: list[bool] = [False] * n scc: list[int] = [] component: list[int] = [] print(kosaraju())
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Coulomb's law states that the magnitude of the electrostatic force of attraction or repulsion between two point charges is directly proportional to the product of the magnitudes of charges and inversely proportional to the square of the distance between them. F = k * q1 * q2 / r^2 k is Coulomb's constant and equals 1/(4π*ε0) q1 is charge of first body (C) q2 is charge of second body (C) r is distance between two charged bodies (m) Reference: https://en.wikipedia.org/wiki/Coulomb%27s_law """ def coulombs_law(q1: float, q2: float, radius: float) -> float: """ Calculate the electrostatic force of attraction or repulsion between two point charges >>> coulombs_law(15.5, 20, 15) 12382849136.06 >>> coulombs_law(1, 15, 5) 5392531075.38 >>> coulombs_law(20, -50, 15) -39944674632.44 >>> coulombs_law(-5, -8, 10) 3595020716.92 >>> coulombs_law(50, 100, 50) 17975103584.6 """ if radius <= 0: raise ValueError("The radius is always a positive number") return round(((8.9875517923 * 10**9) * q1 * q2) / (radius**2), 2) if __name__ == "__main__": import doctest doctest.testmod()
""" Coulomb's law states that the magnitude of the electrostatic force of attraction or repulsion between two point charges is directly proportional to the product of the magnitudes of charges and inversely proportional to the square of the distance between them. F = k * q1 * q2 / r^2 k is Coulomb's constant and equals 1/(4π*ε0) q1 is charge of first body (C) q2 is charge of second body (C) r is distance between two charged bodies (m) Reference: https://en.wikipedia.org/wiki/Coulomb%27s_law """ def coulombs_law(q1: float, q2: float, radius: float) -> float: """ Calculate the electrostatic force of attraction or repulsion between two point charges >>> coulombs_law(15.5, 20, 15) 12382849136.06 >>> coulombs_law(1, 15, 5) 5392531075.38 >>> coulombs_law(20, -50, 15) -39944674632.44 >>> coulombs_law(-5, -8, 10) 3595020716.92 >>> coulombs_law(50, 100, 50) 17975103584.6 """ if radius <= 0: raise ValueError("The radius is always a positive number") return round(((8.9875517923 * 10**9) * q1 * q2) / (radius**2), 2) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 50: https://projecteuler.net/problem=50 Consecutive prime sum The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes? """ from __future__ import annotations def prime_sieve(limit: int) -> list[int]: """ Sieve of Erotosthenes Function to return all the prime numbers up to a number 'limit' https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes >>> prime_sieve(3) [2] >>> prime_sieve(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] """ is_prime = [True] * limit is_prime[0] = False is_prime[1] = False is_prime[2] = True for i in range(3, int(limit**0.5 + 1), 2): index = i * 2 while index < limit: is_prime[index] = False index = index + i primes = [2] for i in range(3, limit, 2): if is_prime[i]: primes.append(i) return primes def solution(ceiling: int = 1_000_000) -> int: """ Returns the biggest prime, below the celing, that can be written as the sum of consecutive the most consecutive primes. >>> solution(500) 499 >>> solution(1_000) 953 >>> solution(10_000) 9521 """ primes = prime_sieve(ceiling) length = 0 largest = 0 for i in range(len(primes)): for j in range(i + length, len(primes)): sol = sum(primes[i:j]) if sol >= ceiling: break if sol in primes: length = j - i largest = sol return largest if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 50: https://projecteuler.net/problem=50 Consecutive prime sum The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes? """ from __future__ import annotations def prime_sieve(limit: int) -> list[int]: """ Sieve of Erotosthenes Function to return all the prime numbers up to a number 'limit' https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes >>> prime_sieve(3) [2] >>> prime_sieve(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] """ is_prime = [True] * limit is_prime[0] = False is_prime[1] = False is_prime[2] = True for i in range(3, int(limit**0.5 + 1), 2): index = i * 2 while index < limit: is_prime[index] = False index = index + i primes = [2] for i in range(3, limit, 2): if is_prime[i]: primes.append(i) return primes def solution(ceiling: int = 1_000_000) -> int: """ Returns the biggest prime, below the celing, that can be written as the sum of consecutive the most consecutive primes. >>> solution(500) 499 >>> solution(1_000) 953 >>> solution(10_000) 9521 """ primes = prime_sieve(ceiling) length = 0 largest = 0 for i in range(len(primes)): for j in range(i + length, len(primes)): sol = sum(primes[i:j]) if sol >= ceiling: break if sol in primes: length = j - i largest = sol return largest if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
#!/usr/bin/env python # # Sort large text files in a minimum amount of memory # import argparse import os class FileSplitter: BLOCK_FILENAME_FORMAT = "block_{0}.dat" def __init__(self, filename): self.filename = filename self.block_filenames = [] def write_block(self, data, block_number): filename = self.BLOCK_FILENAME_FORMAT.format(block_number) with open(filename, "w") as file: file.write(data) self.block_filenames.append(filename) def get_block_filenames(self): return self.block_filenames def split(self, block_size, sort_key=None): i = 0 with open(self.filename) as file: while True: lines = file.readlines(block_size) if lines == []: break if sort_key is None: lines.sort() else: lines.sort(key=sort_key) self.write_block("".join(lines), i) i += 1 def cleanup(self): map(os.remove, self.block_filenames) class NWayMerge: def select(self, choices): min_index = -1 min_str = None for i in range(len(choices)): if min_str is None or choices[i] < min_str: min_index = i return min_index class FilesArray: def __init__(self, files): self.files = files self.empty = set() self.num_buffers = len(files) self.buffers = {i: None for i in range(self.num_buffers)} def get_dict(self): return { i: self.buffers[i] for i in range(self.num_buffers) if i not in self.empty } def refresh(self): for i in range(self.num_buffers): if self.buffers[i] is None and i not in self.empty: self.buffers[i] = self.files[i].readline() if self.buffers[i] == "": self.empty.add(i) self.files[i].close() if len(self.empty) == self.num_buffers: return False return True def unshift(self, index): value = self.buffers[index] self.buffers[index] = None return value class FileMerger: def __init__(self, merge_strategy): self.merge_strategy = merge_strategy def merge(self, filenames, outfilename, buffer_size): buffers = FilesArray(self.get_file_handles(filenames, buffer_size)) with open(outfilename, "w", buffer_size) as outfile: while buffers.refresh(): min_index = self.merge_strategy.select(buffers.get_dict()) outfile.write(buffers.unshift(min_index)) def get_file_handles(self, filenames, buffer_size): files = {} for i in range(len(filenames)): files[i] = open(filenames[i], "r", buffer_size) # noqa: UP015 return files class ExternalSort: def __init__(self, block_size): self.block_size = block_size def sort(self, filename, sort_key=None): num_blocks = self.get_number_blocks(filename, self.block_size) splitter = FileSplitter(filename) splitter.split(self.block_size, sort_key) merger = FileMerger(NWayMerge()) buffer_size = self.block_size / (num_blocks + 1) merger.merge(splitter.get_block_filenames(), filename + ".out", buffer_size) splitter.cleanup() def get_number_blocks(self, filename, block_size): return (os.stat(filename).st_size / block_size) + 1 def parse_memory(string): if string[-1].lower() == "k": return int(string[:-1]) * 1024 elif string[-1].lower() == "m": return int(string[:-1]) * 1024 * 1024 elif string[-1].lower() == "g": return int(string[:-1]) * 1024 * 1024 * 1024 else: return int(string) def main(): parser = argparse.ArgumentParser() parser.add_argument( "-m", "--mem", help="amount of memory to use for sorting", default="100M" ) parser.add_argument( "filename", metavar="<filename>", nargs=1, help="name of file to sort" ) args = parser.parse_args() sorter = ExternalSort(parse_memory(args.mem)) sorter.sort(args.filename[0]) if __name__ == "__main__": main()
#!/usr/bin/env python # # Sort large text files in a minimum amount of memory # import argparse import os class FileSplitter: BLOCK_FILENAME_FORMAT = "block_{0}.dat" def __init__(self, filename): self.filename = filename self.block_filenames = [] def write_block(self, data, block_number): filename = self.BLOCK_FILENAME_FORMAT.format(block_number) with open(filename, "w") as file: file.write(data) self.block_filenames.append(filename) def get_block_filenames(self): return self.block_filenames def split(self, block_size, sort_key=None): i = 0 with open(self.filename) as file: while True: lines = file.readlines(block_size) if lines == []: break if sort_key is None: lines.sort() else: lines.sort(key=sort_key) self.write_block("".join(lines), i) i += 1 def cleanup(self): map(os.remove, self.block_filenames) class NWayMerge: def select(self, choices): min_index = -1 min_str = None for i in range(len(choices)): if min_str is None or choices[i] < min_str: min_index = i return min_index class FilesArray: def __init__(self, files): self.files = files self.empty = set() self.num_buffers = len(files) self.buffers = {i: None for i in range(self.num_buffers)} def get_dict(self): return { i: self.buffers[i] for i in range(self.num_buffers) if i not in self.empty } def refresh(self): for i in range(self.num_buffers): if self.buffers[i] is None and i not in self.empty: self.buffers[i] = self.files[i].readline() if self.buffers[i] == "": self.empty.add(i) self.files[i].close() if len(self.empty) == self.num_buffers: return False return True def unshift(self, index): value = self.buffers[index] self.buffers[index] = None return value class FileMerger: def __init__(self, merge_strategy): self.merge_strategy = merge_strategy def merge(self, filenames, outfilename, buffer_size): buffers = FilesArray(self.get_file_handles(filenames, buffer_size)) with open(outfilename, "w", buffer_size) as outfile: while buffers.refresh(): min_index = self.merge_strategy.select(buffers.get_dict()) outfile.write(buffers.unshift(min_index)) def get_file_handles(self, filenames, buffer_size): files = {} for i in range(len(filenames)): files[i] = open(filenames[i], "r", buffer_size) # noqa: UP015 return files class ExternalSort: def __init__(self, block_size): self.block_size = block_size def sort(self, filename, sort_key=None): num_blocks = self.get_number_blocks(filename, self.block_size) splitter = FileSplitter(filename) splitter.split(self.block_size, sort_key) merger = FileMerger(NWayMerge()) buffer_size = self.block_size / (num_blocks + 1) merger.merge(splitter.get_block_filenames(), filename + ".out", buffer_size) splitter.cleanup() def get_number_blocks(self, filename, block_size): return (os.stat(filename).st_size / block_size) + 1 def parse_memory(string): if string[-1].lower() == "k": return int(string[:-1]) * 1024 elif string[-1].lower() == "m": return int(string[:-1]) * 1024 * 1024 elif string[-1].lower() == "g": return int(string[:-1]) * 1024 * 1024 * 1024 else: return int(string) def main(): parser = argparse.ArgumentParser() parser.add_argument( "-m", "--mem", help="amount of memory to use for sorting", default="100M" ) parser.add_argument( "filename", metavar="<filename>", nargs=1, help="name of file to sort" ) args = parser.parse_args() sorter = ExternalSort(parse_memory(args.mem)) sorter.sort(args.filename[0]) if __name__ == "__main__": main()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# Created by sarathkaul on 12/11/19 import requests def send_slack_message(message_body: str, slack_url: str) -> None: headers = {"Content-Type": "application/json"} response = requests.post(slack_url, json={"text": message_body}, headers=headers) if response.status_code != 200: msg = ( "Request to slack returned an error " f"{response.status_code}, the response is:\n{response.text}" ) raise ValueError(msg) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
# Created by sarathkaul on 12/11/19 import requests def send_slack_message(message_body: str, slack_url: str) -> None: headers = {"Content-Type": "application/json"} response = requests.post(slack_url, json={"text": message_body}, headers=headers) if response.status_code != 200: msg = ( "Request to slack returned an error " f"{response.status_code}, the response is:\n{response.text}" ) raise ValueError(msg) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Sum of all nodes in a binary tree. Python implementation: O(n) time complexity - Recurses through :meth:`depth_first_search` with each element. O(n) space complexity - At any point in time maximum number of stack frames that could be in memory is `n` """ from __future__ import annotations from collections.abc import Iterator class Node: """ A Node has a value variable and pointers to Nodes to its left and right. """ def __init__(self, value: int) -> None: self.value = value self.left: Node | None = None self.right: Node | None = None class BinaryTreeNodeSum: r""" The below tree looks like this 10 / \ 5 -3 / / \ 12 8 0 >>> tree = Node(10) >>> sum(BinaryTreeNodeSum(tree)) 10 >>> tree.left = Node(5) >>> sum(BinaryTreeNodeSum(tree)) 15 >>> tree.right = Node(-3) >>> sum(BinaryTreeNodeSum(tree)) 12 >>> tree.left.left = Node(12) >>> sum(BinaryTreeNodeSum(tree)) 24 >>> tree.right.left = Node(8) >>> tree.right.right = Node(0) >>> sum(BinaryTreeNodeSum(tree)) 32 """ def __init__(self, tree: Node) -> None: self.tree = tree def depth_first_search(self, node: Node | None) -> int: if node is None: return 0 return node.value + ( self.depth_first_search(node.left) + self.depth_first_search(node.right) ) def __iter__(self) -> Iterator[int]: yield self.depth_first_search(self.tree) if __name__ == "__main__": import doctest doctest.testmod()
""" Sum of all nodes in a binary tree. Python implementation: O(n) time complexity - Recurses through :meth:`depth_first_search` with each element. O(n) space complexity - At any point in time maximum number of stack frames that could be in memory is `n` """ from __future__ import annotations from collections.abc import Iterator class Node: """ A Node has a value variable and pointers to Nodes to its left and right. """ def __init__(self, value: int) -> None: self.value = value self.left: Node | None = None self.right: Node | None = None class BinaryTreeNodeSum: r""" The below tree looks like this 10 / \ 5 -3 / / \ 12 8 0 >>> tree = Node(10) >>> sum(BinaryTreeNodeSum(tree)) 10 >>> tree.left = Node(5) >>> sum(BinaryTreeNodeSum(tree)) 15 >>> tree.right = Node(-3) >>> sum(BinaryTreeNodeSum(tree)) 12 >>> tree.left.left = Node(12) >>> sum(BinaryTreeNodeSum(tree)) 24 >>> tree.right.left = Node(8) >>> tree.right.right = Node(0) >>> sum(BinaryTreeNodeSum(tree)) 32 """ def __init__(self, tree: Node) -> None: self.tree = tree def depth_first_search(self, node: Node | None) -> int: if node is None: return 0 return node.value + ( self.depth_first_search(node.left) + self.depth_first_search(node.right) ) def __iter__(self) -> Iterator[int]: yield self.depth_first_search(self.tree) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
r""" A binary search Tree Example 8 / \ 3 10 / \ \ 1 6 14 / \ / 4 7 13 >>> t = BinarySearchTree() >>> t.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 >>> t.remove(20) Traceback (most recent call last): ... ValueError: Value 20 not found >>> BinarySearchTree().search(6) Traceback (most recent call last): ... IndexError: Warning: Tree is empty! please use another. Other example: >>> 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) {'8': ({'3': (1, {'6': (4, 7)})}, {'10': (None, {'14': (13, None)})})} Test existence >>> t.search(6) is not None True >>> t.search(-1) is not None False >>> t.search(6).is_right True >>> t.search(1).is_right False >>> t.get_max().value 14 >>> t.get_min().value 1 >>> t.empty() False >>> for i in testlist: ... t.remove(i) >>> t.empty() True """ from collections.abc import Iterable from typing import Any class Node: def __init__(self, value: int | None = None): self.value = value self.parent: Node | None = None # Added in order to delete a node easier self.left: Node | None = None self.right: Node | None = None def __repr__(self) -> str: 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) @property def is_right(self) -> bool: return self.parent is not None and self is self.parent.right class BinarySearchTree: def __init__(self, root: Node | None = None): self.root = root def __str__(self) -> str: """ Return a string of all the Nodes using in order traversal """ return str(self.root) def __reassign_nodes(self, node: Node, new_children: Node | None) -> None: if new_children is not None: # reset its kids new_children.parent = node.parent if node.parent is not None: # reset its parent if node.is_right: # If it is the right child node.parent.right = new_children else: node.parent.left = new_children else: self.root = new_children def empty(self) -> bool: return self.root is None def __insert(self, value) -> None: """ Insert a new node in Binary Search Tree with value label """ new_node = Node(value) # 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 if parent_node is None: return 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) -> None: for value in values: self.__insert(value) def search(self, value) -> Node | None: 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: Node | None = None) -> Node | None: """ We go deep on the right branch """ if node is None: if self.root is None: return None node = self.root if not self.empty(): while node.right is not None: node = node.right return node def get_min(self, node: Node | None = None) -> Node | None: """ We go deep on the left branch """ if node is None: node = self.root if self.root is None: return None if not self.empty(): node = self.root while node.left is not None: node = node.left return node def remove(self, value: int) -> None: # Look for the node with that label node = self.search(value) if node is None: msg = f"Value {value} not found" raise ValueError(msg) 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: predecessor = self.get_max( node.left ) # Gets the max value of the left branch self.remove(predecessor.value) # type: ignore node.value = ( predecessor.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure def preorder_traverse(self, node: Node | None) -> Iterable: 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) -> Any: """ 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 | None) -> None: """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[int] = [] self.inorder(arr, node) # append all values to list using inorder traversal return arr[k - 1] def postorder(curr_node: Node | None) -> list[Node]: """ postOrder (left, right, self) """ node_list = [] if curr_node is not None: node_list = postorder(curr_node.left) + postorder(curr_node.right) + [curr_node] return node_list if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
r""" A binary search Tree Example 8 / \ 3 10 / \ \ 1 6 14 / \ / 4 7 13 >>> t = BinarySearchTree() >>> t.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 >>> t.remove(20) Traceback (most recent call last): ... ValueError: Value 20 not found >>> BinarySearchTree().search(6) Traceback (most recent call last): ... IndexError: Warning: Tree is empty! please use another. Other example: >>> 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) {'8': ({'3': (1, {'6': (4, 7)})}, {'10': (None, {'14': (13, None)})})} Test existence >>> t.search(6) is not None True >>> t.search(-1) is not None False >>> t.search(6).is_right True >>> t.search(1).is_right False >>> t.get_max().value 14 >>> t.get_min().value 1 >>> t.empty() False >>> for i in testlist: ... t.remove(i) >>> t.empty() True """ from collections.abc import Iterable from typing import Any class Node: def __init__(self, value: int | None = None): self.value = value self.parent: Node | None = None # Added in order to delete a node easier self.left: Node | None = None self.right: Node | None = None def __repr__(self) -> str: 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) @property def is_right(self) -> bool: return self.parent is not None and self is self.parent.right class BinarySearchTree: def __init__(self, root: Node | None = None): self.root = root def __str__(self) -> str: """ Return a string of all the Nodes using in order traversal """ return str(self.root) def __reassign_nodes(self, node: Node, new_children: Node | None) -> None: if new_children is not None: # reset its kids new_children.parent = node.parent if node.parent is not None: # reset its parent if node.is_right: # If it is the right child node.parent.right = new_children else: node.parent.left = new_children else: self.root = new_children def empty(self) -> bool: return self.root is None def __insert(self, value) -> None: """ Insert a new node in Binary Search Tree with value label """ new_node = Node(value) # 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 if parent_node is None: return 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) -> None: for value in values: self.__insert(value) def search(self, value) -> Node | None: 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: Node | None = None) -> Node | None: """ We go deep on the right branch """ if node is None: if self.root is None: return None node = self.root if not self.empty(): while node.right is not None: node = node.right return node def get_min(self, node: Node | None = None) -> Node | None: """ We go deep on the left branch """ if node is None: node = self.root if self.root is None: return None if not self.empty(): node = self.root while node.left is not None: node = node.left return node def remove(self, value: int) -> None: # Look for the node with that label node = self.search(value) if node is None: msg = f"Value {value} not found" raise ValueError(msg) 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: predecessor = self.get_max( node.left ) # Gets the max value of the left branch self.remove(predecessor.value) # type: ignore node.value = ( predecessor.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure def preorder_traverse(self, node: Node | None) -> Iterable: 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) -> Any: """ 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 | None) -> None: """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[int] = [] self.inorder(arr, node) # append all values to list using inorder traversal return arr[k - 1] def postorder(curr_node: Node | None) -> list[Node]: """ postOrder (left, right, self) """ node_list = [] if curr_node is not None: node_list = postorder(curr_node.left) + postorder(curr_node.right) + [curr_node] return node_list if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar T = TypeVar("T") class LRUCache(Generic[T]): """ Page Replacement Algorithm, Least Recently Used (LRU) Caching. >>> lru_cache: LRUCache[str | int] = LRUCache(4) >>> lru_cache.refer("A") >>> lru_cache.refer(2) >>> lru_cache.refer(3) >>> lru_cache LRUCache(4) => [3, 2, 'A'] >>> lru_cache.refer("A") >>> lru_cache LRUCache(4) => ['A', 3, 2] >>> lru_cache.refer(4) >>> lru_cache.refer(5) >>> lru_cache LRUCache(4) => [5, 4, 'A', 3] """ dq_store: deque[T] # Cache store of keys key_reference: set[T] # References of the keys in cache _MAX_CAPACITY: int = 10 # Maximum capacity of cache def __init__(self, n: int) -> None: """Creates an empty store and map for the keys. The LRUCache is set the size n. """ self.dq_store = deque() self.key_reference = set() if not n: LRUCache._MAX_CAPACITY = sys.maxsize elif n < 0: raise ValueError("n should be an integer greater than 0.") else: LRUCache._MAX_CAPACITY = n def refer(self, x: T) -> None: """ Looks for a page in the cache store and adds reference to the set. Remove the least recently used key if the store is full. Update store to reflect recent access. """ if x not in self.key_reference: if len(self.dq_store) == LRUCache._MAX_CAPACITY: last_element = self.dq_store.pop() self.key_reference.remove(last_element) else: self.dq_store.remove(x) self.dq_store.appendleft(x) self.key_reference.add(x) def display(self) -> None: """ Prints all the elements in the store. """ for k in self.dq_store: print(k) def __repr__(self) -> str: return f"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store)}" if __name__ == "__main__": import doctest doctest.testmod() lru_cache: LRUCache[str | int] = LRUCache(4) lru_cache.refer("A") lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer("A") lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar T = TypeVar("T") class LRUCache(Generic[T]): """ Page Replacement Algorithm, Least Recently Used (LRU) Caching. >>> lru_cache: LRUCache[str | int] = LRUCache(4) >>> lru_cache.refer("A") >>> lru_cache.refer(2) >>> lru_cache.refer(3) >>> lru_cache LRUCache(4) => [3, 2, 'A'] >>> lru_cache.refer("A") >>> lru_cache LRUCache(4) => ['A', 3, 2] >>> lru_cache.refer(4) >>> lru_cache.refer(5) >>> lru_cache LRUCache(4) => [5, 4, 'A', 3] """ dq_store: deque[T] # Cache store of keys key_reference: set[T] # References of the keys in cache _MAX_CAPACITY: int = 10 # Maximum capacity of cache def __init__(self, n: int) -> None: """Creates an empty store and map for the keys. The LRUCache is set the size n. """ self.dq_store = deque() self.key_reference = set() if not n: LRUCache._MAX_CAPACITY = sys.maxsize elif n < 0: raise ValueError("n should be an integer greater than 0.") else: LRUCache._MAX_CAPACITY = n def refer(self, x: T) -> None: """ Looks for a page in the cache store and adds reference to the set. Remove the least recently used key if the store is full. Update store to reflect recent access. """ if x not in self.key_reference: if len(self.dq_store) == LRUCache._MAX_CAPACITY: last_element = self.dq_store.pop() self.key_reference.remove(last_element) else: self.dq_store.remove(x) self.dq_store.appendleft(x) self.key_reference.add(x) def display(self) -> None: """ Prints all the elements in the store. """ for k in self.dq_store: print(k) def __repr__(self) -> str: return f"LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store)}" if __name__ == "__main__": import doctest doctest.testmod() lru_cache: LRUCache[str | int] = LRUCache(4) lru_cache.refer("A") lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer("A") lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from __future__ import annotations from collections.abc import Callable from typing import 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.put(1, 1) >>> cache.put(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.put(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.put(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.put(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 put(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].put(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) # noqa: B010 return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations from collections.abc import Callable from typing import 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.put(1, 1) >>> cache.put(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.put(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.put(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.put(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 put(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].put(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) # noqa: B010 return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Author : Alexander Pantyukhin Date : October 14, 2022 This is an implementation of the up-bottom approach to find edit distance. The implementation was tested on Leetcode: https://leetcode.com/problems/edit-distance/ Levinstein distance Dynamic Programming: up -> down. """ import functools def min_distance_up_bottom(word1: str, word2: str) -> int: """ >>> min_distance_up_bottom("intention", "execution") 5 >>> min_distance_up_bottom("intention", "") 9 >>> min_distance_up_bottom("", "") 0 >>> min_distance_up_bottom("zooicoarchaeologist", "zoologist") 10 """ len_word1 = len(word1) len_word2 = len(word2) @functools.cache def min_distance(index1: int, index2: int) -> int: # if first word index overflows - delete all from the second word if index1 >= len_word1: return len_word2 - index2 # if second word index overflows - delete all from the first word if index2 >= len_word2: return len_word1 - index1 diff = int(word1[index1] != word2[index2]) # current letters not identical return min( 1 + min_distance(index1 + 1, index2), 1 + min_distance(index1, index2 + 1), diff + min_distance(index1 + 1, index2 + 1), ) return min_distance(0, 0) if __name__ == "__main__": import doctest doctest.testmod()
""" Author : Alexander Pantyukhin Date : October 14, 2022 This is an implementation of the up-bottom approach to find edit distance. The implementation was tested on Leetcode: https://leetcode.com/problems/edit-distance/ Levinstein distance Dynamic Programming: up -> down. """ import functools def min_distance_up_bottom(word1: str, word2: str) -> int: """ >>> min_distance_up_bottom("intention", "execution") 5 >>> min_distance_up_bottom("intention", "") 9 >>> min_distance_up_bottom("", "") 0 >>> min_distance_up_bottom("zooicoarchaeologist", "zoologist") 10 """ len_word1 = len(word1) len_word2 = len(word2) @functools.cache def min_distance(index1: int, index2: int) -> int: # if first word index overflows - delete all from the second word if index1 >= len_word1: return len_word2 - index2 # if second word index overflows - delete all from the first word if index2 >= len_word2: return len_word1 - index1 diff = int(word1[index1] != word2[index2]) # current letters not identical return min( 1 + min_distance(index1 + 1, index2), 1 + min_distance(index1, index2 + 1), diff + min_distance(index1 + 1, index2 + 1), ) return min_distance(0, 0) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" 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
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Counting Summations Problem 76: https://projecteuler.net/problem=76 It is possible to write five as a sum in exactly six different ways: 4 + 1 3 + 2 3 + 1 + 1 2 + 2 + 1 2 + 1 + 1 + 1 1 + 1 + 1 + 1 + 1 How many different ways can one hundred be written as a sum of at least two positive integers? """ def solution(m: int = 100) -> int: """ Returns the number of different ways the number m can be written as a sum of at least two positive integers. >>> solution(100) 190569291 >>> solution(50) 204225 >>> solution(30) 5603 >>> solution(10) 41 >>> solution(5) 6 >>> solution(3) 2 >>> solution(2) 1 >>> solution(1) 0 """ memo = [[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: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] - 1 if __name__ == "__main__": print(solution(int(input("Enter a number: ").strip())))
""" Counting Summations Problem 76: https://projecteuler.net/problem=76 It is possible to write five as a sum in exactly six different ways: 4 + 1 3 + 2 3 + 1 + 1 2 + 2 + 1 2 + 1 + 1 + 1 1 + 1 + 1 + 1 + 1 How many different ways can one hundred be written as a sum of at least two positive integers? """ def solution(m: int = 100) -> int: """ Returns the number of different ways the number m can be written as a sum of at least two positive integers. >>> solution(100) 190569291 >>> solution(50) 204225 >>> solution(30) 5603 >>> solution(10) 41 >>> solution(5) 6 >>> solution(3) 2 >>> solution(2) 1 >>> solution(1) 0 """ memo = [[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: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] - 1 if __name__ == "__main__": print(solution(int(input("Enter a number: ").strip())))
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler problem 145: https://projecteuler.net/problem=145 Author: Vineet Rao, Maxim Smolskiy Problem statement: Some positive integers n have the property that the sum [ n + reverse(n) ] consists entirely of odd (decimal) digits. For instance, 36 + 63 = 99 and 409 + 904 = 1313. We will call such numbers reversible; so 36, 63, 409, and 904 are reversible. Leading zeroes are not allowed in either n or reverse(n). There are 120 reversible numbers below one-thousand. How many reversible numbers are there below one-billion (10^9)? """ EVEN_DIGITS = [0, 2, 4, 6, 8] ODD_DIGITS = [1, 3, 5, 7, 9] def slow_reversible_numbers( remaining_length: int, remainder: int, digits: list[int], length: int ) -> int: """ Count the number of reversible numbers of given length. Iterate over possible digits considering parity of current sum remainder. >>> slow_reversible_numbers(1, 0, [0], 1) 0 >>> slow_reversible_numbers(2, 0, [0] * 2, 2) 20 >>> slow_reversible_numbers(3, 0, [0] * 3, 3) 100 """ if remaining_length == 0: if digits[0] == 0 or digits[-1] == 0: return 0 for i in range(length // 2 - 1, -1, -1): remainder += digits[i] + digits[length - i - 1] if remainder % 2 == 0: return 0 remainder //= 10 return 1 if remaining_length == 1: if remainder % 2 == 0: return 0 result = 0 for digit in range(10): digits[length // 2] = digit result += slow_reversible_numbers( 0, (remainder + 2 * digit) // 10, digits, length ) return result result = 0 for digit1 in range(10): digits[(length + remaining_length) // 2 - 1] = digit1 if (remainder + digit1) % 2 == 0: other_parity_digits = ODD_DIGITS else: other_parity_digits = EVEN_DIGITS for digit2 in other_parity_digits: digits[(length - remaining_length) // 2] = digit2 result += slow_reversible_numbers( remaining_length - 2, (remainder + digit1 + digit2) // 10, digits, length, ) return result def slow_solution(max_power: int = 9) -> int: """ To evaluate the solution, use solution() >>> slow_solution(3) 120 >>> slow_solution(6) 18720 >>> slow_solution(7) 68720 """ result = 0 for length in range(1, max_power + 1): result += slow_reversible_numbers(length, 0, [0] * length, length) return result def reversible_numbers( remaining_length: int, remainder: int, digits: list[int], length: int ) -> int: """ Count the number of reversible numbers of given length. Iterate over possible digits considering parity of current sum remainder. >>> reversible_numbers(1, 0, [0], 1) 0 >>> reversible_numbers(2, 0, [0] * 2, 2) 20 >>> reversible_numbers(3, 0, [0] * 3, 3) 100 """ # There exist no reversible 1, 5, 9, 13 (ie. 4k+1) digit numbers if (length - 1) % 4 == 0: return 0 return slow_reversible_numbers(length, 0, [0] * length, length) def solution(max_power: int = 9) -> int: """ To evaluate the solution, use solution() >>> solution(3) 120 >>> solution(6) 18720 >>> solution(7) 68720 """ result = 0 for length in range(1, max_power + 1): result += reversible_numbers(length, 0, [0] * length, length) return result def benchmark() -> None: """ Benchmarks """ # Running performance benchmarks... # slow_solution : 292.9300301000003 # solution : 54.90970860000016 from timeit import timeit print("Running performance benchmarks...") print(f"slow_solution : {timeit('slow_solution()', globals=globals(), number=10)}") print(f"solution : {timeit('solution()', globals=globals(), number=10)}") if __name__ == "__main__": print(f"Solution : {solution()}") benchmark() # for i in range(1, 15): # print(f"{i}. {reversible_numbers(i, 0, [0]*i, i)}")
""" Project Euler problem 145: https://projecteuler.net/problem=145 Author: Vineet Rao, Maxim Smolskiy Problem statement: Some positive integers n have the property that the sum [ n + reverse(n) ] consists entirely of odd (decimal) digits. For instance, 36 + 63 = 99 and 409 + 904 = 1313. We will call such numbers reversible; so 36, 63, 409, and 904 are reversible. Leading zeroes are not allowed in either n or reverse(n). There are 120 reversible numbers below one-thousand. How many reversible numbers are there below one-billion (10^9)? """ EVEN_DIGITS = [0, 2, 4, 6, 8] ODD_DIGITS = [1, 3, 5, 7, 9] def slow_reversible_numbers( remaining_length: int, remainder: int, digits: list[int], length: int ) -> int: """ Count the number of reversible numbers of given length. Iterate over possible digits considering parity of current sum remainder. >>> slow_reversible_numbers(1, 0, [0], 1) 0 >>> slow_reversible_numbers(2, 0, [0] * 2, 2) 20 >>> slow_reversible_numbers(3, 0, [0] * 3, 3) 100 """ if remaining_length == 0: if digits[0] == 0 or digits[-1] == 0: return 0 for i in range(length // 2 - 1, -1, -1): remainder += digits[i] + digits[length - i - 1] if remainder % 2 == 0: return 0 remainder //= 10 return 1 if remaining_length == 1: if remainder % 2 == 0: return 0 result = 0 for digit in range(10): digits[length // 2] = digit result += slow_reversible_numbers( 0, (remainder + 2 * digit) // 10, digits, length ) return result result = 0 for digit1 in range(10): digits[(length + remaining_length) // 2 - 1] = digit1 if (remainder + digit1) % 2 == 0: other_parity_digits = ODD_DIGITS else: other_parity_digits = EVEN_DIGITS for digit2 in other_parity_digits: digits[(length - remaining_length) // 2] = digit2 result += slow_reversible_numbers( remaining_length - 2, (remainder + digit1 + digit2) // 10, digits, length, ) return result def slow_solution(max_power: int = 9) -> int: """ To evaluate the solution, use solution() >>> slow_solution(3) 120 >>> slow_solution(6) 18720 >>> slow_solution(7) 68720 """ result = 0 for length in range(1, max_power + 1): result += slow_reversible_numbers(length, 0, [0] * length, length) return result def reversible_numbers( remaining_length: int, remainder: int, digits: list[int], length: int ) -> int: """ Count the number of reversible numbers of given length. Iterate over possible digits considering parity of current sum remainder. >>> reversible_numbers(1, 0, [0], 1) 0 >>> reversible_numbers(2, 0, [0] * 2, 2) 20 >>> reversible_numbers(3, 0, [0] * 3, 3) 100 """ # There exist no reversible 1, 5, 9, 13 (ie. 4k+1) digit numbers if (length - 1) % 4 == 0: return 0 return slow_reversible_numbers(length, 0, [0] * length, length) def solution(max_power: int = 9) -> int: """ To evaluate the solution, use solution() >>> solution(3) 120 >>> solution(6) 18720 >>> solution(7) 68720 """ result = 0 for length in range(1, max_power + 1): result += reversible_numbers(length, 0, [0] * length, length) return result def benchmark() -> None: """ Benchmarks """ # Running performance benchmarks... # slow_solution : 292.9300301000003 # solution : 54.90970860000016 from timeit import timeit print("Running performance benchmarks...") print(f"slow_solution : {timeit('slow_solution()', globals=globals(), number=10)}") print(f"solution : {timeit('solution()', globals=globals(), number=10)}") if __name__ == "__main__": print(f"Solution : {solution()}") benchmark() # for i in range(1, 15): # print(f"{i}. {reversible_numbers(i, 0, [0]*i, i)}")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Sieve of Eratosthenes Input: n = 10 Output: 2 3 5 7 Input: n = 20 Output: 2 3 5 7 11 13 17 19 you can read in detail about this at https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes """ def prime_sieve_eratosthenes(num: int) -> list[int]: """ Print the prime numbers up to n >>> prime_sieve_eratosthenes(10) [2, 3, 5, 7] >>> prime_sieve_eratosthenes(20) [2, 3, 5, 7, 11, 13, 17, 19] >>> prime_sieve_eratosthenes(2) [2] >>> prime_sieve_eratosthenes(1) [] >>> prime_sieve_eratosthenes(-1) Traceback (most recent call last): ... ValueError: Input must be a positive integer """ if num <= 0: raise ValueError("Input must be a positive integer") primes = [True] * (num + 1) p = 2 while p * p <= num: if primes[p]: for i in range(p * p, num + 1, p): primes[i] = False p += 1 return [prime for prime in range(2, num + 1) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() user_num = int(input("Enter a positive integer: ").strip()) print(prime_sieve_eratosthenes(user_num))
""" Sieve of Eratosthenes Input: n = 10 Output: 2 3 5 7 Input: n = 20 Output: 2 3 5 7 11 13 17 19 you can read in detail about this at https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes """ def prime_sieve_eratosthenes(num: int) -> list[int]: """ Print the prime numbers up to n >>> prime_sieve_eratosthenes(10) [2, 3, 5, 7] >>> prime_sieve_eratosthenes(20) [2, 3, 5, 7, 11, 13, 17, 19] >>> prime_sieve_eratosthenes(2) [2] >>> prime_sieve_eratosthenes(1) [] >>> prime_sieve_eratosthenes(-1) Traceback (most recent call last): ... ValueError: Input must be a positive integer """ if num <= 0: raise ValueError("Input must be a positive integer") primes = [True] * (num + 1) p = 2 while p * p <= num: if primes[p]: for i in range(p * p, num + 1, p): primes[i] = False p += 1 return [prime for prime in range(2, num + 1) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() user_num = int(input("Enter a positive integer: ").strip()) print(prime_sieve_eratosthenes(user_num))
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# 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 msg = f"Open Kight Tour cannot be performed on a board of size {n}" raise ValueError(msg) 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 msg = f"Open Kight Tour cannot be performed on a board of size {n}" raise ValueError(msg) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Given an matrix of numbers in which all rows and all columns are sorted in decreasing order, return the number of negative numbers in grid. Reference: https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix """ def generate_large_matrix() -> list[list[int]]: """ >>> generate_large_matrix() # doctest: +ELLIPSIS [[1000, ..., -999], [999, ..., -1001], ..., [2, ..., -1998]] """ return [list(range(1000 - i, -1000 - i, -1)) for i in range(1000)] grid = generate_large_matrix() test_grids = ( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[3, 2], [1, 0]], [[7, 7, 6]], [[7, 7, 6], [-1, -2, -3]], grid, ) def validate_grid(grid: list[list[int]]) -> None: """ Validate that the rows and columns of the grid is sorted in decreasing order. >>> for grid in test_grids: ... validate_grid(grid) """ assert all(row == sorted(row, reverse=True) for row in grid) assert all(list(col) == sorted(col, reverse=True) for col in zip(*grid)) def find_negative_index(array: list[int]) -> int: """ Find the smallest negative index >>> find_negative_index([0,0,0,0]) 4 >>> find_negative_index([4,3,2,-1]) 3 >>> find_negative_index([1,0,-1,-10]) 2 >>> find_negative_index([0,0,0,-1]) 3 >>> find_negative_index([11,8,7,-3,-5,-9]) 3 >>> find_negative_index([-1,-1,-2,-3]) 0 >>> find_negative_index([5,1,0]) 3 >>> find_negative_index([-5,-5,-5]) 0 >>> find_negative_index([0]) 1 >>> find_negative_index([]) 0 """ left = 0 right = len(array) - 1 # Edge cases such as no values or all numbers are negative. if not array or array[0] < 0: return 0 while right + 1 > left: mid = (left + right) // 2 num = array[mid] # Num must be negative and the index must be greater than or equal to 0. if num < 0 and array[mid - 1] >= 0: return mid if num >= 0: left = mid + 1 else: right = mid - 1 # No negative numbers so return the last index of the array + 1 which is the length. return len(array) def count_negatives_binary_search(grid: list[list[int]]) -> int: """ An O(m logn) solution that uses binary search in order to find the boundary between positive and negative numbers >>> [count_negatives_binary_search(grid) for grid in test_grids] [8, 0, 0, 3, 1498500] """ total = 0 bound = len(grid[0]) for i in range(len(grid)): bound = find_negative_index(grid[i][:bound]) total += bound return (len(grid) * len(grid[0])) - total def count_negatives_brute_force(grid: list[list[int]]) -> int: """ This solution is O(n^2) because it iterates through every column and row. >>> [count_negatives_brute_force(grid) for grid in test_grids] [8, 0, 0, 3, 1498500] """ return len([number for row in grid for number in row if number < 0]) def count_negatives_brute_force_with_break(grid: list[list[int]]) -> int: """ Similar to the brute force solution above but uses break in order to reduce the number of iterations. >>> [count_negatives_brute_force_with_break(grid) for grid in test_grids] [8, 0, 0, 3, 1498500] """ total = 0 for row in grid: for i, number in enumerate(row): if number < 0: total += len(row) - i break return total def benchmark() -> None: """Benchmark our functions next to each other""" from timeit import timeit print("Running benchmarks") setup = ( "from __main__ import count_negatives_binary_search, " "count_negatives_brute_force, count_negatives_brute_force_with_break, grid" ) for func in ( "count_negatives_binary_search", # took 0.7727 seconds "count_negatives_brute_force_with_break", # took 4.6505 seconds "count_negatives_brute_force", # took 12.8160 seconds ): time = timeit(f"{func}(grid=grid)", setup=setup, number=500) print(f"{func}() took {time:0.4f} seconds") if __name__ == "__main__": import doctest doctest.testmod() benchmark()
""" Given an matrix of numbers in which all rows and all columns are sorted in decreasing order, return the number of negative numbers in grid. Reference: https://leetcode.com/problems/count-negative-numbers-in-a-sorted-matrix """ def generate_large_matrix() -> list[list[int]]: """ >>> generate_large_matrix() # doctest: +ELLIPSIS [[1000, ..., -999], [999, ..., -1001], ..., [2, ..., -1998]] """ return [list(range(1000 - i, -1000 - i, -1)) for i in range(1000)] grid = generate_large_matrix() test_grids = ( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[3, 2], [1, 0]], [[7, 7, 6]], [[7, 7, 6], [-1, -2, -3]], grid, ) def validate_grid(grid: list[list[int]]) -> None: """ Validate that the rows and columns of the grid is sorted in decreasing order. >>> for grid in test_grids: ... validate_grid(grid) """ assert all(row == sorted(row, reverse=True) for row in grid) assert all(list(col) == sorted(col, reverse=True) for col in zip(*grid)) def find_negative_index(array: list[int]) -> int: """ Find the smallest negative index >>> find_negative_index([0,0,0,0]) 4 >>> find_negative_index([4,3,2,-1]) 3 >>> find_negative_index([1,0,-1,-10]) 2 >>> find_negative_index([0,0,0,-1]) 3 >>> find_negative_index([11,8,7,-3,-5,-9]) 3 >>> find_negative_index([-1,-1,-2,-3]) 0 >>> find_negative_index([5,1,0]) 3 >>> find_negative_index([-5,-5,-5]) 0 >>> find_negative_index([0]) 1 >>> find_negative_index([]) 0 """ left = 0 right = len(array) - 1 # Edge cases such as no values or all numbers are negative. if not array or array[0] < 0: return 0 while right + 1 > left: mid = (left + right) // 2 num = array[mid] # Num must be negative and the index must be greater than or equal to 0. if num < 0 and array[mid - 1] >= 0: return mid if num >= 0: left = mid + 1 else: right = mid - 1 # No negative numbers so return the last index of the array + 1 which is the length. return len(array) def count_negatives_binary_search(grid: list[list[int]]) -> int: """ An O(m logn) solution that uses binary search in order to find the boundary between positive and negative numbers >>> [count_negatives_binary_search(grid) for grid in test_grids] [8, 0, 0, 3, 1498500] """ total = 0 bound = len(grid[0]) for i in range(len(grid)): bound = find_negative_index(grid[i][:bound]) total += bound return (len(grid) * len(grid[0])) - total def count_negatives_brute_force(grid: list[list[int]]) -> int: """ This solution is O(n^2) because it iterates through every column and row. >>> [count_negatives_brute_force(grid) for grid in test_grids] [8, 0, 0, 3, 1498500] """ return len([number for row in grid for number in row if number < 0]) def count_negatives_brute_force_with_break(grid: list[list[int]]) -> int: """ Similar to the brute force solution above but uses break in order to reduce the number of iterations. >>> [count_negatives_brute_force_with_break(grid) for grid in test_grids] [8, 0, 0, 3, 1498500] """ total = 0 for row in grid: for i, number in enumerate(row): if number < 0: total += len(row) - i break return total def benchmark() -> None: """Benchmark our functions next to each other""" from timeit import timeit print("Running benchmarks") setup = ( "from __main__ import count_negatives_binary_search, " "count_negatives_brute_force, count_negatives_brute_force_with_break, grid" ) for func in ( "count_negatives_binary_search", # took 0.7727 seconds "count_negatives_brute_force_with_break", # took 4.6505 seconds "count_negatives_brute_force", # took 12.8160 seconds ): time = timeit(f"{func}(grid=grid)", setup=setup, number=500) print(f"{func}() took {time:0.4f} seconds") if __name__ == "__main__": import doctest doctest.testmod() benchmark()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
"""Queue implementation using two stacks""" from collections.abc import Iterable from typing import Generic, TypeVar _T = TypeVar("_T") class QueueByTwoStacks(Generic[_T]): def __init__(self, iterable: Iterable[_T] | None = None) -> None: """ >>> QueueByTwoStacks() Queue(()) >>> QueueByTwoStacks([10, 20, 30]) Queue((10, 20, 30)) >>> QueueByTwoStacks((i**2 for i in range(1, 4))) Queue((1, 4, 9)) """ self._stack1: list[_T] = list(iterable or []) self._stack2: list[_T] = [] def __len__(self) -> int: """ >>> len(QueueByTwoStacks()) 0 >>> from string import ascii_lowercase >>> len(QueueByTwoStacks(ascii_lowercase)) 26 >>> queue = QueueByTwoStacks() >>> for i in range(1, 11): ... queue.put(i) ... >>> len(queue) 10 >>> for i in range(2): ... queue.get() 1 2 >>> len(queue) 8 """ return len(self._stack1) + len(self._stack2) def __repr__(self) -> str: """ >>> queue = QueueByTwoStacks() >>> queue Queue(()) >>> str(queue) 'Queue(())' >>> queue.put(10) >>> queue Queue((10,)) >>> queue.put(20) >>> queue.put(30) >>> queue Queue((10, 20, 30)) """ return f"Queue({tuple(self._stack2[::-1] + self._stack1)})" def put(self, item: _T) -> None: """ Put `item` into the Queue >>> queue = QueueByTwoStacks() >>> queue.put(10) >>> queue.put(20) >>> len(queue) 2 >>> queue Queue((10, 20)) """ self._stack1.append(item) def get(self) -> _T: """ Get `item` from the Queue >>> queue = QueueByTwoStacks((10, 20, 30)) >>> queue.get() 10 >>> queue.put(40) >>> queue.get() 20 >>> queue.get() 30 >>> len(queue) 1 >>> queue.get() 40 >>> queue.get() Traceback (most recent call last): ... IndexError: Queue is empty """ # To reduce number of attribute look-ups in `while` loop. stack1_pop = self._stack1.pop stack2_append = self._stack2.append if not self._stack2: while self._stack1: stack2_append(stack1_pop()) if not self._stack2: raise IndexError("Queue is empty") return self._stack2.pop() if __name__ == "__main__": from doctest import testmod testmod()
"""Queue implementation using two stacks""" from collections.abc import Iterable from typing import Generic, TypeVar _T = TypeVar("_T") class QueueByTwoStacks(Generic[_T]): def __init__(self, iterable: Iterable[_T] | None = None) -> None: """ >>> QueueByTwoStacks() Queue(()) >>> QueueByTwoStacks([10, 20, 30]) Queue((10, 20, 30)) >>> QueueByTwoStacks((i**2 for i in range(1, 4))) Queue((1, 4, 9)) """ self._stack1: list[_T] = list(iterable or []) self._stack2: list[_T] = [] def __len__(self) -> int: """ >>> len(QueueByTwoStacks()) 0 >>> from string import ascii_lowercase >>> len(QueueByTwoStacks(ascii_lowercase)) 26 >>> queue = QueueByTwoStacks() >>> for i in range(1, 11): ... queue.put(i) ... >>> len(queue) 10 >>> for i in range(2): ... queue.get() 1 2 >>> len(queue) 8 """ return len(self._stack1) + len(self._stack2) def __repr__(self) -> str: """ >>> queue = QueueByTwoStacks() >>> queue Queue(()) >>> str(queue) 'Queue(())' >>> queue.put(10) >>> queue Queue((10,)) >>> queue.put(20) >>> queue.put(30) >>> queue Queue((10, 20, 30)) """ return f"Queue({tuple(self._stack2[::-1] + self._stack1)})" def put(self, item: _T) -> None: """ Put `item` into the Queue >>> queue = QueueByTwoStacks() >>> queue.put(10) >>> queue.put(20) >>> len(queue) 2 >>> queue Queue((10, 20)) """ self._stack1.append(item) def get(self) -> _T: """ Get `item` from the Queue >>> queue = QueueByTwoStacks((10, 20, 30)) >>> queue.get() 10 >>> queue.put(40) >>> queue.get() 20 >>> queue.get() 30 >>> len(queue) 1 >>> queue.get() 40 >>> queue.get() Traceback (most recent call last): ... IndexError: Queue is empty """ # To reduce number of attribute look-ups in `while` loop. stack1_pop = self._stack1.pop stack2_append = self._stack2.append if not self._stack2: while self._stack1: stack2_append(stack1_pop()) if not self._stack2: raise IndexError("Queue is empty") return self._stack2.pop() if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" 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 str_eval(s: str) -> int: """ Returns product of digits in given string n >>> str_eval("987654321") 362880 >>> str_eval("22222222") 256 """ product = 1 for digit in s: product *= int(digit) return product 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. """ largest_product = -sys.maxsize - 1 substr = n[:13] cur_index = 13 while cur_index < len(n) - 13: if int(n[cur_index]) >= int(substr[0]): substr = substr[1:] + n[cur_index] cur_index += 1 else: largest_product = max(largest_product, str_eval(substr)) substr = n[cur_index : cur_index + 13] cur_index += 13 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 str_eval(s: str) -> int: """ Returns product of digits in given string n >>> str_eval("987654321") 362880 >>> str_eval("22222222") 256 """ product = 1 for digit in s: product *= int(digit) return product 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. """ largest_product = -sys.maxsize - 1 substr = n[:13] cur_index = 13 while cur_index < len(n) - 13: if int(n[cur_index]) >= int(substr[0]): substr = substr[1:] + n[cur_index] cur_index += 1 else: largest_product = max(largest_product, str_eval(substr)) substr = n[cur_index : cur_index + 13] cur_index += 13 return largest_product if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" In laser physics, a "white cell" is a mirror system that acts as a delay line for the laser beam. The beam enters the cell, bounces around on the mirrors, and eventually works its way back out. The specific white cell we will be considering is an ellipse with the equation 4x^2 + y^2 = 100 The section corresponding to −0.01 ≤ x ≤ +0.01 at the top is missing, allowing the light to enter and exit through the hole.  The light beam in this problem starts at the point (0.0,10.1) just outside the white cell, and the beam first impacts the mirror at (1.4,-9.6). Each time the laser beam hits the surface of the ellipse, it follows the usual law of reflection "angle of incidence equals angle of reflection." That is, both the incident and reflected beams make the same angle with the normal line at the point of incidence. In the figure on the left, the red line shows the first two points of contact between the laser beam and the wall of the white cell; the blue line shows the line tangent to the ellipse at the point of incidence of the first bounce. The slope m of the tangent line at any point (x,y) of the given ellipse is: m = −4x/y The normal line is perpendicular to this tangent line at the point of incidence. The animation on the right shows the first 10 reflections of the beam. How many times does the beam hit the internal surface of the white cell before exiting? """ from math import isclose, sqrt def next_point( point_x: float, point_y: float, incoming_gradient: float ) -> tuple[float, float, float]: """ Given that a laser beam hits the interior of the white cell at point (point_x, point_y) with gradient incoming_gradient, return a tuple (x,y,m1) where the next point of contact with the interior is (x,y) with gradient m1. >>> next_point(5.0, 0.0, 0.0) (-5.0, 0.0, 0.0) >>> next_point(5.0, 0.0, -2.0) (0.0, -10.0, 2.0) """ # normal_gradient = gradient of line through which the beam is reflected # outgoing_gradient = gradient of reflected line normal_gradient = point_y / 4 / point_x s2 = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) c2 = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) outgoing_gradient = (s2 - c2 * incoming_gradient) / (c2 + s2 * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 quadratic_term = outgoing_gradient**2 + 4 linear_term = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) constant_term = (point_y - outgoing_gradient * point_x) ** 2 - 100 x_minus = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term) ) / (2 * quadratic_term) x_plus = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term) ) / (2 * quadratic_term) # two solutions, one of which is our input point next_x = x_minus if isclose(x_plus, point_x) else x_plus next_y = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def solution(first_x_coord: float = 1.4, first_y_coord: float = -9.6) -> int: """ Return the number of times that the beam hits the interior wall of the cell before exiting. >>> solution(0.00001,-10) 1 >>> solution(5, 0) 287 """ num_reflections: int = 0 point_x: float = first_x_coord point_y: float = first_y_coord gradient: float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): point_x, point_y, gradient = next_point(point_x, point_y, gradient) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f"{solution() = }")
""" In laser physics, a "white cell" is a mirror system that acts as a delay line for the laser beam. The beam enters the cell, bounces around on the mirrors, and eventually works its way back out. The specific white cell we will be considering is an ellipse with the equation 4x^2 + y^2 = 100 The section corresponding to −0.01 ≤ x ≤ +0.01 at the top is missing, allowing the light to enter and exit through the hole.  The light beam in this problem starts at the point (0.0,10.1) just outside the white cell, and the beam first impacts the mirror at (1.4,-9.6). Each time the laser beam hits the surface of the ellipse, it follows the usual law of reflection "angle of incidence equals angle of reflection." That is, both the incident and reflected beams make the same angle with the normal line at the point of incidence. In the figure on the left, the red line shows the first two points of contact between the laser beam and the wall of the white cell; the blue line shows the line tangent to the ellipse at the point of incidence of the first bounce. The slope m of the tangent line at any point (x,y) of the given ellipse is: m = −4x/y The normal line is perpendicular to this tangent line at the point of incidence. The animation on the right shows the first 10 reflections of the beam. How many times does the beam hit the internal surface of the white cell before exiting? """ from math import isclose, sqrt def next_point( point_x: float, point_y: float, incoming_gradient: float ) -> tuple[float, float, float]: """ Given that a laser beam hits the interior of the white cell at point (point_x, point_y) with gradient incoming_gradient, return a tuple (x,y,m1) where the next point of contact with the interior is (x,y) with gradient m1. >>> next_point(5.0, 0.0, 0.0) (-5.0, 0.0, 0.0) >>> next_point(5.0, 0.0, -2.0) (0.0, -10.0, 2.0) """ # normal_gradient = gradient of line through which the beam is reflected # outgoing_gradient = gradient of reflected line normal_gradient = point_y / 4 / point_x s2 = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) c2 = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) outgoing_gradient = (s2 - c2 * incoming_gradient) / (c2 + s2 * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 quadratic_term = outgoing_gradient**2 + 4 linear_term = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) constant_term = (point_y - outgoing_gradient * point_x) ** 2 - 100 x_minus = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term) ) / (2 * quadratic_term) x_plus = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term) ) / (2 * quadratic_term) # two solutions, one of which is our input point next_x = x_minus if isclose(x_plus, point_x) else x_plus next_y = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def solution(first_x_coord: float = 1.4, first_y_coord: float = -9.6) -> int: """ Return the number of times that the beam hits the interior wall of the cell before exiting. >>> solution(0.00001,-10) 1 >>> solution(5, 0) 287 """ num_reflections: int = 0 point_x: float = first_x_coord point_y: float = first_y_coord gradient: float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): point_x, point_y, gradient = next_point(point_x, point_y, gradient) num_reflections += 1 return num_reflections if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 9: https://projecteuler.net/problem=9 Special Pythagorean triplet A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product a*b*c. References: - https://en.wikipedia.org/wiki/Pythagorean_triple """ def solution() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a**2 + b**2 = c**2 2. a + b + c = 1000 >>> solution() 31875000 """ return next( iter( [ a * b * (1000 - a - b) for a in range(1, 999) for b in range(a, 999) if (a * a + b * b == (1000 - a - b) ** 2) ] ) ) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 9: https://projecteuler.net/problem=9 Special Pythagorean triplet A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product a*b*c. References: - https://en.wikipedia.org/wiki/Pythagorean_triple """ def solution() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a**2 + b**2 = c**2 2. a + b + c = 1000 >>> solution() 31875000 """ return next( iter( [ a * b * (1000 - a - b) for a in range(1, 999) for b in range(a, 999) if (a * a + b * b == (1000 - a - b) ** 2) ] ) ) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Task: There are n gas stations along a circular route, where the amount of gas at the ith station is gas_quantities[i]. You have a car with an unlimited gas tank and it costs costs[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays gas_quantities and costs, return the starting gas station's index if you can travel around the circuit once in the clockwise direction otherwise, return -1. If there exists a solution, it is guaranteed to be unique Reference: https://leetcode.com/problems/gas-station/description Implementation notes: First, check whether the total gas is enough to complete the journey. If not, return -1. However, if there is enough gas, it is guaranteed that there is a valid starting index to reach the end of the journey. Greedily calculate the net gain (gas_quantity - cost) at each station. If the net gain ever goes below 0 while iterating through the stations, start checking from the next station. """ from dataclasses import dataclass @dataclass class GasStation: gas_quantity: int cost: int def get_gas_stations( gas_quantities: list[int], costs: list[int] ) -> tuple[GasStation, ...]: """ This function returns a tuple of gas stations. Args: gas_quantities: Amount of gas available at each station costs: The cost of gas required to move from one station to the next Returns: A tuple of gas stations >>> gas_stations = get_gas_stations([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]) >>> len(gas_stations) 5 >>> gas_stations[0] GasStation(gas_quantity=1, cost=3) >>> gas_stations[-1] GasStation(gas_quantity=5, cost=2) """ return tuple( GasStation(quantity, cost) for quantity, cost in zip(gas_quantities, costs) ) def can_complete_journey(gas_stations: tuple[GasStation, ...]) -> int: """ This function returns the index from which to start the journey in order to reach the end. Args: gas_quantities [list]: Amount of gas available at each station cost [list]: The cost of gas required to move from one station to the next Returns: start [int]: start index needed to complete the journey Examples: >>> can_complete_journey(get_gas_stations([1, 2, 3, 4, 5], [3, 4, 5, 1, 2])) 3 >>> can_complete_journey(get_gas_stations([2, 3, 4], [3, 4, 3])) -1 """ total_gas = sum(gas_station.gas_quantity for gas_station in gas_stations) total_cost = sum(gas_station.cost for gas_station in gas_stations) if total_gas < total_cost: return -1 start = 0 net = 0 for i, gas_station in enumerate(gas_stations): net += gas_station.gas_quantity - gas_station.cost if net < 0: start = i + 1 net = 0 return start if __name__ == "__main__": import doctest doctest.testmod()
""" Task: There are n gas stations along a circular route, where the amount of gas at the ith station is gas_quantities[i]. You have a car with an unlimited gas tank and it costs costs[i] of gas to travel from the ith station to its next (i + 1)th station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays gas_quantities and costs, return the starting gas station's index if you can travel around the circuit once in the clockwise direction otherwise, return -1. If there exists a solution, it is guaranteed to be unique Reference: https://leetcode.com/problems/gas-station/description Implementation notes: First, check whether the total gas is enough to complete the journey. If not, return -1. However, if there is enough gas, it is guaranteed that there is a valid starting index to reach the end of the journey. Greedily calculate the net gain (gas_quantity - cost) at each station. If the net gain ever goes below 0 while iterating through the stations, start checking from the next station. """ from dataclasses import dataclass @dataclass class GasStation: gas_quantity: int cost: int def get_gas_stations( gas_quantities: list[int], costs: list[int] ) -> tuple[GasStation, ...]: """ This function returns a tuple of gas stations. Args: gas_quantities: Amount of gas available at each station costs: The cost of gas required to move from one station to the next Returns: A tuple of gas stations >>> gas_stations = get_gas_stations([1, 2, 3, 4, 5], [3, 4, 5, 1, 2]) >>> len(gas_stations) 5 >>> gas_stations[0] GasStation(gas_quantity=1, cost=3) >>> gas_stations[-1] GasStation(gas_quantity=5, cost=2) """ return tuple( GasStation(quantity, cost) for quantity, cost in zip(gas_quantities, costs) ) def can_complete_journey(gas_stations: tuple[GasStation, ...]) -> int: """ This function returns the index from which to start the journey in order to reach the end. Args: gas_quantities [list]: Amount of gas available at each station cost [list]: The cost of gas required to move from one station to the next Returns: start [int]: start index needed to complete the journey Examples: >>> can_complete_journey(get_gas_stations([1, 2, 3, 4, 5], [3, 4, 5, 1, 2])) 3 >>> can_complete_journey(get_gas_stations([2, 3, 4], [3, 4, 3])) -1 """ total_gas = sum(gas_station.gas_quantity for gas_station in gas_stations) total_cost = sum(gas_station.cost for gas_station in gas_stations) if total_gas < total_cost: return -1 start = 0 net = 0 for i, gas_station in enumerate(gas_stations): net += gas_station.gas_quantity - gas_station.cost if net < 0: start = i + 1 net = 0 return start if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Problem 72 Counting fractions: https://projecteuler.net/problem=72 Description: Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that there are 21 elements in this set. How many elements would be contained in the set of reduced proper fractions for d ≤ 1,000,000? Solution: Number of numbers between 1 and n that are coprime to n is given by the Euler's Totient function, phi(n). So, the answer is simply the sum of phi(n) for 2 <= n <= 1,000,000 Sum of phi(d), for all d|n = n. This result can be used to find phi(n) using a sieve. Time: 1 sec """ import numpy as np def solution(limit: int = 1_000_000) -> int: """ Returns an integer, the solution to the problem >>> solution(10) 31 >>> solution(100) 3043 >>> solution(1_000) 304191 """ # generating an array from -1 to limit phi = np.arange(-1, limit) for i in range(2, limit + 1): if phi[i] == i - 1: ind = np.arange(2 * i, limit + 1, i) # indexes for selection phi[ind] -= phi[ind] // i return np.sum(phi[2 : limit + 1]) if __name__ == "__main__": print(solution())
""" Problem 72 Counting fractions: https://projecteuler.net/problem=72 Description: Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that there are 21 elements in this set. How many elements would be contained in the set of reduced proper fractions for d ≤ 1,000,000? Solution: Number of numbers between 1 and n that are coprime to n is given by the Euler's Totient function, phi(n). So, the answer is simply the sum of phi(n) for 2 <= n <= 1,000,000 Sum of phi(d), for all d|n = n. This result can be used to find phi(n) using a sieve. Time: 1 sec """ import numpy as np def solution(limit: int = 1_000_000) -> int: """ Returns an integer, the solution to the problem >>> solution(10) 31 >>> solution(100) 3043 >>> solution(1_000) 304191 """ # generating an array from -1 to limit phi = np.arange(-1, limit) for i in range(2, limit + 1): if phi[i] == i - 1: ind = np.arange(2 * i, limit + 1, i) # indexes for selection phi[ind] -= phi[ind] // i return np.sum(phi[2 : limit + 1]) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Program to check if a cycle is present in a given graph """ def check_cycle(graph: dict) -> bool: """ Returns True if graph is cyclic else False >>> check_cycle(graph={0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]}) False >>> check_cycle(graph={0:[1, 2], 1:[2], 2:[0, 3], 3:[3]}) True """ # Keep track of visited nodes visited: set[int] = set() # To detect a back edge, keep track of vertices currently in the recursion stack rec_stk: set[int] = set() return any( node not in visited and depth_first_search(graph, node, visited, rec_stk) for node in graph ) def depth_first_search(graph: dict, vertex: int, visited: set, rec_stk: set) -> bool: """ Recur for all neighbours. If any neighbour is visited and in rec_stk then graph is cyclic. >>> graph = {0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]} >>> vertex, visited, rec_stk = 0, set(), set() >>> depth_first_search(graph, vertex, visited, rec_stk) False """ # Mark current node as visited and add to recursion stack visited.add(vertex) rec_stk.add(vertex) for node in graph[vertex]: if node not in visited: if depth_first_search(graph, node, visited, rec_stk): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(vertex) return False if __name__ == "__main__": from doctest import testmod testmod()
""" Program to check if a cycle is present in a given graph """ def check_cycle(graph: dict) -> bool: """ Returns True if graph is cyclic else False >>> check_cycle(graph={0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]}) False >>> check_cycle(graph={0:[1, 2], 1:[2], 2:[0, 3], 3:[3]}) True """ # Keep track of visited nodes visited: set[int] = set() # To detect a back edge, keep track of vertices currently in the recursion stack rec_stk: set[int] = set() return any( node not in visited and depth_first_search(graph, node, visited, rec_stk) for node in graph ) def depth_first_search(graph: dict, vertex: int, visited: set, rec_stk: set) -> bool: """ Recur for all neighbours. If any neighbour is visited and in rec_stk then graph is cyclic. >>> graph = {0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]} >>> vertex, visited, rec_stk = 0, set(), set() >>> depth_first_search(graph, vertex, visited, rec_stk) False """ # Mark current node as visited and add to recursion stack visited.add(vertex) rec_stk.add(vertex) for node in graph[vertex]: if node not in visited: if depth_first_search(graph, node, visited, rec_stk): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(vertex) return False if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" 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 """ result = 0 for i in range(n): if i % 3 == 0 or i % 5 == 0: result += i return result 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 """ result = 0 for i in range(n): if i % 3 == 0 or i % 5 == 0: result += i return result if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Reference: https://en.wikipedia.org/wiki/Gaussian_function """ from numpy import exp, pi, sqrt def gaussian(x, mu: float = 0.0, sigma: float = 1.0) -> int: """ >>> gaussian(1) 0.24197072451914337 >>> gaussian(24) 3.342714441794458e-126 >>> gaussian(1, 4, 2) 0.06475879783294587 >>> gaussian(1, 5, 3) 0.05467002489199788 Supports NumPy Arrays Use numpy.meshgrid with this to generate gaussian blur on images. >>> import numpy as np >>> x = np.arange(15) >>> gaussian(x) array([3.98942280e-01, 2.41970725e-01, 5.39909665e-02, 4.43184841e-03, 1.33830226e-04, 1.48671951e-06, 6.07588285e-09, 9.13472041e-12, 5.05227108e-15, 1.02797736e-18, 7.69459863e-23, 2.11881925e-27, 2.14638374e-32, 7.99882776e-38, 1.09660656e-43]) >>> gaussian(15) 5.530709549844416e-50 >>> gaussian([1,2, 'string']) Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'list' and 'float' >>> gaussian('hello world') Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'str' and 'float' >>> gaussian(10**234) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... OverflowError: (34, 'Result too large') >>> gaussian(10**-326) 0.3989422804014327 >>> gaussian(2523, mu=234234, sigma=3425) 0.0 """ return 1 / sqrt(2 * pi * sigma**2) * exp(-((x - mu) ** 2) / (2 * sigma**2)) if __name__ == "__main__": import doctest doctest.testmod()
""" Reference: https://en.wikipedia.org/wiki/Gaussian_function """ from numpy import exp, pi, sqrt def gaussian(x, mu: float = 0.0, sigma: float = 1.0) -> int: """ >>> gaussian(1) 0.24197072451914337 >>> gaussian(24) 3.342714441794458e-126 >>> gaussian(1, 4, 2) 0.06475879783294587 >>> gaussian(1, 5, 3) 0.05467002489199788 Supports NumPy Arrays Use numpy.meshgrid with this to generate gaussian blur on images. >>> import numpy as np >>> x = np.arange(15) >>> gaussian(x) array([3.98942280e-01, 2.41970725e-01, 5.39909665e-02, 4.43184841e-03, 1.33830226e-04, 1.48671951e-06, 6.07588285e-09, 9.13472041e-12, 5.05227108e-15, 1.02797736e-18, 7.69459863e-23, 2.11881925e-27, 2.14638374e-32, 7.99882776e-38, 1.09660656e-43]) >>> gaussian(15) 5.530709549844416e-50 >>> gaussian([1,2, 'string']) Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'list' and 'float' >>> gaussian('hello world') Traceback (most recent call last): ... TypeError: unsupported operand type(s) for -: 'str' and 'float' >>> gaussian(10**234) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... OverflowError: (34, 'Result too large') >>> gaussian(10**-326) 0.3989422804014327 >>> gaussian(2523, mu=234234, sigma=3425) 0.0 """ return 1 / sqrt(2 * pi * sigma**2) * exp(-((x - mu) ** 2) / (2 * sigma**2)) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Implements an is valid email address algorithm @ https://en.wikipedia.org/wiki/Email_address """ import string email_tests: tuple[tuple[str, bool], ...] = ( ("simple@example.com", True), ("very.common@example.com", True), ("disposable.style.email.with+symbol@example.com", True), ("other-email-with-hyphen@and.subdomains.example.com", True), ("fully-qualified-domain@example.com", True), ("user.name+tag+sorting@example.com", True), ("x@example.com", True), ("example-indeed@strange-example.com", True), ("test/test@test.com", True), ( "123456789012345678901234567890123456789012345678901234567890123@example.com", True, ), ("admin@mailserver1", True), ("example@s.example", True), ("Abc.example.com", False), ("A@b@c@example.com", False), ("abc@example..com", False), ("a(c)d,e:f;g<h>i[j\\k]l@example.com", False), ( "12345678901234567890123456789012345678901234567890123456789012345@example.com", False, ), ("i.like.underscores@but_its_not_allowed_in_this_part", False), ("", False), ) # The maximum octets (one character as a standard unicode character is one byte) # that the local part and the domain part can have MAX_LOCAL_PART_OCTETS = 64 MAX_DOMAIN_OCTETS = 255 def is_valid_email_address(email: str) -> bool: """ Returns True if the passed email address is valid. The local part of the email precedes the singular @ symbol and is associated with a display-name. For example, "john.smith" The domain is stricter than the local part and follows the @ symbol. Global email checks: 1. There can only be one @ symbol in the email address. Technically if the @ symbol is quoted in the local-part, then it is valid, however this implementation ignores "" for now. (See https://en.wikipedia.org/wiki/Email_address#:~:text=If%20quoted,) 2. The local-part and the domain are limited to a certain number of octets. With unicode storing a single character in one byte, each octet is equivalent to a character. Hence, we can just check the length of the string. Checks for the local-part: 3. The local-part may contain: upper and lowercase latin letters, digits 0 to 9, and printable characters (!#$%&'*+-/=?^_`{|}~) 4. The local-part may also contain a "." in any place that is not the first or last character, and may not have more than one "." consecutively. Checks for the domain: 5. The domain may contain: upper and lowercase latin letters and digits 0 to 9 6. Hyphen "-", provided that it is not the first or last character 7. The domain may also contain a "." in any place that is not the first or last character, and may not have more than one "." consecutively. >>> for email, valid in email_tests: ... assert is_valid_email_address(email) == valid """ # (1.) Make sure that there is only one @ symbol in the email address if email.count("@") != 1: return False local_part, domain = email.split("@") # (2.) Check octet length of the local part and domain if len(local_part) > MAX_LOCAL_PART_OCTETS or len(domain) > MAX_DOMAIN_OCTETS: return False # (3.) Validate the characters in the local-part if any( char not in string.ascii_letters + string.digits + ".(!#$%&'*+-/=?^_`{|}~)" for char in local_part ): return False # (4.) Validate the placement of "." characters in the local-part if local_part.startswith(".") or local_part.endswith(".") or ".." in local_part: return False # (5.) Validate the characters in the domain if any(char not in string.ascii_letters + string.digits + ".-" for char in domain): return False # (6.) Validate the placement of "-" characters if domain.startswith("-") or domain.endswith("."): return False # (7.) Validate the placement of "." characters if domain.startswith(".") or domain.endswith(".") or ".." in domain: return False return True if __name__ == "__main__": import doctest doctest.testmod() for email, valid in email_tests: is_valid = is_valid_email_address(email) assert is_valid == valid, f"{email} is {is_valid}" print(f"Email address {email} is {'not ' if not is_valid else ''}valid")
""" Implements an is valid email address algorithm @ https://en.wikipedia.org/wiki/Email_address """ import string email_tests: tuple[tuple[str, bool], ...] = ( ("simple@example.com", True), ("very.common@example.com", True), ("disposable.style.email.with+symbol@example.com", True), ("other-email-with-hyphen@and.subdomains.example.com", True), ("fully-qualified-domain@example.com", True), ("user.name+tag+sorting@example.com", True), ("x@example.com", True), ("example-indeed@strange-example.com", True), ("test/test@test.com", True), ( "123456789012345678901234567890123456789012345678901234567890123@example.com", True, ), ("admin@mailserver1", True), ("example@s.example", True), ("Abc.example.com", False), ("A@b@c@example.com", False), ("abc@example..com", False), ("a(c)d,e:f;g<h>i[j\\k]l@example.com", False), ( "12345678901234567890123456789012345678901234567890123456789012345@example.com", False, ), ("i.like.underscores@but_its_not_allowed_in_this_part", False), ("", False), ) # The maximum octets (one character as a standard unicode character is one byte) # that the local part and the domain part can have MAX_LOCAL_PART_OCTETS = 64 MAX_DOMAIN_OCTETS = 255 def is_valid_email_address(email: str) -> bool: """ Returns True if the passed email address is valid. The local part of the email precedes the singular @ symbol and is associated with a display-name. For example, "john.smith" The domain is stricter than the local part and follows the @ symbol. Global email checks: 1. There can only be one @ symbol in the email address. Technically if the @ symbol is quoted in the local-part, then it is valid, however this implementation ignores "" for now. (See https://en.wikipedia.org/wiki/Email_address#:~:text=If%20quoted,) 2. The local-part and the domain are limited to a certain number of octets. With unicode storing a single character in one byte, each octet is equivalent to a character. Hence, we can just check the length of the string. Checks for the local-part: 3. The local-part may contain: upper and lowercase latin letters, digits 0 to 9, and printable characters (!#$%&'*+-/=?^_`{|}~) 4. The local-part may also contain a "." in any place that is not the first or last character, and may not have more than one "." consecutively. Checks for the domain: 5. The domain may contain: upper and lowercase latin letters and digits 0 to 9 6. Hyphen "-", provided that it is not the first or last character 7. The domain may also contain a "." in any place that is not the first or last character, and may not have more than one "." consecutively. >>> for email, valid in email_tests: ... assert is_valid_email_address(email) == valid """ # (1.) Make sure that there is only one @ symbol in the email address if email.count("@") != 1: return False local_part, domain = email.split("@") # (2.) Check octet length of the local part and domain if len(local_part) > MAX_LOCAL_PART_OCTETS or len(domain) > MAX_DOMAIN_OCTETS: return False # (3.) Validate the characters in the local-part if any( char not in string.ascii_letters + string.digits + ".(!#$%&'*+-/=?^_`{|}~)" for char in local_part ): return False # (4.) Validate the placement of "." characters in the local-part if local_part.startswith(".") or local_part.endswith(".") or ".." in local_part: return False # (5.) Validate the characters in the domain if any(char not in string.ascii_letters + string.digits + ".-" for char in domain): return False # (6.) Validate the placement of "-" characters if domain.startswith("-") or domain.endswith("."): return False # (7.) Validate the placement of "." characters if domain.startswith(".") or domain.endswith(".") or ".." in domain: return False return True if __name__ == "__main__": import doctest doctest.testmod() for email, valid in email_tests: is_valid = is_valid_email_address(email) assert is_valid == valid, f"{email} is {is_valid}" print(f"Email address {email} is {'not ' if not is_valid else ''}valid")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
import math from timeit import timeit def num_digits(n: int) -> int: """ Find the number of digits in a number. >>> num_digits(12345) 5 >>> num_digits(123) 3 >>> num_digits(0) 1 >>> num_digits(-1) 1 >>> num_digits(-123456) 6 >>> num_digits('123') # Raises a TypeError for non-integer input Traceback (most recent call last): ... TypeError: Input must be an integer """ if not isinstance(n, int): raise TypeError("Input must be an integer") digits = 0 n = abs(n) while True: n = n // 10 digits += 1 if n == 0: break return digits def num_digits_fast(n: int) -> int: """ Find the number of digits in a number. abs() is used as logarithm for negative numbers is not defined. >>> num_digits_fast(12345) 5 >>> num_digits_fast(123) 3 >>> num_digits_fast(0) 1 >>> num_digits_fast(-1) 1 >>> num_digits_fast(-123456) 6 >>> num_digits('123') # Raises a TypeError for non-integer input Traceback (most recent call last): ... TypeError: Input must be an integer """ if not isinstance(n, int): raise TypeError("Input must be an integer") return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1) def num_digits_faster(n: int) -> int: """ Find the number of digits in a number. abs() is used for negative numbers >>> num_digits_faster(12345) 5 >>> num_digits_faster(123) 3 >>> num_digits_faster(0) 1 >>> num_digits_faster(-1) 1 >>> num_digits_faster(-123456) 6 >>> num_digits('123') # Raises a TypeError for non-integer input Traceback (most recent call last): ... TypeError: Input must be an integer """ if not isinstance(n, int): raise TypeError("Input must be an integer") return len(str(abs(n))) def benchmark() -> None: """ Benchmark multiple functions, with three different length int values. """ from collections.abc import Callable def benchmark_a_function(func: Callable, value: int) -> None: call = f"{func.__name__}({value})" timing = timeit(f"__main__.{call}", setup="import __main__") print(f"{call}: {func(value)} -- {timing} seconds") for value in (262144, 1125899906842624, 1267650600228229401496703205376): for func in (num_digits, num_digits_fast, num_digits_faster): benchmark_a_function(func, value) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
import math from timeit import timeit def num_digits(n: int) -> int: """ Find the number of digits in a number. >>> num_digits(12345) 5 >>> num_digits(123) 3 >>> num_digits(0) 1 >>> num_digits(-1) 1 >>> num_digits(-123456) 6 >>> num_digits('123') # Raises a TypeError for non-integer input Traceback (most recent call last): ... TypeError: Input must be an integer """ if not isinstance(n, int): raise TypeError("Input must be an integer") digits = 0 n = abs(n) while True: n = n // 10 digits += 1 if n == 0: break return digits def num_digits_fast(n: int) -> int: """ Find the number of digits in a number. abs() is used as logarithm for negative numbers is not defined. >>> num_digits_fast(12345) 5 >>> num_digits_fast(123) 3 >>> num_digits_fast(0) 1 >>> num_digits_fast(-1) 1 >>> num_digits_fast(-123456) 6 >>> num_digits('123') # Raises a TypeError for non-integer input Traceback (most recent call last): ... TypeError: Input must be an integer """ if not isinstance(n, int): raise TypeError("Input must be an integer") return 1 if n == 0 else math.floor(math.log(abs(n), 10) + 1) def num_digits_faster(n: int) -> int: """ Find the number of digits in a number. abs() is used for negative numbers >>> num_digits_faster(12345) 5 >>> num_digits_faster(123) 3 >>> num_digits_faster(0) 1 >>> num_digits_faster(-1) 1 >>> num_digits_faster(-123456) 6 >>> num_digits('123') # Raises a TypeError for non-integer input Traceback (most recent call last): ... TypeError: Input must be an integer """ if not isinstance(n, int): raise TypeError("Input must be an integer") return len(str(abs(n))) def benchmark() -> None: """ Benchmark multiple functions, with three different length int values. """ from collections.abc import Callable def benchmark_a_function(func: Callable, value: int) -> None: call = f"{func.__name__}({value})" timing = timeit(f"__main__.{call}", setup="import __main__") print(f"{call}: {func(value)} -- {timing} seconds") for value in (262144, 1125899906842624, 1267650600228229401496703205376): for func in (num_digits, num_digits_fast, num_digits_faster): benchmark_a_function(func, value) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Problem 112: https://projecteuler.net/problem=112 Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number, for example, 155349. Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538. Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%. Find the least number for which the proportion of bouncy numbers is exactly 99%. """ def check_bouncy(n: int) -> bool: """ Returns True if number is bouncy, False otherwise >>> check_bouncy(6789) False >>> check_bouncy(-12345) False >>> check_bouncy(0) False >>> check_bouncy(6.74) Traceback (most recent call last): ... ValueError: check_bouncy() accepts only integer arguments >>> check_bouncy(132475) True >>> check_bouncy(34) False >>> check_bouncy(341) True >>> check_bouncy(47) False >>> check_bouncy(-12.54) Traceback (most recent call last): ... ValueError: check_bouncy() accepts only integer arguments >>> check_bouncy(-6548) True """ if not isinstance(n, int): raise ValueError("check_bouncy() accepts only integer arguments") str_n = str(n) sorted_str_n = "".join(sorted(str_n)) return str_n not in {sorted_str_n, sorted_str_n[::-1]} def solution(percent: float = 99) -> int: """ Returns the least number for which the proportion of bouncy numbers is exactly 'percent' >>> solution(50) 538 >>> solution(90) 21780 >>> solution(80) 4770 >>> solution(105) Traceback (most recent call last): ... ValueError: solution() only accepts values from 0 to 100 >>> solution(100.011) Traceback (most recent call last): ... ValueError: solution() only accepts values from 0 to 100 """ if not 0 < percent < 100: raise ValueError("solution() only accepts values from 0 to 100") bouncy_num = 0 num = 1 while True: if check_bouncy(num): bouncy_num += 1 if (bouncy_num / num) * 100 >= percent: return num num += 1 if __name__ == "__main__": from doctest import testmod testmod() print(f"{solution(99)}")
""" Problem 112: https://projecteuler.net/problem=112 Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number, for example, 155349. Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538. Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%. Find the least number for which the proportion of bouncy numbers is exactly 99%. """ def check_bouncy(n: int) -> bool: """ Returns True if number is bouncy, False otherwise >>> check_bouncy(6789) False >>> check_bouncy(-12345) False >>> check_bouncy(0) False >>> check_bouncy(6.74) Traceback (most recent call last): ... ValueError: check_bouncy() accepts only integer arguments >>> check_bouncy(132475) True >>> check_bouncy(34) False >>> check_bouncy(341) True >>> check_bouncy(47) False >>> check_bouncy(-12.54) Traceback (most recent call last): ... ValueError: check_bouncy() accepts only integer arguments >>> check_bouncy(-6548) True """ if not isinstance(n, int): raise ValueError("check_bouncy() accepts only integer arguments") str_n = str(n) sorted_str_n = "".join(sorted(str_n)) return str_n not in {sorted_str_n, sorted_str_n[::-1]} def solution(percent: float = 99) -> int: """ Returns the least number for which the proportion of bouncy numbers is exactly 'percent' >>> solution(50) 538 >>> solution(90) 21780 >>> solution(80) 4770 >>> solution(105) Traceback (most recent call last): ... ValueError: solution() only accepts values from 0 to 100 >>> solution(100.011) Traceback (most recent call last): ... ValueError: solution() only accepts values from 0 to 100 """ if not 0 < percent < 100: raise ValueError("solution() only accepts values from 0 to 100") bouncy_num = 0 num = 1 while True: if check_bouncy(num): bouncy_num += 1 if (bouncy_num / num) * 100 >= percent: return num num += 1 if __name__ == "__main__": from doctest import testmod testmod() print(f"{solution(99)}")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
def multiplication_table(number: int, number_of_terms: int) -> str: """ Prints the multiplication table of a given number till the given number of terms >>> print(multiplication_table(3, 5)) 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 3 * 4 = 12 3 * 5 = 15 >>> print(multiplication_table(-4, 6)) -4 * 1 = -4 -4 * 2 = -8 -4 * 3 = -12 -4 * 4 = -16 -4 * 5 = -20 -4 * 6 = -24 """ return "\n".join( f"{number} * {i} = {number * i}" for i in range(1, number_of_terms + 1) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=10))
def multiplication_table(number: int, number_of_terms: int) -> str: """ Prints the multiplication table of a given number till the given number of terms >>> print(multiplication_table(3, 5)) 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 3 * 4 = 12 3 * 5 = 15 >>> print(multiplication_table(-4, 6)) -4 * 1 = -4 -4 * 2 = -8 -4 * 3 = -12 -4 * 4 = -16 -4 * 5 = -20 -4 * 6 = -24 """ return "\n".join( f"{number} * {i} = {number * i}" for i in range(1, number_of_terms + 1) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=10))
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Horizontal Projectile Motion problem in physics. This algorithm solves a specific problem in which the motion starts from the ground as can be seen below: (v = 0) * * * * * * * * * * * * GROUND GROUND For more info: https://en.wikipedia.org/wiki/Projectile_motion """ # Importing packages from math import radians as angle_to_radians from math import sin # Acceleration Constant on Earth (unit m/s^2) g = 9.80665 def check_args(init_velocity: float, angle: float) -> None: """ Check that the arguments are valid """ # Ensure valid instance if not isinstance(init_velocity, (int, float)): raise TypeError("Invalid velocity. Should be a positive number.") if not isinstance(angle, (int, float)): raise TypeError("Invalid angle. Range is 1-90 degrees.") # Ensure valid angle if angle > 90 or angle < 1: raise ValueError("Invalid angle. Range is 1-90 degrees.") # Ensure valid velocity if init_velocity < 0: raise ValueError("Invalid velocity. Should be a positive number.") def horizontal_distance(init_velocity: float, angle: float) -> float: """ Returns the horizontal distance that the object cover Formula: v_0^2 * sin(2 * alpha) --------------------- g v_0 - initial velocity alpha - angle >>> horizontal_distance(30, 45) 91.77 >>> horizontal_distance(100, 78) 414.76 >>> horizontal_distance(-1, 20) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, -20) Traceback (most recent call last): ... ValueError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(2 * angle) return round(init_velocity**2 * sin(radians) / g, 2) def max_height(init_velocity: float, angle: float) -> float: """ Returns the maximum height that the object reach Formula: v_0^2 * sin^2(alpha) -------------------- 2g v_0 - initial velocity alpha - angle >>> max_height(30, 45) 22.94 >>> max_height(100, 78) 487.82 >>> max_height("a", 20) Traceback (most recent call last): ... TypeError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(init_velocity**2 * sin(radians) ** 2 / (2 * g), 2) def total_time(init_velocity: float, angle: float) -> float: """ Returns total time of the motion Formula: 2 * v_0 * sin(alpha) -------------------- g v_0 - initial velocity alpha - angle >>> total_time(30, 45) 4.33 >>> total_time(100, 78) 19.95 >>> total_time(-10, 40) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> total_time(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(2 * init_velocity * sin(radians) / g, 2) def test_motion() -> None: """ >>> test_motion() """ v0, angle = 25, 20 assert horizontal_distance(v0, angle) == 40.97 assert max_height(v0, angle) == 3.73 assert total_time(v0, angle) == 1.74 if __name__ == "__main__": from doctest import testmod testmod() # Get input from user init_vel = float(input("Initial Velocity: ").strip()) # Get input from user angle = float(input("angle: ").strip()) # Print results print() print("Results: ") print(f"Horizontal Distance: {horizontal_distance(init_vel, angle)!s} [m]") print(f"Maximum Height: {max_height(init_vel, angle)!s} [m]") print(f"Total Time: {total_time(init_vel, angle)!s} [s]")
""" Horizontal Projectile Motion problem in physics. This algorithm solves a specific problem in which the motion starts from the ground as can be seen below: (v = 0) * * * * * * * * * * * * GROUND GROUND For more info: https://en.wikipedia.org/wiki/Projectile_motion """ # Importing packages from math import radians as angle_to_radians from math import sin # Acceleration Constant on Earth (unit m/s^2) g = 9.80665 def check_args(init_velocity: float, angle: float) -> None: """ Check that the arguments are valid """ # Ensure valid instance if not isinstance(init_velocity, (int, float)): raise TypeError("Invalid velocity. Should be a positive number.") if not isinstance(angle, (int, float)): raise TypeError("Invalid angle. Range is 1-90 degrees.") # Ensure valid angle if angle > 90 or angle < 1: raise ValueError("Invalid angle. Range is 1-90 degrees.") # Ensure valid velocity if init_velocity < 0: raise ValueError("Invalid velocity. Should be a positive number.") def horizontal_distance(init_velocity: float, angle: float) -> float: """ Returns the horizontal distance that the object cover Formula: v_0^2 * sin(2 * alpha) --------------------- g v_0 - initial velocity alpha - angle >>> horizontal_distance(30, 45) 91.77 >>> horizontal_distance(100, 78) 414.76 >>> horizontal_distance(-1, 20) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, -20) Traceback (most recent call last): ... ValueError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(2 * angle) return round(init_velocity**2 * sin(radians) / g, 2) def max_height(init_velocity: float, angle: float) -> float: """ Returns the maximum height that the object reach Formula: v_0^2 * sin^2(alpha) -------------------- 2g v_0 - initial velocity alpha - angle >>> max_height(30, 45) 22.94 >>> max_height(100, 78) 487.82 >>> max_height("a", 20) Traceback (most recent call last): ... TypeError: Invalid velocity. Should be a positive number. >>> horizontal_distance(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(init_velocity**2 * sin(radians) ** 2 / (2 * g), 2) def total_time(init_velocity: float, angle: float) -> float: """ Returns total time of the motion Formula: 2 * v_0 * sin(alpha) -------------------- g v_0 - initial velocity alpha - angle >>> total_time(30, 45) 4.33 >>> total_time(100, 78) 19.95 >>> total_time(-10, 40) Traceback (most recent call last): ... ValueError: Invalid velocity. Should be a positive number. >>> total_time(30, "b") Traceback (most recent call last): ... TypeError: Invalid angle. Range is 1-90 degrees. """ check_args(init_velocity, angle) radians = angle_to_radians(angle) return round(2 * init_velocity * sin(radians) / g, 2) def test_motion() -> None: """ >>> test_motion() """ v0, angle = 25, 20 assert horizontal_distance(v0, angle) == 40.97 assert max_height(v0, angle) == 3.73 assert total_time(v0, angle) == 1.74 if __name__ == "__main__": from doctest import testmod testmod() # Get input from user init_vel = float(input("Initial Velocity: ").strip()) # Get input from user angle = float(input("angle: ").strip()) # Print results print() print("Results: ") print(f"Horizontal Distance: {horizontal_distance(init_vel, angle)!s} [m]") print(f"Maximum Height: {max_height(init_vel, angle)!s} [m]") print(f"Total Time: {total_time(init_vel, angle)!s} [s]")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 8: https://projecteuler.net/problem=8 Largest product in a series The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ from functools import reduce N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def solution(n: str = N) -> int: """ Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. >>> solution("13978431290823798458352374") 609638400 >>> solution("13978431295823798458352374") 2612736000 >>> solution("1397843129582379841238352374") 209018880 """ return max( # mypy cannot properly interpret reduce int(reduce(lambda x, y: str(int(x) * int(y)), n[i : i + 13])) for i in range(len(n) - 12) ) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 8: https://projecteuler.net/problem=8 Largest product in a series The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. 73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 62229893423380308135336276614282806444486645238749 30358907296290491560440772390713810515859307960866 70172427121883998797908792274921901699720888093776 65727333001053367881220235421809751254540594752243 52584907711670556013604839586446706324415722155397 53697817977846174064955149290862569321978468622482 83972241375657056057490261407972968652414535100474 82166370484403199890008895243450658541227588666881 16427171479924442928230863465674813919123162824586 17866458359124566529476545682848912883142607690042 24219022671055626321111109370544217506941658960408 07198403850962455444362981230987879927244284909188 84580156166097919133875499200524063689912560717606 05886116467109405077541002256983155200055935729725 71636269561882670428252483600823257530420752963450 Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? """ from functools import reduce N = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def solution(n: str = N) -> int: """ Find the thirteen adjacent digits in the 1000-digit number n that have the greatest product and returns it. >>> solution("13978431290823798458352374") 609638400 >>> solution("13978431295823798458352374") 2612736000 >>> solution("1397843129582379841238352374") 209018880 """ return max( # mypy cannot properly interpret reduce int(reduce(lambda x, y: str(int(x) * int(y)), n[i : i + 13])) for i in range(len(n) - 12) ) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" == Juggler Sequence == Juggler sequence start with any positive integer n. The next term is obtained as follows: If n term is even, the next term is floor value of square root of n . If n is odd, the next term is floor value of 3 time the square root of n. https://en.wikipedia.org/wiki/Juggler_sequence """ # Author : Akshay Dubey (https://github.com/itsAkshayDubey) import math def juggler_sequence(number: int) -> list[int]: """ >>> juggler_sequence(0) Traceback (most recent call last): ... ValueError: Input value of [number=0] must be a positive integer >>> juggler_sequence(1) [1] >>> juggler_sequence(2) [2, 1] >>> juggler_sequence(3) [3, 5, 11, 36, 6, 2, 1] >>> juggler_sequence(5) [5, 11, 36, 6, 2, 1] >>> juggler_sequence(10) [10, 3, 5, 11, 36, 6, 2, 1] >>> juggler_sequence(25) [25, 125, 1397, 52214, 228, 15, 58, 7, 18, 4, 2, 1] >>> juggler_sequence(6.0) Traceback (most recent call last): ... TypeError: Input value of [number=6.0] must be an integer >>> juggler_sequence(-1) Traceback (most recent call last): ... ValueError: Input value of [number=-1] must be a positive integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: msg = f"Input value of [number={number}] must be a positive integer" raise ValueError(msg) sequence = [number] while number != 1: if number % 2 == 0: number = math.floor(math.sqrt(number)) else: number = math.floor( math.sqrt(number) * math.sqrt(number) * math.sqrt(number) ) sequence.append(number) return sequence if __name__ == "__main__": import doctest doctest.testmod()
""" == Juggler Sequence == Juggler sequence start with any positive integer n. The next term is obtained as follows: If n term is even, the next term is floor value of square root of n . If n is odd, the next term is floor value of 3 time the square root of n. https://en.wikipedia.org/wiki/Juggler_sequence """ # Author : Akshay Dubey (https://github.com/itsAkshayDubey) import math def juggler_sequence(number: int) -> list[int]: """ >>> juggler_sequence(0) Traceback (most recent call last): ... ValueError: Input value of [number=0] must be a positive integer >>> juggler_sequence(1) [1] >>> juggler_sequence(2) [2, 1] >>> juggler_sequence(3) [3, 5, 11, 36, 6, 2, 1] >>> juggler_sequence(5) [5, 11, 36, 6, 2, 1] >>> juggler_sequence(10) [10, 3, 5, 11, 36, 6, 2, 1] >>> juggler_sequence(25) [25, 125, 1397, 52214, 228, 15, 58, 7, 18, 4, 2, 1] >>> juggler_sequence(6.0) Traceback (most recent call last): ... TypeError: Input value of [number=6.0] must be an integer >>> juggler_sequence(-1) Traceback (most recent call last): ... ValueError: Input value of [number=-1] must be a positive integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 1: msg = f"Input value of [number={number}] must be a positive integer" raise ValueError(msg) sequence = [number] while number != 1: if number % 2 == 0: number = math.floor(math.sqrt(number)) else: number = math.floor( math.sqrt(number) * math.sqrt(number) * math.sqrt(number) ) sequence.append(number) return sequence if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" 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 from numpy.linalg import norm 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: msg = ( "Wrong input data's dimensions... " f"dataset : {dataset.ndim}, value_array : {value_array.ndim}" ) raise ValueError(msg) try: if dataset.shape[1] != value_array.shape[1]: msg = ( "Wrong input data's shape... " f"dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}" ) raise ValueError(msg) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError("Wrong shape") if dataset.dtype != value_array.dtype: msg = ( "Input data have different datatype... " f"dataset : {dataset.dtype}, value_array : {value_array.dtype}" ) raise TypeError(msg) 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 def cosine_similarity(input_a: np.ndarray, input_b: np.ndarray) -> float: """ Calculates cosine similarity between two data. :param input_a: ndarray of first vector. :param input_b: ndarray of second vector. :return: Cosine similarity of input_a and input_b. By using math.sqrt(), result will be float. >>> cosine_similarity(np.array([1]), np.array([1])) 1.0 >>> cosine_similarity(np.array([1, 2]), np.array([6, 32])) 0.9615239476408232 """ return np.dot(input_a, input_b) / (norm(input_a) * norm(input_b)) 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 from numpy.linalg import norm 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: msg = ( "Wrong input data's dimensions... " f"dataset : {dataset.ndim}, value_array : {value_array.ndim}" ) raise ValueError(msg) try: if dataset.shape[1] != value_array.shape[1]: msg = ( "Wrong input data's shape... " f"dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}" ) raise ValueError(msg) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError("Wrong shape") if dataset.dtype != value_array.dtype: msg = ( "Input data have different datatype... " f"dataset : {dataset.dtype}, value_array : {value_array.dtype}" ) raise TypeError(msg) 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 def cosine_similarity(input_a: np.ndarray, input_b: np.ndarray) -> float: """ Calculates cosine similarity between two data. :param input_a: ndarray of first vector. :param input_b: ndarray of second vector. :return: Cosine similarity of input_a and input_b. By using math.sqrt(), result will be float. >>> cosine_similarity(np.array([1]), np.array([1])) 1.0 >>> cosine_similarity(np.array([1, 2]), np.array([6, 32])) 0.9615239476408232 """ return np.dot(input_a, input_b) / (norm(input_a) * norm(input_b)) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from __future__ import annotations import csv import requests from bs4 import BeautifulSoup def get_imdb_top_250_movies(url: str = "") -> dict[str, float]: url = url or "https://www.imdb.com/chart/top/?ref_=nv_mv_250" soup = BeautifulSoup(requests.get(url).text, "html.parser") titles = soup.find_all("td", attrs="titleColumn") ratings = soup.find_all("td", class_="ratingColumn imdbRating") return { title.a.text: float(rating.strong.text) for title, rating in zip(titles, ratings) } def write_movies(filename: str = "IMDb_Top_250_Movies.csv") -> None: movies = get_imdb_top_250_movies() with open(filename, "w", newline="") as out_file: writer = csv.writer(out_file) writer.writerow(["Movie title", "IMDb rating"]) for title, rating in movies.items(): writer.writerow([title, rating]) if __name__ == "__main__": write_movies()
from __future__ import annotations import csv import requests from bs4 import BeautifulSoup def get_imdb_top_250_movies(url: str = "") -> dict[str, float]: url = url or "https://www.imdb.com/chart/top/?ref_=nv_mv_250" soup = BeautifulSoup(requests.get(url).text, "html.parser") titles = soup.find_all("td", attrs="titleColumn") ratings = soup.find_all("td", class_="ratingColumn imdbRating") return { title.a.text: float(rating.strong.text) for title, rating in zip(titles, ratings) } def write_movies(filename: str = "IMDb_Top_250_Movies.csv") -> None: movies = get_imdb_top_250_movies() with open(filename, "w", newline="") as out_file: writer = csv.writer(out_file) writer.writerow(["Movie title", "IMDb rating"]) for title, rating in movies.items(): writer.writerow([title, rating]) if __name__ == "__main__": write_movies()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def password_generator(length: int = 8) -> str: """ Password Generator allows you to generate a random password of length N. >>> len(password_generator()) 8 >>> len(password_generator(length=16)) 16 >>> len(password_generator(257)) 257 >>> len(password_generator(length=0)) 0 >>> len(password_generator(-1)) 0 """ chars = ascii_letters + digits + punctuation return "".join(secrets.choice(chars) for _ in range(length)) # ALTERNATIVE METHODS # chars_incl= characters that must be in password # i= how many letters or characters the password length will be def alternative_password_generator(chars_incl: str, i: int) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(chars_incl) quotient = i // 3 remainder = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) chars = ( chars_incl + random(ascii_letters, quotient + remainder) + random(digits, quotient) + random(punctuation, quotient) ) list_of_chars = list(chars) shuffle(list_of_chars) return "".join(list_of_chars) # random is a generalised function for letters, characters and numbers def random(chars_incl: str, i: int) -> str: return "".join(secrets.choice(chars_incl) for _ in range(i)) def random_number(chars_incl, i): pass # Put your code here... def random_letters(chars_incl, i): pass # Put your code here... def random_characters(chars_incl, i): pass # Put your code here... def is_strong_password(password: str, min_length: int = 8) -> bool: """ This will check whether a given password is strong or not. The password must be at least as long as the provided minimum length, and it must contain at least 1 lowercase letter, 1 uppercase letter, 1 number and 1 special character. >>> is_strong_password('Hwea7$2!') True >>> is_strong_password('Sh0r1') False >>> is_strong_password('Hello123') False >>> is_strong_password('Hello1238udfhiaf038fajdvjjf!jaiuFhkqi1') True >>> is_strong_password('0') False """ if len(password) < min_length: return False 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) return upper and lower and num and spec_char def main(): length = int(input("Please indicate the max length of your password: ").strip()) chars_incl = input( "Please indicate the characters that must be in your password: " ).strip() print("Password generated:", password_generator(length)) print( "Alternative Password generated:", alternative_password_generator(chars_incl, length), ) print("[If you are thinking of using this password, You better save it.]") if __name__ == "__main__": main()
import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def password_generator(length: int = 8) -> str: """ Password Generator allows you to generate a random password of length N. >>> len(password_generator()) 8 >>> len(password_generator(length=16)) 16 >>> len(password_generator(257)) 257 >>> len(password_generator(length=0)) 0 >>> len(password_generator(-1)) 0 """ chars = ascii_letters + digits + punctuation return "".join(secrets.choice(chars) for _ in range(length)) # ALTERNATIVE METHODS # chars_incl= characters that must be in password # i= how many letters or characters the password length will be def alternative_password_generator(chars_incl: str, i: int) -> str: # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(chars_incl) quotient = i // 3 remainder = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) chars = ( chars_incl + random(ascii_letters, quotient + remainder) + random(digits, quotient) + random(punctuation, quotient) ) list_of_chars = list(chars) shuffle(list_of_chars) return "".join(list_of_chars) # random is a generalised function for letters, characters and numbers def random(chars_incl: str, i: int) -> str: return "".join(secrets.choice(chars_incl) for _ in range(i)) def random_number(chars_incl, i): pass # Put your code here... def random_letters(chars_incl, i): pass # Put your code here... def random_characters(chars_incl, i): pass # Put your code here... def is_strong_password(password: str, min_length: int = 8) -> bool: """ This will check whether a given password is strong or not. The password must be at least as long as the provided minimum length, and it must contain at least 1 lowercase letter, 1 uppercase letter, 1 number and 1 special character. >>> is_strong_password('Hwea7$2!') True >>> is_strong_password('Sh0r1') False >>> is_strong_password('Hello123') False >>> is_strong_password('Hello1238udfhiaf038fajdvjjf!jaiuFhkqi1') True >>> is_strong_password('0') False """ if len(password) < min_length: return False 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) return upper and lower and num and spec_char def main(): length = int(input("Please indicate the max length of your password: ").strip()) chars_incl = input( "Please indicate the characters that must be in your password: " ).strip() print("Password generated:", password_generator(length)) print( "Alternative Password generated:", alternative_password_generator(chars_incl, length), ) print("[If you are thinking of using this password, You better save it.]") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" The ideal gas law, also called the general gas equation, is the equation of state of a hypothetical ideal gas. It is a good approximation of the behavior of many gases under many conditions, although it has several limitations. It was first stated by Benoît Paul Émile Clapeyron in 1834 as a combination of the empirical Boyle's law, Charles's law, Avogadro's law, and Gay-Lussac's law.[1] The ideal gas law is often written in an empirical form: ------------ | PV = nRT | ------------ P = Pressure (Pa) V = Volume (m^3) n = Amount of substance (mol) R = Universal gas constant T = Absolute temperature (Kelvin) (Description adapted from https://en.wikipedia.org/wiki/Ideal_gas_law ) """ UNIVERSAL_GAS_CONSTANT = 8.314462 # Unit - J mol-1 K-1 def pressure_of_gas_system(moles: float, kelvin: float, volume: float) -> float: """ >>> pressure_of_gas_system(2, 100, 5) 332.57848 >>> pressure_of_gas_system(0.5, 273, 0.004) 283731.01575 >>> pressure_of_gas_system(3, -0.46, 23.5) Traceback (most recent call last): ... ValueError: Invalid inputs. Enter positive value. """ if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("Invalid inputs. Enter positive value.") return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def volume_of_gas_system(moles: float, kelvin: float, pressure: float) -> float: """ >>> volume_of_gas_system(2, 100, 5) 332.57848 >>> volume_of_gas_system(0.5, 273, 0.004) 283731.01575 >>> volume_of_gas_system(3, -0.46, 23.5) Traceback (most recent call last): ... ValueError: Invalid inputs. Enter positive value. """ if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure def temperature_of_gas_system(moles: float, volume: float, pressure: float) -> float: """ >>> temperature_of_gas_system(2, 100, 5) 30.068090996146232 >>> temperature_of_gas_system(11, 5009, 1000) 54767.66101807144 >>> temperature_of_gas_system(3, -0.46, 23.5) Traceback (most recent call last): ... ValueError: Invalid inputs. Enter positive value. """ if moles < 0 or volume < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return pressure * volume / (moles * UNIVERSAL_GAS_CONSTANT) def moles_of_gas_system(kelvin: float, volume: float, pressure: float) -> float: """ >>> moles_of_gas_system(100, 5, 10) 0.06013618199229246 >>> moles_of_gas_system(110, 5009, 1000) 5476.766101807144 >>> moles_of_gas_system(3, -0.46, 23.5) Traceback (most recent call last): ... ValueError: Invalid inputs. Enter positive value. """ if kelvin < 0 or volume < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return pressure * volume / (kelvin * UNIVERSAL_GAS_CONSTANT) if __name__ == "__main__": from doctest import testmod testmod()
""" The ideal gas law, also called the general gas equation, is the equation of state of a hypothetical ideal gas. It is a good approximation of the behavior of many gases under many conditions, although it has several limitations. It was first stated by Benoît Paul Émile Clapeyron in 1834 as a combination of the empirical Boyle's law, Charles's law, Avogadro's law, and Gay-Lussac's law.[1] The ideal gas law is often written in an empirical form: ------------ | PV = nRT | ------------ P = Pressure (Pa) V = Volume (m^3) n = Amount of substance (mol) R = Universal gas constant T = Absolute temperature (Kelvin) (Description adapted from https://en.wikipedia.org/wiki/Ideal_gas_law ) """ UNIVERSAL_GAS_CONSTANT = 8.314462 # Unit - J mol-1 K-1 def pressure_of_gas_system(moles: float, kelvin: float, volume: float) -> float: """ >>> pressure_of_gas_system(2, 100, 5) 332.57848 >>> pressure_of_gas_system(0.5, 273, 0.004) 283731.01575 >>> pressure_of_gas_system(3, -0.46, 23.5) Traceback (most recent call last): ... ValueError: Invalid inputs. Enter positive value. """ if moles < 0 or kelvin < 0 or volume < 0: raise ValueError("Invalid inputs. Enter positive value.") return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume def volume_of_gas_system(moles: float, kelvin: float, pressure: float) -> float: """ >>> volume_of_gas_system(2, 100, 5) 332.57848 >>> volume_of_gas_system(0.5, 273, 0.004) 283731.01575 >>> volume_of_gas_system(3, -0.46, 23.5) Traceback (most recent call last): ... ValueError: Invalid inputs. Enter positive value. """ if moles < 0 or kelvin < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure def temperature_of_gas_system(moles: float, volume: float, pressure: float) -> float: """ >>> temperature_of_gas_system(2, 100, 5) 30.068090996146232 >>> temperature_of_gas_system(11, 5009, 1000) 54767.66101807144 >>> temperature_of_gas_system(3, -0.46, 23.5) Traceback (most recent call last): ... ValueError: Invalid inputs. Enter positive value. """ if moles < 0 or volume < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return pressure * volume / (moles * UNIVERSAL_GAS_CONSTANT) def moles_of_gas_system(kelvin: float, volume: float, pressure: float) -> float: """ >>> moles_of_gas_system(100, 5, 10) 0.06013618199229246 >>> moles_of_gas_system(110, 5009, 1000) 5476.766101807144 >>> moles_of_gas_system(3, -0.46, 23.5) Traceback (most recent call last): ... ValueError: Invalid inputs. Enter positive value. """ if kelvin < 0 or volume < 0 or pressure < 0: raise ValueError("Invalid inputs. Enter positive value.") return pressure * volume / (kelvin * UNIVERSAL_GAS_CONSTANT) if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
#!/usr/bin/env python3 from __future__ import annotations def decrypt_caesar_with_chi_squared( ciphertext: str, cipher_alphabet: list[str] | None = None, frequencies_dict: dict[str, float] | None = None, case_sensitive: bool = False, ) -> tuple[int, float, str]: """ Basic Usage =========== Arguments: * ciphertext (str): the text to decode (encoded with the caesar cipher) Optional Arguments: * cipher_alphabet (list): the alphabet used for the cipher (each letter is a string separated by commas) * frequencies_dict (dict): a dictionary of word frequencies where keys are the letters and values are a percentage representation of the frequency as a decimal/float * case_sensitive (bool): a boolean value: True if the case matters during decryption, False if it doesn't Returns: * A tuple in the form of: ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher ) where... - most_likely_cipher is an integer representing the shift of the smallest chi-squared statistic (most likely key) - most_likely_cipher_chi_squared_value is a float representing the chi-squared statistic of the most likely shift - decoded_most_likely_cipher is a string with the decoded cipher (decoded by the most_likely_cipher key) The Chi-squared test ==================== The caesar cipher ----------------- The caesar cipher is a very insecure encryption algorithm, however it has been used since Julius Caesar. The cipher is a simple substitution cipher where each character in the plain text is replaced by a character in the alphabet a certain number of characters after the original character. The number of characters away is called the shift or key. For example: Plain text: hello Key: 1 Cipher text: ifmmp (each letter in hello has been shifted one to the right in the eng. alphabet) As you can imagine, this doesn't provide lots of security. In fact decrypting ciphertext by brute-force is extremely easy even by hand. However one way to do that is the chi-squared test. The chi-squared test ------------------- Each letter in the english alphabet has a frequency, or the amount of times it shows up compared to other letters (usually expressed as a decimal representing the percentage likelihood). The most common letter in the english language is "e" with a frequency of 0.11162 or 11.162%. The test is completed in the following fashion. 1. The ciphertext is decoded in a brute force way (every combination of the 26 possible combinations) 2. For every combination, for each letter in the combination, the average amount of times the letter should appear the message is calculated by multiplying the total number of characters by the frequency of the letter For example: In a message of 100 characters, e should appear around 11.162 times. 3. Then, to calculate the margin of error (the amount of times the letter SHOULD appear with the amount of times the letter DOES appear), we use the chi-squared test. The following formula is used: Let: - n be the number of times the letter actually appears - p be the predicted value of the number of times the letter should appear (see #2) - let v be the chi-squared test result (referred to here as chi-squared value/statistic) (n - p)^2 --------- = v p 4. Each chi squared value for each letter is then added up to the total. The total is the chi-squared statistic for that encryption key. 5. The encryption key with the lowest chi-squared value is the most likely to be the decoded answer. Further Reading ================ * http://practicalcryptography.com/cryptanalysis/text-characterisation/chi-squared- statistic/ * https://en.wikipedia.org/wiki/Letter_frequency * https://en.wikipedia.org/wiki/Chi-squared_test * https://en.m.wikipedia.org/wiki/Caesar_cipher Doctests ======== >>> decrypt_caesar_with_chi_squared( ... 'dof pz aol jhlzhy jpwoly zv wvwbshy? pa pz avv lhzf av jyhjr!' ... ) # doctest: +NORMALIZE_WHITESPACE (7, 3129.228005747531, 'why is the caesar cipher so popular? it is too easy to crack!') >>> decrypt_caesar_with_chi_squared('crybd cdbsxq') (10, 233.35343938980898, 'short string') >>> decrypt_caesar_with_chi_squared('Crybd Cdbsxq', case_sensitive=True) (10, 233.35343938980898, 'Short String') >>> decrypt_caesar_with_chi_squared(12) Traceback (most recent call last): AttributeError: 'int' object has no attribute 'lower' """ alphabet_letters = cipher_alphabet or [chr(i) for i in range(97, 123)] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) frequencies = { "a": 0.08497, "b": 0.01492, "c": 0.02202, "d": 0.04253, "e": 0.11162, "f": 0.02228, "g": 0.02015, "h": 0.06094, "i": 0.07546, "j": 0.00153, "k": 0.01292, "l": 0.04025, "m": 0.02406, "n": 0.06749, "o": 0.07507, "p": 0.01929, "q": 0.00095, "r": 0.07587, "s": 0.06327, "t": 0.09356, "u": 0.02758, "v": 0.00978, "w": 0.02560, "x": 0.00150, "y": 0.01994, "z": 0.00077, } else: # Custom frequencies dictionary frequencies = frequencies_dict if not case_sensitive: ciphertext = ciphertext.lower() # Chi squared statistic values chi_squared_statistic_values: dict[int, tuple[float, str]] = {} # cycle through all of the shifts for shift in range(len(alphabet_letters)): decrypted_with_shift = "" # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet new_key = (alphabet_letters.index(letter.lower()) - shift) % len( alphabet_letters ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter chi_squared_statistic = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: letter = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message occurrences = decrypted_with_shift.lower().count(letter) # Get the excepcted amount of times the letter should appear based # on letter frequencies expected = frequencies[letter] * occurrences # Complete the chi squared statistic formula chi_letter_value = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: # Get the amount of times the letter occurs in the message occurrences = decrypted_with_shift.count(letter) # Get the excepcted amount of times the letter should appear based # on letter frequencies expected = frequencies[letter] * occurrences # Complete the chi squared statistic formula chi_letter_value = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary chi_squared_statistic_values[shift] = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(key: int) -> tuple[float, str]: return chi_squared_statistic_values[key] most_likely_cipher: int = min( chi_squared_statistic_values, key=chi_squared_statistic_values_sorting_key, ) # Get all the data from the most likely cipher (key, decoded message) ( most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, ) = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
#!/usr/bin/env python3 from __future__ import annotations def decrypt_caesar_with_chi_squared( ciphertext: str, cipher_alphabet: list[str] | None = None, frequencies_dict: dict[str, float] | None = None, case_sensitive: bool = False, ) -> tuple[int, float, str]: """ Basic Usage =========== Arguments: * ciphertext (str): the text to decode (encoded with the caesar cipher) Optional Arguments: * cipher_alphabet (list): the alphabet used for the cipher (each letter is a string separated by commas) * frequencies_dict (dict): a dictionary of word frequencies where keys are the letters and values are a percentage representation of the frequency as a decimal/float * case_sensitive (bool): a boolean value: True if the case matters during decryption, False if it doesn't Returns: * A tuple in the form of: ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher ) where... - most_likely_cipher is an integer representing the shift of the smallest chi-squared statistic (most likely key) - most_likely_cipher_chi_squared_value is a float representing the chi-squared statistic of the most likely shift - decoded_most_likely_cipher is a string with the decoded cipher (decoded by the most_likely_cipher key) The Chi-squared test ==================== The caesar cipher ----------------- The caesar cipher is a very insecure encryption algorithm, however it has been used since Julius Caesar. The cipher is a simple substitution cipher where each character in the plain text is replaced by a character in the alphabet a certain number of characters after the original character. The number of characters away is called the shift or key. For example: Plain text: hello Key: 1 Cipher text: ifmmp (each letter in hello has been shifted one to the right in the eng. alphabet) As you can imagine, this doesn't provide lots of security. In fact decrypting ciphertext by brute-force is extremely easy even by hand. However one way to do that is the chi-squared test. The chi-squared test ------------------- Each letter in the english alphabet has a frequency, or the amount of times it shows up compared to other letters (usually expressed as a decimal representing the percentage likelihood). The most common letter in the english language is "e" with a frequency of 0.11162 or 11.162%. The test is completed in the following fashion. 1. The ciphertext is decoded in a brute force way (every combination of the 26 possible combinations) 2. For every combination, for each letter in the combination, the average amount of times the letter should appear the message is calculated by multiplying the total number of characters by the frequency of the letter For example: In a message of 100 characters, e should appear around 11.162 times. 3. Then, to calculate the margin of error (the amount of times the letter SHOULD appear with the amount of times the letter DOES appear), we use the chi-squared test. The following formula is used: Let: - n be the number of times the letter actually appears - p be the predicted value of the number of times the letter should appear (see #2) - let v be the chi-squared test result (referred to here as chi-squared value/statistic) (n - p)^2 --------- = v p 4. Each chi squared value for each letter is then added up to the total. The total is the chi-squared statistic for that encryption key. 5. The encryption key with the lowest chi-squared value is the most likely to be the decoded answer. Further Reading ================ * http://practicalcryptography.com/cryptanalysis/text-characterisation/chi-squared- statistic/ * https://en.wikipedia.org/wiki/Letter_frequency * https://en.wikipedia.org/wiki/Chi-squared_test * https://en.m.wikipedia.org/wiki/Caesar_cipher Doctests ======== >>> decrypt_caesar_with_chi_squared( ... 'dof pz aol jhlzhy jpwoly zv wvwbshy? pa pz avv lhzf av jyhjr!' ... ) # doctest: +NORMALIZE_WHITESPACE (7, 3129.228005747531, 'why is the caesar cipher so popular? it is too easy to crack!') >>> decrypt_caesar_with_chi_squared('crybd cdbsxq') (10, 233.35343938980898, 'short string') >>> decrypt_caesar_with_chi_squared('Crybd Cdbsxq', case_sensitive=True) (10, 233.35343938980898, 'Short String') >>> decrypt_caesar_with_chi_squared(12) Traceback (most recent call last): AttributeError: 'int' object has no attribute 'lower' """ alphabet_letters = cipher_alphabet or [chr(i) for i in range(97, 123)] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) frequencies = { "a": 0.08497, "b": 0.01492, "c": 0.02202, "d": 0.04253, "e": 0.11162, "f": 0.02228, "g": 0.02015, "h": 0.06094, "i": 0.07546, "j": 0.00153, "k": 0.01292, "l": 0.04025, "m": 0.02406, "n": 0.06749, "o": 0.07507, "p": 0.01929, "q": 0.00095, "r": 0.07587, "s": 0.06327, "t": 0.09356, "u": 0.02758, "v": 0.00978, "w": 0.02560, "x": 0.00150, "y": 0.01994, "z": 0.00077, } else: # Custom frequencies dictionary frequencies = frequencies_dict if not case_sensitive: ciphertext = ciphertext.lower() # Chi squared statistic values chi_squared_statistic_values: dict[int, tuple[float, str]] = {} # cycle through all of the shifts for shift in range(len(alphabet_letters)): decrypted_with_shift = "" # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet new_key = (alphabet_letters.index(letter.lower()) - shift) % len( alphabet_letters ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter chi_squared_statistic = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: letter = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message occurrences = decrypted_with_shift.lower().count(letter) # Get the excepcted amount of times the letter should appear based # on letter frequencies expected = frequencies[letter] * occurrences # Complete the chi squared statistic formula chi_letter_value = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: # Get the amount of times the letter occurs in the message occurrences = decrypted_with_shift.count(letter) # Get the excepcted amount of times the letter should appear based # on letter frequencies expected = frequencies[letter] * occurrences # Complete the chi squared statistic formula chi_letter_value = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary chi_squared_statistic_values[shift] = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(key: int) -> tuple[float, str]: return chi_squared_statistic_values[key] most_likely_cipher: int = min( chi_squared_statistic_values, key=chi_squared_statistic_values_sorting_key, ) # Get all the data from the most likely cipher (key, decoded message) ( most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, ) = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Author: P Shreyas Shetty Implementation of Newton-Raphson method for solving equations of kind f(x) = 0. It is an iterative method where solution is found by the expression x[n+1] = x[n] + f(x[n])/f'(x[n]) If no solution exists, then either the solution will not be found when iteration limit is reached or the gradient f'(x[n]) approaches zero. In both cases, exception is raised. If iteration limit is reached, try increasing maxiter. """ import math as m from collections.abc import Callable DerivativeFunc = Callable[[float], float] def calc_derivative(f: DerivativeFunc, a: float, h: float = 0.001) -> float: """ Calculates derivative at point a for function f using finite difference method """ return (f(a + h) - f(a - h)) / (2 * h) def newton_raphson( f: DerivativeFunc, x0: float = 0, maxiter: int = 100, step: float = 0.0001, maxerror: float = 1e-6, logsteps: bool = False, ) -> tuple[float, float, list[float]]: a = x0 # set the initial guess steps = [a] error = abs(f(a)) f1 = lambda x: calc_derivative(f, x, h=step) # noqa: E731 Derivative of f(x) for _ in range(maxiter): if f1(a) == 0: raise ValueError("No converging solution found") a = a - f(a) / f1(a) # Calculate the next estimate if logsteps: steps.append(a) if error < maxerror: break else: raise ValueError("Iteration limit reached, no converging solution found") if logsteps: # If logstep is true, then log intermediate steps return a, error, steps return a, error, [] if __name__ == "__main__": from matplotlib import pyplot as plt f = lambda x: m.tanh(x) ** 2 - m.exp(3 * x) # noqa: E731 solution, error, steps = newton_raphson( f, x0=10, maxiter=1000, step=1e-6, logsteps=True ) plt.plot([abs(f(x)) for x in steps]) plt.xlabel("step") plt.ylabel("error") plt.show() print(f"solution = {{{solution:f}}}, error = {{{error:f}}}")
""" Author: P Shreyas Shetty Implementation of Newton-Raphson method for solving equations of kind f(x) = 0. It is an iterative method where solution is found by the expression x[n+1] = x[n] + f(x[n])/f'(x[n]) If no solution exists, then either the solution will not be found when iteration limit is reached or the gradient f'(x[n]) approaches zero. In both cases, exception is raised. If iteration limit is reached, try increasing maxiter. """ import math as m from collections.abc import Callable DerivativeFunc = Callable[[float], float] def calc_derivative(f: DerivativeFunc, a: float, h: float = 0.001) -> float: """ Calculates derivative at point a for function f using finite difference method """ return (f(a + h) - f(a - h)) / (2 * h) def newton_raphson( f: DerivativeFunc, x0: float = 0, maxiter: int = 100, step: float = 0.0001, maxerror: float = 1e-6, logsteps: bool = False, ) -> tuple[float, float, list[float]]: a = x0 # set the initial guess steps = [a] error = abs(f(a)) f1 = lambda x: calc_derivative(f, x, h=step) # noqa: E731 Derivative of f(x) for _ in range(maxiter): if f1(a) == 0: raise ValueError("No converging solution found") a = a - f(a) / f1(a) # Calculate the next estimate if logsteps: steps.append(a) if error < maxerror: break else: raise ValueError("Iteration limit reached, no converging solution found") if logsteps: # If logstep is true, then log intermediate steps return a, error, steps return a, error, [] if __name__ == "__main__": from matplotlib import pyplot as plt f = lambda x: m.tanh(x) ** 2 - m.exp(3 * x) # noqa: E731 solution, error, steps = newton_raphson( f, x0=10, maxiter=1000, step=1e-6, logsteps=True ) plt.plot([abs(f(x)) for x in steps]) plt.xlabel("step") plt.ylabel("error") plt.show() print(f"solution = {{{solution:f}}}, error = {{{error:f}}}")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 587: https://projecteuler.net/problem=587 A square is drawn around a circle as shown in the diagram below on the left. We shall call the blue shaded region the L-section. A line is drawn from the bottom left of the square to the top right as shown in the diagram on the right. We shall call the orange shaded region a concave triangle. It should be clear that the concave triangle occupies exactly half of the L-section. Two circles are placed next to each other horizontally, a rectangle is drawn around both circles, and a line is drawn from the bottom left to the top right as shown in the diagram below. This time the concave triangle occupies approximately 36.46% of the L-section. If n circles are placed next to each other horizontally, a rectangle is drawn around the n circles, and a line is drawn from the bottom left to the top right, then it can be shown that the least value of n for which the concave triangle occupies less than 10% of the L-section is n = 15. What is the least value of n for which the concave triangle occupies less than 0.1% of the L-section? """ from itertools import count from math import asin, pi, sqrt def circle_bottom_arc_integral(point: float) -> float: """ Returns integral of circle bottom arc y = 1 / 2 - sqrt(1 / 4 - (x - 1 / 2) ^ 2) >>> circle_bottom_arc_integral(0) 0.39269908169872414 >>> circle_bottom_arc_integral(1 / 2) 0.44634954084936207 >>> circle_bottom_arc_integral(1) 0.5 """ return ( (1 - 2 * point) * sqrt(point - point**2) + 2 * point + asin(sqrt(1 - point)) ) / 4 def concave_triangle_area(circles_number: int) -> float: """ Returns area of concave triangle >>> concave_triangle_area(1) 0.026825229575318944 >>> concave_triangle_area(2) 0.01956236140083944 """ intersection_y = (circles_number + 1 - sqrt(2 * circles_number)) / ( 2 * (circles_number**2 + 1) ) intersection_x = circles_number * intersection_y triangle_area = intersection_x * intersection_y / 2 concave_region_area = circle_bottom_arc_integral( 1 / 2 ) - circle_bottom_arc_integral(intersection_x) return triangle_area + concave_region_area def solution(fraction: float = 1 / 1000) -> int: """ Returns least value of n for which the concave triangle occupies less than fraction of the L-section >>> solution(1 / 10) 15 """ l_section_area = (1 - pi / 4) / 4 for n in count(1): if concave_triangle_area(n) / l_section_area < fraction: return n return -1 if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 587: https://projecteuler.net/problem=587 A square is drawn around a circle as shown in the diagram below on the left. We shall call the blue shaded region the L-section. A line is drawn from the bottom left of the square to the top right as shown in the diagram on the right. We shall call the orange shaded region a concave triangle. It should be clear that the concave triangle occupies exactly half of the L-section. Two circles are placed next to each other horizontally, a rectangle is drawn around both circles, and a line is drawn from the bottom left to the top right as shown in the diagram below. This time the concave triangle occupies approximately 36.46% of the L-section. If n circles are placed next to each other horizontally, a rectangle is drawn around the n circles, and a line is drawn from the bottom left to the top right, then it can be shown that the least value of n for which the concave triangle occupies less than 10% of the L-section is n = 15. What is the least value of n for which the concave triangle occupies less than 0.1% of the L-section? """ from itertools import count from math import asin, pi, sqrt def circle_bottom_arc_integral(point: float) -> float: """ Returns integral of circle bottom arc y = 1 / 2 - sqrt(1 / 4 - (x - 1 / 2) ^ 2) >>> circle_bottom_arc_integral(0) 0.39269908169872414 >>> circle_bottom_arc_integral(1 / 2) 0.44634954084936207 >>> circle_bottom_arc_integral(1) 0.5 """ return ( (1 - 2 * point) * sqrt(point - point**2) + 2 * point + asin(sqrt(1 - point)) ) / 4 def concave_triangle_area(circles_number: int) -> float: """ Returns area of concave triangle >>> concave_triangle_area(1) 0.026825229575318944 >>> concave_triangle_area(2) 0.01956236140083944 """ intersection_y = (circles_number + 1 - sqrt(2 * circles_number)) / ( 2 * (circles_number**2 + 1) ) intersection_x = circles_number * intersection_y triangle_area = intersection_x * intersection_y / 2 concave_region_area = circle_bottom_arc_integral( 1 / 2 ) - circle_bottom_arc_integral(intersection_x) return triangle_area + concave_region_area def solution(fraction: float = 1 / 1000) -> int: """ Returns least value of n for which the concave triangle occupies less than fraction of the L-section >>> solution(1 / 10) 15 """ l_section_area = (1 - pi / 4) / 4 for n in count(1): if concave_triangle_area(n) / l_section_area < fraction: return n return -1 if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
#!/usr/bin/env python3 import os from collections.abc import Iterator def good_file_paths(top_dir: str = ".") -> Iterator[str]: for dir_path, dir_names, filenames in os.walk(top_dir): dir_names[:] = [d for d in dir_names if d != "scripts" and d[0] not in "._"] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(filename)[1] in (".py", ".ipynb"): yield os.path.join(dir_path, filename).lstrip("./") def md_prefix(i): return f"{i * ' '}*" if i else "\n##" def print_path(old_path: str, new_path: str) -> str: old_parts = old_path.split(os.sep) for i, new_part in enumerate(new_path.split(os.sep)): if (i + 1 > len(old_parts) or old_parts[i] != new_part) and new_part: print(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") return new_path def print_directory_md(top_dir: str = ".") -> None: old_path = "" for filepath in sorted(good_file_paths(top_dir)): filepath, filename = os.path.split(filepath) if filepath != old_path: old_path = print_path(old_path, filepath) indent = (filepath.count(os.sep) + 1) if filepath else 0 url = f"{filepath}/{filename}".replace(" ", "%20") filename = os.path.splitext(filename.replace("_", " ").title())[0] print(f"{md_prefix(indent)} [{filename}]({url})") if __name__ == "__main__": print_directory_md(".")
#!/usr/bin/env python3 import os from collections.abc import Iterator def good_file_paths(top_dir: str = ".") -> Iterator[str]: for dir_path, dir_names, filenames in os.walk(top_dir): dir_names[:] = [d for d in dir_names if d != "scripts" and d[0] not in "._"] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(filename)[1] in (".py", ".ipynb"): yield os.path.join(dir_path, filename).lstrip("./") def md_prefix(i): return f"{i * ' '}*" if i else "\n##" def print_path(old_path: str, new_path: str) -> str: old_parts = old_path.split(os.sep) for i, new_part in enumerate(new_path.split(os.sep)): if (i + 1 > len(old_parts) or old_parts[i] != new_part) and new_part: print(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") return new_path def print_directory_md(top_dir: str = ".") -> None: old_path = "" for filepath in sorted(good_file_paths(top_dir)): filepath, filename = os.path.split(filepath) if filepath != old_path: old_path = print_path(old_path, filepath) indent = (filepath.count(os.sep) + 1) if filepath else 0 url = f"{filepath}/{filename}".replace(" ", "%20") filename = os.path.splitext(filename.replace("_", " ").title())[0] print(f"{md_prefix(indent)} [{filename}]({url})") if __name__ == "__main__": print_directory_md(".")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" The MD5 algorithm is a hash function that's commonly used as a checksum to detect data corruption. The algorithm works by processing a given message in blocks of 512 bits, padding the message as needed. It uses the blocks to operate a 128-bit state and performs a total of 64 such operations. Note that all values are little-endian, so inputs are converted as needed. Although MD5 was used as a cryptographic hash function in the past, it's since been cracked, so it shouldn't be used for security purposes. For more info, see https://en.wikipedia.org/wiki/MD5 """ from collections.abc import Generator from math import sin def to_little_endian(string_32: bytes) -> bytes: """ Converts the given string to little-endian in groups of 8 chars. Arguments: string_32 {[string]} -- [32-char string] Raises: ValueError -- [input is not 32 char] Returns: 32-char little-endian string >>> to_little_endian(b'1234567890abcdfghijklmnopqrstuvw') b'pqrstuvwhijklmno90abcdfg12345678' >>> to_little_endian(b'1234567890') Traceback (most recent call last): ... ValueError: Input must be of length 32 """ if len(string_32) != 32: raise ValueError("Input must be of length 32") little_endian = b"" for i in [3, 2, 1, 0]: little_endian += string_32[8 * i : 8 * i + 8] return little_endian def reformat_hex(i: int) -> bytes: """ Converts the given non-negative integer to hex string. Example: Suppose the input is the following: i = 1234 The input is 0x000004d2 in hex, so the little-endian hex string is "d2040000". Arguments: i {[int]} -- [integer] Raises: ValueError -- [input is negative] Returns: 8-char little-endian hex string >>> reformat_hex(1234) b'd2040000' >>> reformat_hex(666) b'9a020000' >>> reformat_hex(0) b'00000000' >>> reformat_hex(1234567890) b'd2029649' >>> reformat_hex(1234567890987654321) b'b11c6cb1' >>> reformat_hex(-1) Traceback (most recent call last): ... ValueError: Input must be non-negative """ if i < 0: raise ValueError("Input must be non-negative") hex_rep = format(i, "08x")[-8:] little_endian_hex = b"" for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("utf-8") return little_endian_hex def preprocess(message: bytes) -> bytes: """ Preprocesses the message string: - Convert message to bit string - Pad bit string to a multiple of 512 chars: - Append a 1 - Append 0's until length = 448 (mod 512) - Append length of original message (64 chars) Example: Suppose the input is the following: message = "a" The message bit string is "01100001", which is 8 bits long. Thus, the bit string needs 439 bits of padding so that (bit_string + "1" + padding) = 448 (mod 512). The message length is "000010000...0" in 64-bit little-endian binary. The combined bit string is then 512 bits long. Arguments: message {[string]} -- [message string] Returns: processed bit string padded to a multiple of 512 chars >>> preprocess(b"a") == (b"01100001" + b"1" + ... (b"0" * 439) + b"00001000" + (b"0" * 56)) True >>> preprocess(b"") == b"1" + (b"0" * 447) + (b"0" * 64) True """ bit_string = b"" for char in message: bit_string += format(char, "08b").encode("utf-8") start_len = format(len(bit_string), "064b").encode("utf-8") # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(bit_string) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:]) + to_little_endian(start_len[:32]) return bit_string def get_block_words(bit_string: bytes) -> Generator[list[int], None, None]: """ Splits bit string into blocks of 512 chars and yields each block as a list of 32-bit words Example: Suppose the input is the following: bit_string = "000000000...0" + # 0x00 (32 bits, padded to the right) "000000010...0" + # 0x01 (32 bits, padded to the right) "000000100...0" + # 0x02 (32 bits, padded to the right) "000000110...0" + # 0x03 (32 bits, padded to the right) ... "000011110...0" # 0x0a (32 bits, padded to the right) Then len(bit_string) == 512, so there'll be 1 block. The block is split into 32-bit words, and each word is converted to little endian. The first word is interpreted as 0 in decimal, the second word is interpreted as 1 in decimal, etc. Thus, block_words == [[0, 1, 2, 3, ..., 15]]. Arguments: bit_string {[string]} -- [bit string with multiple of 512 as length] Raises: ValueError -- [length of bit string isn't multiple of 512] Yields: a list of 16 32-bit words >>> test_string = ("".join(format(n << 24, "032b") for n in range(16)) ... .encode("utf-8")) >>> list(get_block_words(test_string)) [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]] >>> list(get_block_words(test_string * 4)) == [list(range(16))] * 4 True >>> list(get_block_words(b"1" * 512)) == [[4294967295] * 16] True >>> list(get_block_words(b"")) [] >>> list(get_block_words(b"1111")) Traceback (most recent call last): ... ValueError: Input must have length that's a multiple of 512 """ if len(bit_string) % 512 != 0: raise ValueError("Input must have length that's a multiple of 512") for pos in range(0, len(bit_string), 512): block = bit_string[pos : pos + 512] block_words = [] for i in range(0, 512, 32): block_words.append(int(to_little_endian(block[i : i + 32]), 2)) yield block_words def not_32(i: int) -> int: """ Perform bitwise NOT on given int. Arguments: i {[int]} -- [given int] Raises: ValueError -- [input is negative] Returns: Result of bitwise NOT on i >>> not_32(34) 4294967261 >>> not_32(1234) 4294966061 >>> not_32(4294966061) 1234 >>> not_32(0) 4294967295 >>> not_32(1) 4294967294 >>> not_32(-1) Traceback (most recent call last): ... ValueError: Input must be non-negative """ if i < 0: raise ValueError("Input must be non-negative") i_str = format(i, "032b") new_str = "" for c in i_str: new_str += "1" if c == "0" else "0" return int(new_str, 2) def sum_32(a: int, b: int) -> int: """ Add two numbers as 32-bit ints. Arguments: a {[int]} -- [first given int] b {[int]} -- [second given int] Returns: (a + b) as an unsigned 32-bit int >>> sum_32(1, 1) 2 >>> sum_32(2, 3) 5 >>> sum_32(0, 0) 0 >>> sum_32(-1, -1) 4294967294 >>> sum_32(4294967295, 1) 0 """ return (a + b) % 2**32 def left_rotate_32(i: int, shift: int) -> int: """ Rotate the bits of a given int left by a given amount. Arguments: i {[int]} -- [given int] shift {[int]} -- [shift amount] Raises: ValueError -- [either given int or shift is negative] Returns: `i` rotated to the left by `shift` bits >>> left_rotate_32(1234, 1) 2468 >>> left_rotate_32(1111, 4) 17776 >>> left_rotate_32(2147483648, 1) 1 >>> left_rotate_32(2147483648, 3) 4 >>> left_rotate_32(4294967295, 4) 4294967295 >>> left_rotate_32(1234, 0) 1234 >>> left_rotate_32(0, 0) 0 >>> left_rotate_32(-1, 0) Traceback (most recent call last): ... ValueError: Input must be non-negative >>> left_rotate_32(0, -1) Traceback (most recent call last): ... ValueError: Shift must be non-negative """ if i < 0: raise ValueError("Input must be non-negative") if shift < 0: raise ValueError("Shift must be non-negative") return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def md5_me(message: bytes) -> bytes: """ Returns the 32-char MD5 hash of a given message. Reference: https://en.wikipedia.org/wiki/MD5#Algorithm Arguments: message {[string]} -- [message] Returns: 32-char MD5 hash string >>> md5_me(b"") b'd41d8cd98f00b204e9800998ecf8427e' >>> md5_me(b"The quick brown fox jumps over the lazy dog") b'9e107d9d372bb6826bd81d3542a419d6' >>> md5_me(b"The quick brown fox jumps over the lazy dog.") b'e4d909c290d0fb1ca068ffaddf22cbd0' >>> import hashlib >>> from string import ascii_letters >>> msgs = [b"", ascii_letters.encode("utf-8"), "Üñîçø∂é".encode("utf-8"), ... b"The quick brown fox jumps over the lazy dog."] >>> all(md5_me(msg) == hashlib.md5(msg).hexdigest().encode("utf-8") for msg in msgs) True """ # Convert to bit string, add padding and append message length bit_string = preprocess(message) added_consts = [int(2**32 * abs(sin(i + 1))) for i in range(64)] # Starting states a0 = 0x67452301 b0 = 0xEFCDAB89 c0 = 0x98BADCFE d0 = 0x10325476 shift_amounts = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(bit_string): a = a0 b = b0 c = c0 d = d0 # Hash current chunk for i in range(64): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f f = d ^ (b & (c ^ d)) g = i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f f = c ^ (d & (b ^ c)) g = (5 * i + 1) % 16 elif i <= 47: f = b ^ c ^ d g = (3 * i + 5) % 16 else: f = c ^ (b | not_32(d)) g = (7 * i) % 16 f = (f + a + added_consts[i] + block_words[g]) % 2**32 a = d d = c c = b b = sum_32(b, left_rotate_32(f, shift_amounts[i])) # Add hashed chunk to running total a0 = sum_32(a0, a) b0 = sum_32(b0, b) c0 = sum_32(c0, c) d0 = sum_32(d0, d) digest = reformat_hex(a0) + reformat_hex(b0) + reformat_hex(c0) + reformat_hex(d0) return digest if __name__ == "__main__": import doctest doctest.testmod()
""" The MD5 algorithm is a hash function that's commonly used as a checksum to detect data corruption. The algorithm works by processing a given message in blocks of 512 bits, padding the message as needed. It uses the blocks to operate a 128-bit state and performs a total of 64 such operations. Note that all values are little-endian, so inputs are converted as needed. Although MD5 was used as a cryptographic hash function in the past, it's since been cracked, so it shouldn't be used for security purposes. For more info, see https://en.wikipedia.org/wiki/MD5 """ from collections.abc import Generator from math import sin def to_little_endian(string_32: bytes) -> bytes: """ Converts the given string to little-endian in groups of 8 chars. Arguments: string_32 {[string]} -- [32-char string] Raises: ValueError -- [input is not 32 char] Returns: 32-char little-endian string >>> to_little_endian(b'1234567890abcdfghijklmnopqrstuvw') b'pqrstuvwhijklmno90abcdfg12345678' >>> to_little_endian(b'1234567890') Traceback (most recent call last): ... ValueError: Input must be of length 32 """ if len(string_32) != 32: raise ValueError("Input must be of length 32") little_endian = b"" for i in [3, 2, 1, 0]: little_endian += string_32[8 * i : 8 * i + 8] return little_endian def reformat_hex(i: int) -> bytes: """ Converts the given non-negative integer to hex string. Example: Suppose the input is the following: i = 1234 The input is 0x000004d2 in hex, so the little-endian hex string is "d2040000". Arguments: i {[int]} -- [integer] Raises: ValueError -- [input is negative] Returns: 8-char little-endian hex string >>> reformat_hex(1234) b'd2040000' >>> reformat_hex(666) b'9a020000' >>> reformat_hex(0) b'00000000' >>> reformat_hex(1234567890) b'd2029649' >>> reformat_hex(1234567890987654321) b'b11c6cb1' >>> reformat_hex(-1) Traceback (most recent call last): ... ValueError: Input must be non-negative """ if i < 0: raise ValueError("Input must be non-negative") hex_rep = format(i, "08x")[-8:] little_endian_hex = b"" for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("utf-8") return little_endian_hex def preprocess(message: bytes) -> bytes: """ Preprocesses the message string: - Convert message to bit string - Pad bit string to a multiple of 512 chars: - Append a 1 - Append 0's until length = 448 (mod 512) - Append length of original message (64 chars) Example: Suppose the input is the following: message = "a" The message bit string is "01100001", which is 8 bits long. Thus, the bit string needs 439 bits of padding so that (bit_string + "1" + padding) = 448 (mod 512). The message length is "000010000...0" in 64-bit little-endian binary. The combined bit string is then 512 bits long. Arguments: message {[string]} -- [message string] Returns: processed bit string padded to a multiple of 512 chars >>> preprocess(b"a") == (b"01100001" + b"1" + ... (b"0" * 439) + b"00001000" + (b"0" * 56)) True >>> preprocess(b"") == b"1" + (b"0" * 447) + (b"0" * 64) True """ bit_string = b"" for char in message: bit_string += format(char, "08b").encode("utf-8") start_len = format(len(bit_string), "064b").encode("utf-8") # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(bit_string) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:]) + to_little_endian(start_len[:32]) return bit_string def get_block_words(bit_string: bytes) -> Generator[list[int], None, None]: """ Splits bit string into blocks of 512 chars and yields each block as a list of 32-bit words Example: Suppose the input is the following: bit_string = "000000000...0" + # 0x00 (32 bits, padded to the right) "000000010...0" + # 0x01 (32 bits, padded to the right) "000000100...0" + # 0x02 (32 bits, padded to the right) "000000110...0" + # 0x03 (32 bits, padded to the right) ... "000011110...0" # 0x0a (32 bits, padded to the right) Then len(bit_string) == 512, so there'll be 1 block. The block is split into 32-bit words, and each word is converted to little endian. The first word is interpreted as 0 in decimal, the second word is interpreted as 1 in decimal, etc. Thus, block_words == [[0, 1, 2, 3, ..., 15]]. Arguments: bit_string {[string]} -- [bit string with multiple of 512 as length] Raises: ValueError -- [length of bit string isn't multiple of 512] Yields: a list of 16 32-bit words >>> test_string = ("".join(format(n << 24, "032b") for n in range(16)) ... .encode("utf-8")) >>> list(get_block_words(test_string)) [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]] >>> list(get_block_words(test_string * 4)) == [list(range(16))] * 4 True >>> list(get_block_words(b"1" * 512)) == [[4294967295] * 16] True >>> list(get_block_words(b"")) [] >>> list(get_block_words(b"1111")) Traceback (most recent call last): ... ValueError: Input must have length that's a multiple of 512 """ if len(bit_string) % 512 != 0: raise ValueError("Input must have length that's a multiple of 512") for pos in range(0, len(bit_string), 512): block = bit_string[pos : pos + 512] block_words = [] for i in range(0, 512, 32): block_words.append(int(to_little_endian(block[i : i + 32]), 2)) yield block_words def not_32(i: int) -> int: """ Perform bitwise NOT on given int. Arguments: i {[int]} -- [given int] Raises: ValueError -- [input is negative] Returns: Result of bitwise NOT on i >>> not_32(34) 4294967261 >>> not_32(1234) 4294966061 >>> not_32(4294966061) 1234 >>> not_32(0) 4294967295 >>> not_32(1) 4294967294 >>> not_32(-1) Traceback (most recent call last): ... ValueError: Input must be non-negative """ if i < 0: raise ValueError("Input must be non-negative") i_str = format(i, "032b") new_str = "" for c in i_str: new_str += "1" if c == "0" else "0" return int(new_str, 2) def sum_32(a: int, b: int) -> int: """ Add two numbers as 32-bit ints. Arguments: a {[int]} -- [first given int] b {[int]} -- [second given int] Returns: (a + b) as an unsigned 32-bit int >>> sum_32(1, 1) 2 >>> sum_32(2, 3) 5 >>> sum_32(0, 0) 0 >>> sum_32(-1, -1) 4294967294 >>> sum_32(4294967295, 1) 0 """ return (a + b) % 2**32 def left_rotate_32(i: int, shift: int) -> int: """ Rotate the bits of a given int left by a given amount. Arguments: i {[int]} -- [given int] shift {[int]} -- [shift amount] Raises: ValueError -- [either given int or shift is negative] Returns: `i` rotated to the left by `shift` bits >>> left_rotate_32(1234, 1) 2468 >>> left_rotate_32(1111, 4) 17776 >>> left_rotate_32(2147483648, 1) 1 >>> left_rotate_32(2147483648, 3) 4 >>> left_rotate_32(4294967295, 4) 4294967295 >>> left_rotate_32(1234, 0) 1234 >>> left_rotate_32(0, 0) 0 >>> left_rotate_32(-1, 0) Traceback (most recent call last): ... ValueError: Input must be non-negative >>> left_rotate_32(0, -1) Traceback (most recent call last): ... ValueError: Shift must be non-negative """ if i < 0: raise ValueError("Input must be non-negative") if shift < 0: raise ValueError("Shift must be non-negative") return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def md5_me(message: bytes) -> bytes: """ Returns the 32-char MD5 hash of a given message. Reference: https://en.wikipedia.org/wiki/MD5#Algorithm Arguments: message {[string]} -- [message] Returns: 32-char MD5 hash string >>> md5_me(b"") b'd41d8cd98f00b204e9800998ecf8427e' >>> md5_me(b"The quick brown fox jumps over the lazy dog") b'9e107d9d372bb6826bd81d3542a419d6' >>> md5_me(b"The quick brown fox jumps over the lazy dog.") b'e4d909c290d0fb1ca068ffaddf22cbd0' >>> import hashlib >>> from string import ascii_letters >>> msgs = [b"", ascii_letters.encode("utf-8"), "Üñîçø∂é".encode("utf-8"), ... b"The quick brown fox jumps over the lazy dog."] >>> all(md5_me(msg) == hashlib.md5(msg).hexdigest().encode("utf-8") for msg in msgs) True """ # Convert to bit string, add padding and append message length bit_string = preprocess(message) added_consts = [int(2**32 * abs(sin(i + 1))) for i in range(64)] # Starting states a0 = 0x67452301 b0 = 0xEFCDAB89 c0 = 0x98BADCFE d0 = 0x10325476 shift_amounts = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(bit_string): a = a0 b = b0 c = c0 d = d0 # Hash current chunk for i in range(64): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f f = d ^ (b & (c ^ d)) g = i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f f = c ^ (d & (b ^ c)) g = (5 * i + 1) % 16 elif i <= 47: f = b ^ c ^ d g = (3 * i + 5) % 16 else: f = c ^ (b | not_32(d)) g = (7 * i) % 16 f = (f + a + added_consts[i] + block_words[g]) % 2**32 a = d d = c c = b b = sum_32(b, left_rotate_32(f, shift_amounts[i])) # Add hashed chunk to running total a0 = sum_32(a0, a) b0 = sum_32(b0, b) c0 = sum_32(c0, c) d0 = sum_32(d0, d) digest = reformat_hex(a0) + reformat_hex(b0) + reformat_hex(c0) + reformat_hex(d0) return digest if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Creates a random wordsearch with eight different directions that are best described as compass locations. @ https://en.wikipedia.org/wiki/Word_search """ from random import choice, randint, shuffle # The words to display on the word search - # can be made dynamic by randonly selecting a certain number of # words from a predefined word file, while ensuring the character # count fits within the matrix size (n x m) WORDS = ["cat", "dog", "snake", "fish"] WIDTH = 10 HEIGHT = 10 class WordSearch: """ >>> ws = WordSearch(WORDS, WIDTH, HEIGHT) >>> ws.board # doctest: +ELLIPSIS [[None, ..., None], ..., [None, ..., None]] >>> ws.generate_board() """ def __init__(self, words: list[str], width: int, height: int) -> None: self.words = words self.width = width self.height = height # Board matrix holding each letter self.board: list[list[str | None]] = [[None] * width for _ in range(height)] def insert_north(self, word: str, rows: list[int], cols: list[int]) -> None: """ >>> ws = WordSearch(WORDS, 3, 3) >>> ws.insert_north("cat", [2], [2]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, None, 't'], [None, None, 'a'], [None, None, 'c']] >>> ws.insert_north("at", [0, 1, 2], [2, 1]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, 't', 't'], [None, 'a', 'a'], [None, None, 'c']] """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space above the row to fit in the word if word_length > row + 1: continue # Attempt to insert the word into each column for col in cols: # Only check to be made here is if there are existing letters # above the column that will be overwritten letters_above = [self.board[row - i][col] for i in range(word_length)] if all(letter is None for letter in letters_above): # Successful, insert the word north for i in range(word_length): self.board[row - i][col] = word[i] return def insert_northeast(self, word: str, rows: list[int], cols: list[int]) -> None: """ >>> ws = WordSearch(WORDS, 3, 3) >>> ws.insert_northeast("cat", [2], [0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, None, 't'], [None, 'a', None], ['c', None, None]] >>> ws.insert_northeast("at", [0, 1], [2, 1, 0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, 't', 't'], ['a', 'a', None], ['c', None, None]] """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space for the word above the row if word_length > row + 1: continue # Attempt to insert the word into each column for col in cols: # Check if there is space to the right of the word as well as above if word_length + col > self.width: continue # Check if there are existing letters # to the right of the column that will be overwritten letters_diagonal_left = [ self.board[row - i][col + i] for i in range(word_length) ] if all(letter is None for letter in letters_diagonal_left): # Successful, insert the word northeast for i in range(word_length): self.board[row - i][col + i] = word[i] return def insert_east(self, word: str, rows: list[int], cols: list[int]) -> None: """ >>> ws = WordSearch(WORDS, 3, 3) >>> ws.insert_east("cat", [1], [0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, None, None], ['c', 'a', 't'], [None, None, None]] >>> ws.insert_east("at", [1, 0], [2, 1, 0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, 'a', 't'], ['c', 'a', 't'], [None, None, None]] """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Attempt to insert the word into each column for col in cols: # Check if there is space to the right of the word if word_length + col > self.width: continue # Check if there are existing letters # to the right of the column that will be overwritten letters_left = [self.board[row][col + i] for i in range(word_length)] if all(letter is None for letter in letters_left): # Successful, insert the word east for i in range(word_length): self.board[row][col + i] = word[i] return def insert_southeast(self, word: str, rows: list[int], cols: list[int]) -> None: """ >>> ws = WordSearch(WORDS, 3, 3) >>> ws.insert_southeast("cat", [0], [0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [['c', None, None], [None, 'a', None], [None, None, 't']] >>> ws.insert_southeast("at", [1, 0], [2, 1, 0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [['c', None, None], ['a', 'a', None], [None, 't', 't']] """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space for the word below the row if word_length + row > self.height: continue # Attempt to insert the word into each column for col in cols: # Check if there is space to the right of the word as well as below if word_length + col > self.width: continue # Check if there are existing letters # to the right of the column that will be overwritten letters_diagonal_left = [ self.board[row + i][col + i] for i in range(word_length) ] if all(letter is None for letter in letters_diagonal_left): # Successful, insert the word southeast for i in range(word_length): self.board[row + i][col + i] = word[i] return def insert_south(self, word: str, rows: list[int], cols: list[int]) -> None: """ >>> ws = WordSearch(WORDS, 3, 3) >>> ws.insert_south("cat", [0], [0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [['c', None, None], ['a', None, None], ['t', None, None]] >>> ws.insert_south("at", [2, 1, 0], [0, 1, 2]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [['c', None, None], ['a', 'a', None], ['t', 't', None]] """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space below the row to fit in the word if word_length + row > self.height: continue # Attempt to insert the word into each column for col in cols: # Only check to be made here is if there are existing letters # below the column that will be overwritten letters_below = [self.board[row + i][col] for i in range(word_length)] if all(letter is None for letter in letters_below): # Successful, insert the word south for i in range(word_length): self.board[row + i][col] = word[i] return def insert_southwest(self, word: str, rows: list[int], cols: list[int]) -> None: """ >>> ws = WordSearch(WORDS, 3, 3) >>> ws.insert_southwest("cat", [0], [2]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, None, 'c'], [None, 'a', None], ['t', None, None]] >>> ws.insert_southwest("at", [1, 2], [2, 1, 0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, None, 'c'], [None, 'a', 'a'], ['t', 't', None]] """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space for the word below the row if word_length + row > self.height: continue # Attempt to insert the word into each column for col in cols: # Check if there is space to the left of the word as well as below if word_length > col + 1: continue # Check if there are existing letters # to the right of the column that will be overwritten letters_diagonal_left = [ self.board[row + i][col - i] for i in range(word_length) ] if all(letter is None for letter in letters_diagonal_left): # Successful, insert the word southwest for i in range(word_length): self.board[row + i][col - i] = word[i] return def insert_west(self, word: str, rows: list[int], cols: list[int]) -> None: """ >>> ws = WordSearch(WORDS, 3, 3) >>> ws.insert_west("cat", [1], [2]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, None, None], ['t', 'a', 'c'], [None, None, None]] >>> ws.insert_west("at", [1, 0], [1, 2, 0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [['t', 'a', None], ['t', 'a', 'c'], [None, None, None]] """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Attempt to insert the word into each column for col in cols: # Check if there is space to the left of the word if word_length > col + 1: continue # Check if there are existing letters # to the left of the column that will be overwritten letters_left = [self.board[row][col - i] for i in range(word_length)] if all(letter is None for letter in letters_left): # Successful, insert the word west for i in range(word_length): self.board[row][col - i] = word[i] return def insert_northwest(self, word: str, rows: list[int], cols: list[int]) -> None: """ >>> ws = WordSearch(WORDS, 3, 3) >>> ws.insert_northwest("cat", [2], [2]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [['t', None, None], [None, 'a', None], [None, None, 'c']] >>> ws.insert_northwest("at", [1, 2], [0, 1]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [['t', None, None], ['t', 'a', None], [None, 'a', 'c']] """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space for the word above the row if word_length > row + 1: continue # Attempt to insert the word into each column for col in cols: # Check if there is space to the left of the word as well as above if word_length > col + 1: continue # Check if there are existing letters # to the right of the column that will be overwritten letters_diagonal_left = [ self.board[row - i][col - i] for i in range(word_length) ] if all(letter is None for letter in letters_diagonal_left): # Successful, insert the word northwest for i in range(word_length): self.board[row - i][col - i] = word[i] return def generate_board(self) -> None: """ Generates a board with a random direction for each word. >>> wt = WordSearch(WORDS, WIDTH, HEIGHT) >>> wt.generate_board() >>> len(list(filter(lambda word: word is not None, sum(wt.board, start=[]))) ... ) == sum(map(lambda word: len(word), WORDS)) True """ directions = ( self.insert_north, self.insert_northeast, self.insert_east, self.insert_southeast, self.insert_south, self.insert_southwest, self.insert_west, self.insert_northwest, ) for word in self.words: # Shuffle the row order and column order that is used when brute forcing # the insertion of the word rows, cols = list(range(self.height)), list(range(self.width)) shuffle(rows) shuffle(cols) # Insert the word via the direction choice(directions)(word, rows, cols) def visualise_word_search( board: list[list[str | None]] | None = None, *, add_fake_chars: bool = True ) -> None: """ Graphically displays the word search in the terminal. >>> ws = WordSearch(WORDS, 5, 5) >>> ws.insert_north("cat", [4], [4]) >>> visualise_word_search( ... ws.board, add_fake_chars=False) # doctest: +NORMALIZE_WHITESPACE # # # # # # # # # # # # # # t # # # # a # # # # c >>> ws.insert_northeast("snake", [4], [4, 3, 2, 1, 0]) >>> visualise_word_search( ... ws.board, add_fake_chars=False) # doctest: +NORMALIZE_WHITESPACE # # # # e # # # k # # # a # t # n # # a s # # # c """ if board is None: word_search = WordSearch(WORDS, WIDTH, HEIGHT) word_search.generate_board() board = word_search.board result = "" for row in range(len(board)): for col in range(len(board[0])): character = "#" if (letter := board[row][col]) is not None: character = letter # Empty char, so add a fake char elif add_fake_chars: character = chr(randint(97, 122)) result += f"{character} " result += "\n" print(result, end="") if __name__ == "__main__": import doctest doctest.testmod() visualise_word_search()
""" Creates a random wordsearch with eight different directions that are best described as compass locations. @ https://en.wikipedia.org/wiki/Word_search """ from random import choice, randint, shuffle # The words to display on the word search - # can be made dynamic by randonly selecting a certain number of # words from a predefined word file, while ensuring the character # count fits within the matrix size (n x m) WORDS = ["cat", "dog", "snake", "fish"] WIDTH = 10 HEIGHT = 10 class WordSearch: """ >>> ws = WordSearch(WORDS, WIDTH, HEIGHT) >>> ws.board # doctest: +ELLIPSIS [[None, ..., None], ..., [None, ..., None]] >>> ws.generate_board() """ def __init__(self, words: list[str], width: int, height: int) -> None: self.words = words self.width = width self.height = height # Board matrix holding each letter self.board: list[list[str | None]] = [[None] * width for _ in range(height)] def insert_north(self, word: str, rows: list[int], cols: list[int]) -> None: """ >>> ws = WordSearch(WORDS, 3, 3) >>> ws.insert_north("cat", [2], [2]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, None, 't'], [None, None, 'a'], [None, None, 'c']] >>> ws.insert_north("at", [0, 1, 2], [2, 1]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, 't', 't'], [None, 'a', 'a'], [None, None, 'c']] """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space above the row to fit in the word if word_length > row + 1: continue # Attempt to insert the word into each column for col in cols: # Only check to be made here is if there are existing letters # above the column that will be overwritten letters_above = [self.board[row - i][col] for i in range(word_length)] if all(letter is None for letter in letters_above): # Successful, insert the word north for i in range(word_length): self.board[row - i][col] = word[i] return def insert_northeast(self, word: str, rows: list[int], cols: list[int]) -> None: """ >>> ws = WordSearch(WORDS, 3, 3) >>> ws.insert_northeast("cat", [2], [0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, None, 't'], [None, 'a', None], ['c', None, None]] >>> ws.insert_northeast("at", [0, 1], [2, 1, 0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, 't', 't'], ['a', 'a', None], ['c', None, None]] """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space for the word above the row if word_length > row + 1: continue # Attempt to insert the word into each column for col in cols: # Check if there is space to the right of the word as well as above if word_length + col > self.width: continue # Check if there are existing letters # to the right of the column that will be overwritten letters_diagonal_left = [ self.board[row - i][col + i] for i in range(word_length) ] if all(letter is None for letter in letters_diagonal_left): # Successful, insert the word northeast for i in range(word_length): self.board[row - i][col + i] = word[i] return def insert_east(self, word: str, rows: list[int], cols: list[int]) -> None: """ >>> ws = WordSearch(WORDS, 3, 3) >>> ws.insert_east("cat", [1], [0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, None, None], ['c', 'a', 't'], [None, None, None]] >>> ws.insert_east("at", [1, 0], [2, 1, 0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, 'a', 't'], ['c', 'a', 't'], [None, None, None]] """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Attempt to insert the word into each column for col in cols: # Check if there is space to the right of the word if word_length + col > self.width: continue # Check if there are existing letters # to the right of the column that will be overwritten letters_left = [self.board[row][col + i] for i in range(word_length)] if all(letter is None for letter in letters_left): # Successful, insert the word east for i in range(word_length): self.board[row][col + i] = word[i] return def insert_southeast(self, word: str, rows: list[int], cols: list[int]) -> None: """ >>> ws = WordSearch(WORDS, 3, 3) >>> ws.insert_southeast("cat", [0], [0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [['c', None, None], [None, 'a', None], [None, None, 't']] >>> ws.insert_southeast("at", [1, 0], [2, 1, 0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [['c', None, None], ['a', 'a', None], [None, 't', 't']] """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space for the word below the row if word_length + row > self.height: continue # Attempt to insert the word into each column for col in cols: # Check if there is space to the right of the word as well as below if word_length + col > self.width: continue # Check if there are existing letters # to the right of the column that will be overwritten letters_diagonal_left = [ self.board[row + i][col + i] for i in range(word_length) ] if all(letter is None for letter in letters_diagonal_left): # Successful, insert the word southeast for i in range(word_length): self.board[row + i][col + i] = word[i] return def insert_south(self, word: str, rows: list[int], cols: list[int]) -> None: """ >>> ws = WordSearch(WORDS, 3, 3) >>> ws.insert_south("cat", [0], [0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [['c', None, None], ['a', None, None], ['t', None, None]] >>> ws.insert_south("at", [2, 1, 0], [0, 1, 2]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [['c', None, None], ['a', 'a', None], ['t', 't', None]] """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space below the row to fit in the word if word_length + row > self.height: continue # Attempt to insert the word into each column for col in cols: # Only check to be made here is if there are existing letters # below the column that will be overwritten letters_below = [self.board[row + i][col] for i in range(word_length)] if all(letter is None for letter in letters_below): # Successful, insert the word south for i in range(word_length): self.board[row + i][col] = word[i] return def insert_southwest(self, word: str, rows: list[int], cols: list[int]) -> None: """ >>> ws = WordSearch(WORDS, 3, 3) >>> ws.insert_southwest("cat", [0], [2]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, None, 'c'], [None, 'a', None], ['t', None, None]] >>> ws.insert_southwest("at", [1, 2], [2, 1, 0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, None, 'c'], [None, 'a', 'a'], ['t', 't', None]] """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space for the word below the row if word_length + row > self.height: continue # Attempt to insert the word into each column for col in cols: # Check if there is space to the left of the word as well as below if word_length > col + 1: continue # Check if there are existing letters # to the right of the column that will be overwritten letters_diagonal_left = [ self.board[row + i][col - i] for i in range(word_length) ] if all(letter is None for letter in letters_diagonal_left): # Successful, insert the word southwest for i in range(word_length): self.board[row + i][col - i] = word[i] return def insert_west(self, word: str, rows: list[int], cols: list[int]) -> None: """ >>> ws = WordSearch(WORDS, 3, 3) >>> ws.insert_west("cat", [1], [2]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [[None, None, None], ['t', 'a', 'c'], [None, None, None]] >>> ws.insert_west("at", [1, 0], [1, 2, 0]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [['t', 'a', None], ['t', 'a', 'c'], [None, None, None]] """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Attempt to insert the word into each column for col in cols: # Check if there is space to the left of the word if word_length > col + 1: continue # Check if there are existing letters # to the left of the column that will be overwritten letters_left = [self.board[row][col - i] for i in range(word_length)] if all(letter is None for letter in letters_left): # Successful, insert the word west for i in range(word_length): self.board[row][col - i] = word[i] return def insert_northwest(self, word: str, rows: list[int], cols: list[int]) -> None: """ >>> ws = WordSearch(WORDS, 3, 3) >>> ws.insert_northwest("cat", [2], [2]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [['t', None, None], [None, 'a', None], [None, None, 'c']] >>> ws.insert_northwest("at", [1, 2], [0, 1]) >>> ws.board # doctest: +NORMALIZE_WHITESPACE [['t', None, None], ['t', 'a', None], [None, 'a', 'c']] """ word_length = len(word) # Attempt to insert the word into each row and when successful, exit for row in rows: # Check if there is space for the word above the row if word_length > row + 1: continue # Attempt to insert the word into each column for col in cols: # Check if there is space to the left of the word as well as above if word_length > col + 1: continue # Check if there are existing letters # to the right of the column that will be overwritten letters_diagonal_left = [ self.board[row - i][col - i] for i in range(word_length) ] if all(letter is None for letter in letters_diagonal_left): # Successful, insert the word northwest for i in range(word_length): self.board[row - i][col - i] = word[i] return def generate_board(self) -> None: """ Generates a board with a random direction for each word. >>> wt = WordSearch(WORDS, WIDTH, HEIGHT) >>> wt.generate_board() >>> len(list(filter(lambda word: word is not None, sum(wt.board, start=[]))) ... ) == sum(map(lambda word: len(word), WORDS)) True """ directions = ( self.insert_north, self.insert_northeast, self.insert_east, self.insert_southeast, self.insert_south, self.insert_southwest, self.insert_west, self.insert_northwest, ) for word in self.words: # Shuffle the row order and column order that is used when brute forcing # the insertion of the word rows, cols = list(range(self.height)), list(range(self.width)) shuffle(rows) shuffle(cols) # Insert the word via the direction choice(directions)(word, rows, cols) def visualise_word_search( board: list[list[str | None]] | None = None, *, add_fake_chars: bool = True ) -> None: """ Graphically displays the word search in the terminal. >>> ws = WordSearch(WORDS, 5, 5) >>> ws.insert_north("cat", [4], [4]) >>> visualise_word_search( ... ws.board, add_fake_chars=False) # doctest: +NORMALIZE_WHITESPACE # # # # # # # # # # # # # # t # # # # a # # # # c >>> ws.insert_northeast("snake", [4], [4, 3, 2, 1, 0]) >>> visualise_word_search( ... ws.board, add_fake_chars=False) # doctest: +NORMALIZE_WHITESPACE # # # # e # # # k # # # a # t # n # # a s # # # c """ if board is None: word_search = WordSearch(WORDS, WIDTH, HEIGHT) word_search.generate_board() board = word_search.board result = "" for row in range(len(board)): for col in range(len(board[0])): character = "#" if (letter := board[row][col]) is not None: character = letter # Empty char, so add a fake char elif add_fake_chars: character = chr(randint(97, 122)) result += f"{character} " result += "\n" print(result, end="") if __name__ == "__main__": import doctest doctest.testmod() visualise_word_search()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
"""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()
"""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
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
def bin_to_decimal(bin_string: str) -> int: """ Convert a binary value to its decimal equivalent >>> bin_to_decimal("101") 5 >>> bin_to_decimal(" 1010 ") 10 >>> bin_to_decimal("-11101") -29 >>> bin_to_decimal("0") 0 >>> bin_to_decimal("a") Traceback (most recent call last): ... ValueError: Non-binary value was passed to the function >>> bin_to_decimal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> bin_to_decimal("39") Traceback (most recent call last): ... ValueError: Non-binary value was passed to the function """ bin_string = str(bin_string).strip() if not bin_string: raise ValueError("Empty string was passed to the function") is_negative = bin_string[0] == "-" if is_negative: bin_string = bin_string[1:] if not all(char in "01" for char in bin_string): raise ValueError("Non-binary value was passed to the function") decimal_number = 0 for char in bin_string: decimal_number = 2 * decimal_number + int(char) return -decimal_number if is_negative else decimal_number if __name__ == "__main__": from doctest import testmod testmod()
def bin_to_decimal(bin_string: str) -> int: """ Convert a binary value to its decimal equivalent >>> bin_to_decimal("101") 5 >>> bin_to_decimal(" 1010 ") 10 >>> bin_to_decimal("-11101") -29 >>> bin_to_decimal("0") 0 >>> bin_to_decimal("a") Traceback (most recent call last): ... ValueError: Non-binary value was passed to the function >>> bin_to_decimal("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function >>> bin_to_decimal("39") Traceback (most recent call last): ... ValueError: Non-binary value was passed to the function """ bin_string = str(bin_string).strip() if not bin_string: raise ValueError("Empty string was passed to the function") is_negative = bin_string[0] == "-" if is_negative: bin_string = bin_string[1:] if not all(char in "01" for char in bin_string): raise ValueError("Non-binary value was passed to the function") decimal_number = 0 for char in bin_string: decimal_number = 2 * decimal_number + int(char) return -decimal_number if is_negative else decimal_number if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" What is the greatest product of four adjacent numbers (horizontally, vertically, or diagonally) in this 20x20 array? 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ import os def solution(): """Returns the greatest product of four adjacent numbers (horizontally, vertically, or diagonally). >>> solution() 70600674 """ with open(os.path.dirname(__file__) + "/grid.txt") as f: l = [] # noqa: E741 for _ in range(20): l.append([int(x) for x in f.readline().split()]) maximum = 0 # right for i in range(20): for j in range(17): temp = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: maximum = temp # down for i in range(17): for j in range(20): temp = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: maximum = temp # diagonal 1 for i in range(17): for j in range(17): temp = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: maximum = temp # diagonal 2 for i in range(17): for j in range(3, 20): temp = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: maximum = temp return maximum if __name__ == "__main__": print(solution())
""" What is the greatest product of four adjacent numbers (horizontally, vertically, or diagonally) in this 20x20 array? 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ import os def solution(): """Returns the greatest product of four adjacent numbers (horizontally, vertically, or diagonally). >>> solution() 70600674 """ with open(os.path.dirname(__file__) + "/grid.txt") as f: l = [] # noqa: E741 for _ in range(20): l.append([int(x) for x in f.readline().split()]) maximum = 0 # right for i in range(20): for j in range(17): temp = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: maximum = temp # down for i in range(17): for j in range(20): temp = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: maximum = temp # diagonal 1 for i in range(17): for j in range(17): temp = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: maximum = temp # diagonal 2 for i in range(17): for j in range(3, 20): temp = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: maximum = temp return maximum if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Python implementation of the MSD radix sort algorithm. It used the binary representation of the integers to sort them. https://en.wikipedia.org/wiki/Radix_sort """ from __future__ import annotations def msd_radix_sort(list_of_ints: list[int]) -> list[int]: """ Implementation of the MSD radix sort algorithm. Only works with positive integers :param list_of_ints: A list of integers :return: Returns the sorted list >>> msd_radix_sort([40, 12, 1, 100, 4]) [1, 4, 12, 40, 100] >>> msd_radix_sort([]) [] >>> msd_radix_sort([123, 345, 123, 80]) [80, 123, 123, 345] >>> msd_radix_sort([1209, 834598, 1, 540402, 45]) [1, 45, 1209, 540402, 834598] >>> msd_radix_sort([-1, 34, 45]) Traceback (most recent call last): ... ValueError: All numbers must be positive """ if not list_of_ints: return [] if min(list_of_ints) < 0: raise ValueError("All numbers must be positive") most_bits = max(len(bin(x)[2:]) for x in list_of_ints) return _msd_radix_sort(list_of_ints, most_bits) def _msd_radix_sort(list_of_ints: list[int], bit_position: int) -> list[int]: """ Sort the given list based on the bit at bit_position. Numbers with a 0 at that position will be at the start of the list, numbers with a 1 at the end. :param list_of_ints: A list of integers :param bit_position: the position of the bit that gets compared :return: Returns a partially sorted list >>> _msd_radix_sort([45, 2, 32], 1) [2, 32, 45] >>> _msd_radix_sort([10, 4, 12], 2) [4, 12, 10] """ if bit_position == 0 or len(list_of_ints) in [0, 1]: return list_of_ints zeros = [] ones = [] # Split numbers based on bit at bit_position from the right for number in list_of_ints: if (number >> (bit_position - 1)) & 1: # number has a one at bit bit_position ones.append(number) else: # number has a zero at bit bit_position zeros.append(number) # recursively split both lists further zeros = _msd_radix_sort(zeros, bit_position - 1) ones = _msd_radix_sort(ones, bit_position - 1) # recombine lists res = zeros res.extend(ones) return res def msd_radix_sort_inplace(list_of_ints: list[int]): """ Inplace implementation of the MSD radix sort algorithm. Sorts based on the binary representation of the integers. >>> lst = [1, 345, 23, 89, 0, 3] >>> msd_radix_sort_inplace(lst) >>> lst == sorted(lst) True >>> lst = [1, 43, 0, 0, 0, 24, 3, 3] >>> msd_radix_sort_inplace(lst) >>> lst == sorted(lst) True >>> lst = [] >>> msd_radix_sort_inplace(lst) >>> lst == [] True >>> lst = [-1, 34, 23, 4, -42] >>> msd_radix_sort_inplace(lst) Traceback (most recent call last): ... ValueError: All numbers must be positive """ length = len(list_of_ints) if not list_of_ints or length == 1: return if min(list_of_ints) < 0: raise ValueError("All numbers must be positive") most_bits = max(len(bin(x)[2:]) for x in list_of_ints) _msd_radix_sort_inplace(list_of_ints, most_bits, 0, length) def _msd_radix_sort_inplace( list_of_ints: list[int], bit_position: int, begin_index: int, end_index: int ): """ Sort the given list based on the bit at bit_position. Numbers with a 0 at that position will be at the start of the list, numbers with a 1 at the end. >>> lst = [45, 2, 32, 24, 534, 2932] >>> _msd_radix_sort_inplace(lst, 1, 0, 3) >>> lst == [32, 2, 45, 24, 534, 2932] True >>> lst = [0, 2, 1, 3, 12, 10, 4, 90, 54, 2323, 756] >>> _msd_radix_sort_inplace(lst, 2, 4, 7) >>> lst == [0, 2, 1, 3, 12, 4, 10, 90, 54, 2323, 756] True """ if bit_position == 0 or end_index - begin_index <= 1: return bit_position -= 1 i = begin_index j = end_index - 1 while i <= j: changed = False if not (list_of_ints[i] >> bit_position) & 1: # found zero at the beginning i += 1 changed = True if (list_of_ints[j] >> bit_position) & 1: # found one at the end j -= 1 changed = True if changed: continue list_of_ints[i], list_of_ints[j] = list_of_ints[j], list_of_ints[i] j -= 1 if j != i: i += 1 _msd_radix_sort_inplace(list_of_ints, bit_position, begin_index, i) _msd_radix_sort_inplace(list_of_ints, bit_position, i, end_index) if __name__ == "__main__": import doctest doctest.testmod()
""" Python implementation of the MSD radix sort algorithm. It used the binary representation of the integers to sort them. https://en.wikipedia.org/wiki/Radix_sort """ from __future__ import annotations def msd_radix_sort(list_of_ints: list[int]) -> list[int]: """ Implementation of the MSD radix sort algorithm. Only works with positive integers :param list_of_ints: A list of integers :return: Returns the sorted list >>> msd_radix_sort([40, 12, 1, 100, 4]) [1, 4, 12, 40, 100] >>> msd_radix_sort([]) [] >>> msd_radix_sort([123, 345, 123, 80]) [80, 123, 123, 345] >>> msd_radix_sort([1209, 834598, 1, 540402, 45]) [1, 45, 1209, 540402, 834598] >>> msd_radix_sort([-1, 34, 45]) Traceback (most recent call last): ... ValueError: All numbers must be positive """ if not list_of_ints: return [] if min(list_of_ints) < 0: raise ValueError("All numbers must be positive") most_bits = max(len(bin(x)[2:]) for x in list_of_ints) return _msd_radix_sort(list_of_ints, most_bits) def _msd_radix_sort(list_of_ints: list[int], bit_position: int) -> list[int]: """ Sort the given list based on the bit at bit_position. Numbers with a 0 at that position will be at the start of the list, numbers with a 1 at the end. :param list_of_ints: A list of integers :param bit_position: the position of the bit that gets compared :return: Returns a partially sorted list >>> _msd_radix_sort([45, 2, 32], 1) [2, 32, 45] >>> _msd_radix_sort([10, 4, 12], 2) [4, 12, 10] """ if bit_position == 0 or len(list_of_ints) in [0, 1]: return list_of_ints zeros = [] ones = [] # Split numbers based on bit at bit_position from the right for number in list_of_ints: if (number >> (bit_position - 1)) & 1: # number has a one at bit bit_position ones.append(number) else: # number has a zero at bit bit_position zeros.append(number) # recursively split both lists further zeros = _msd_radix_sort(zeros, bit_position - 1) ones = _msd_radix_sort(ones, bit_position - 1) # recombine lists res = zeros res.extend(ones) return res def msd_radix_sort_inplace(list_of_ints: list[int]): """ Inplace implementation of the MSD radix sort algorithm. Sorts based on the binary representation of the integers. >>> lst = [1, 345, 23, 89, 0, 3] >>> msd_radix_sort_inplace(lst) >>> lst == sorted(lst) True >>> lst = [1, 43, 0, 0, 0, 24, 3, 3] >>> msd_radix_sort_inplace(lst) >>> lst == sorted(lst) True >>> lst = [] >>> msd_radix_sort_inplace(lst) >>> lst == [] True >>> lst = [-1, 34, 23, 4, -42] >>> msd_radix_sort_inplace(lst) Traceback (most recent call last): ... ValueError: All numbers must be positive """ length = len(list_of_ints) if not list_of_ints or length == 1: return if min(list_of_ints) < 0: raise ValueError("All numbers must be positive") most_bits = max(len(bin(x)[2:]) for x in list_of_ints) _msd_radix_sort_inplace(list_of_ints, most_bits, 0, length) def _msd_radix_sort_inplace( list_of_ints: list[int], bit_position: int, begin_index: int, end_index: int ): """ Sort the given list based on the bit at bit_position. Numbers with a 0 at that position will be at the start of the list, numbers with a 1 at the end. >>> lst = [45, 2, 32, 24, 534, 2932] >>> _msd_radix_sort_inplace(lst, 1, 0, 3) >>> lst == [32, 2, 45, 24, 534, 2932] True >>> lst = [0, 2, 1, 3, 12, 10, 4, 90, 54, 2323, 756] >>> _msd_radix_sort_inplace(lst, 2, 4, 7) >>> lst == [0, 2, 1, 3, 12, 4, 10, 90, 54, 2323, 756] True """ if bit_position == 0 or end_index - begin_index <= 1: return bit_position -= 1 i = begin_index j = end_index - 1 while i <= j: changed = False if not (list_of_ints[i] >> bit_position) & 1: # found zero at the beginning i += 1 changed = True if (list_of_ints[j] >> bit_position) & 1: # found one at the end j -= 1 changed = True if changed: continue list_of_ints[i], list_of_ints[j] = list_of_ints[j], list_of_ints[i] j -= 1 if j != i: i += 1 _msd_radix_sort_inplace(list_of_ints, bit_position, begin_index, i) _msd_radix_sort_inplace(list_of_ints, bit_position, i, end_index) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Implemented an algorithm using opencv to tone an image with sepia technique """ from cv2 import destroyAllWindows, imread, imshow, waitKey def make_sepia(img, factor: int): """ Function create sepia tone. Source: https://en.wikipedia.org/wiki/Sepia_(color) """ pixel_h, pixel_v = img.shape[0], img.shape[1] def to_grayscale(blue, green, red): """ Helper function to create pixel's greyscale representation Src: https://pl.wikipedia.org/wiki/YUV """ return 0.2126 * red + 0.587 * green + 0.114 * blue def normalize(value): """Helper function to normalize R/G/B value -> return 255 if value > 255""" return min(value, 255) for i in range(pixel_h): for j in range(pixel_v): greyscale = int(to_grayscale(*img[i][j])) img[i][j] = [ normalize(greyscale), normalize(greyscale + factor), normalize(greyscale + 2 * factor), ] return img if __name__ == "__main__": # read original image images = { percentage: imread("image_data/lena.jpg", 1) for percentage in (10, 20, 30, 40) } for percentage, img in images.items(): make_sepia(img, percentage) for percentage, img in images.items(): imshow(f"Original image with sepia (factor: {percentage})", img) waitKey(0) destroyAllWindows()
""" Implemented an algorithm using opencv to tone an image with sepia technique """ from cv2 import destroyAllWindows, imread, imshow, waitKey def make_sepia(img, factor: int): """ Function create sepia tone. Source: https://en.wikipedia.org/wiki/Sepia_(color) """ pixel_h, pixel_v = img.shape[0], img.shape[1] def to_grayscale(blue, green, red): """ Helper function to create pixel's greyscale representation Src: https://pl.wikipedia.org/wiki/YUV """ return 0.2126 * red + 0.587 * green + 0.114 * blue def normalize(value): """Helper function to normalize R/G/B value -> return 255 if value > 255""" return min(value, 255) for i in range(pixel_h): for j in range(pixel_v): greyscale = int(to_grayscale(*img[i][j])) img[i][j] = [ normalize(greyscale), normalize(greyscale + factor), normalize(greyscale + 2 * factor), ] return img if __name__ == "__main__": # read original image images = { percentage: imread("image_data/lena.jpg", 1) for percentage in (10, 20, 30, 40) } for percentage, img in images.items(): make_sepia(img, percentage) for percentage, img in images.items(): imshow(f"Original image with sepia (factor: {percentage})", img) waitKey(0) destroyAllWindows()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# Implementation of Circular Queue using linked lists # https://en.wikipedia.org/wiki/Circular_buffer from __future__ import annotations from typing import Any class CircularQueueLinkedList: """ Circular FIFO list with the given capacity (default queue length : 6) >>> cq = CircularQueueLinkedList(2) >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.enqueue('c') Traceback (most recent call last): ... Exception: Full Queue """ def __init__(self, initial_capacity: int = 6) -> None: self.front: Node | None = None self.rear: Node | None = None self.create_linked_list(initial_capacity) def create_linked_list(self, initial_capacity: int) -> None: current_node = Node() self.front = current_node self.rear = current_node previous_node = current_node for _ in range(1, initial_capacity): current_node = Node() previous_node.next = current_node current_node.prev = previous_node previous_node = current_node previous_node.next = self.front self.front.prev = previous_node def is_empty(self) -> bool: """ Checks where the queue is empty or not >>> cq = CircularQueueLinkedList() >>> cq.is_empty() True >>> cq.enqueue('a') >>> cq.is_empty() False >>> cq.dequeue() 'a' >>> cq.is_empty() True """ return ( self.front == self.rear and self.front is not None and self.front.data is None ) def first(self) -> Any | None: """ Returns the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.first() 'a' >>> cq.dequeue() 'a' >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('b') >>> cq.enqueue('c') >>> cq.first() 'b' """ self.check_can_perform_operation() return self.front.data if self.front else None def enqueue(self, data: Any) -> None: """ Saves data at the end of the queue >>> cq = CircularQueueLinkedList() >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.dequeue() 'a' >>> cq.dequeue() 'b' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ if self.rear is None: return self.check_is_full() if not self.is_empty(): self.rear = self.rear.next if self.rear: self.rear.data = data def dequeue(self) -> Any: """ Removes and retrieves the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.dequeue() 'a' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: data = self.front.data self.front.data = None return data old_front = self.front self.front = old_front.next data = old_front.data old_front.data = None return data def check_can_perform_operation(self) -> None: if self.is_empty(): raise Exception("Empty Queue") def check_is_full(self) -> None: if self.rear and self.rear.next == self.front: raise Exception("Full Queue") class Node: def __init__(self) -> None: self.data: Any | None = None self.next: Node | None = None self.prev: Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
# Implementation of Circular Queue using linked lists # https://en.wikipedia.org/wiki/Circular_buffer from __future__ import annotations from typing import Any class CircularQueueLinkedList: """ Circular FIFO list with the given capacity (default queue length : 6) >>> cq = CircularQueueLinkedList(2) >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.enqueue('c') Traceback (most recent call last): ... Exception: Full Queue """ def __init__(self, initial_capacity: int = 6) -> None: self.front: Node | None = None self.rear: Node | None = None self.create_linked_list(initial_capacity) def create_linked_list(self, initial_capacity: int) -> None: current_node = Node() self.front = current_node self.rear = current_node previous_node = current_node for _ in range(1, initial_capacity): current_node = Node() previous_node.next = current_node current_node.prev = previous_node previous_node = current_node previous_node.next = self.front self.front.prev = previous_node def is_empty(self) -> bool: """ Checks where the queue is empty or not >>> cq = CircularQueueLinkedList() >>> cq.is_empty() True >>> cq.enqueue('a') >>> cq.is_empty() False >>> cq.dequeue() 'a' >>> cq.is_empty() True """ return ( self.front == self.rear and self.front is not None and self.front.data is None ) def first(self) -> Any | None: """ Returns the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.first() 'a' >>> cq.dequeue() 'a' >>> cq.first() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('b') >>> cq.enqueue('c') >>> cq.first() 'b' """ self.check_can_perform_operation() return self.front.data if self.front else None def enqueue(self, data: Any) -> None: """ Saves data at the end of the queue >>> cq = CircularQueueLinkedList() >>> cq.enqueue('a') >>> cq.enqueue('b') >>> cq.dequeue() 'a' >>> cq.dequeue() 'b' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ if self.rear is None: return self.check_is_full() if not self.is_empty(): self.rear = self.rear.next if self.rear: self.rear.data = data def dequeue(self) -> Any: """ Removes and retrieves the first element of the queue >>> cq = CircularQueueLinkedList() >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue >>> cq.enqueue('a') >>> cq.dequeue() 'a' >>> cq.dequeue() Traceback (most recent call last): ... Exception: Empty Queue """ self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: data = self.front.data self.front.data = None return data old_front = self.front self.front = old_front.next data = old_front.data old_front.data = None return data def check_can_perform_operation(self) -> None: if self.is_empty(): raise Exception("Empty Queue") def check_is_full(self) -> None: if self.rear and self.rear.next == self.front: raise Exception("Full Queue") class Node: def __init__(self) -> None: self.data: Any | None = None self.next: Node | None = None self.prev: Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" The sum-of-subsetsproblem states that a set of non-negative integers, and a value M, determine all possible subsets of the given set whose summation sum equal to given M. Summation of the chosen numbers must be equal to given number M and one number can be used only once. """ from __future__ import annotations def generate_sum_of_subsets_soln(nums: list[int], max_sum: int) -> list[list[int]]: result: list[list[int]] = [] path: list[int] = [] num_index = 0 remaining_nums_sum = sum(nums) create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum) return result def create_state_space_tree( nums: list[int], max_sum: int, num_index: int, path: list[int], result: list[list[int]], remaining_nums_sum: int, ) -> None: """ Creates a state space tree to iterate through each branch using DFS. It terminates the branching of a node when any of the two conditions given below satisfy. This algorithm follows depth-fist-search and backtracks when the node is not branchable. """ if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum: return if sum(path) == max_sum: result.append(path) return for index in range(num_index, len(nums)): create_state_space_tree( nums, max_sum, index + 1, [*path, nums[index]], result, remaining_nums_sum - nums[index], ) """ remove the comment to take an input from the user print("Enter the elements") nums = list(map(int, input().split())) print("Enter max_sum sum") max_sum = int(input()) """ nums = [3, 34, 4, 12, 5, 2] max_sum = 9 result = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
""" The sum-of-subsetsproblem states that a set of non-negative integers, and a value M, determine all possible subsets of the given set whose summation sum equal to given M. Summation of the chosen numbers must be equal to given number M and one number can be used only once. """ from __future__ import annotations def generate_sum_of_subsets_soln(nums: list[int], max_sum: int) -> list[list[int]]: result: list[list[int]] = [] path: list[int] = [] num_index = 0 remaining_nums_sum = sum(nums) create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum) return result def create_state_space_tree( nums: list[int], max_sum: int, num_index: int, path: list[int], result: list[list[int]], remaining_nums_sum: int, ) -> None: """ Creates a state space tree to iterate through each branch using DFS. It terminates the branching of a node when any of the two conditions given below satisfy. This algorithm follows depth-fist-search and backtracks when the node is not branchable. """ if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum: return if sum(path) == max_sum: result.append(path) return for index in range(num_index, len(nums)): create_state_space_tree( nums, max_sum, index + 1, [*path, nums[index]], result, remaining_nums_sum - nums[index], ) """ remove the comment to take an input from the user print("Enter the elements") nums = list(map(int, input().split())) print("Enter max_sum sum") max_sum = int(input()) """ nums = [3, 34, 4, 12, 5, 2] max_sum = 9 result = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 27 https://projecteuler.net/problem=27 Problem Statement: Euler discovered the remarkable quadratic formula: n2 + n + 41 It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 412 + 41 + 41 is clearly divisible by 41. The incredible formula n2 − 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, −79 and 1601, is −126479. Considering quadratics of the form: n² + an + b, where |a| &lt; 1000 and |b| &lt; 1000 where |n| is the modulus/absolute value of ne.g. |11| = 11 and |−4| = 4 Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. """ import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. Returns boolean representing primality of given number num (i.e., if the result is true, then the number is indeed prime else it is not). >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(-10) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(a_limit: int = 1000, b_limit: int = 1000) -> int: """ >>> solution(1000, 1000) -59231 >>> solution(200, 1000) -59231 >>> solution(200, 200) -4925 >>> solution(-1000, 1000) 0 >>> solution(-1000, -1000) 0 """ longest = [0, 0, 0] # length, a, b for a in range((a_limit * -1) + 1, a_limit): for b in range(2, b_limit): if is_prime(b): count = 0 n = 0 while is_prime((n**2) + (a * n) + b): count += 1 n += 1 if count > longest[0]: longest = [count, a, b] ans = longest[1] * longest[2] return ans if __name__ == "__main__": print(solution(1000, 1000))
""" Project Euler Problem 27 https://projecteuler.net/problem=27 Problem Statement: Euler discovered the remarkable quadratic formula: n2 + n + 41 It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 412 + 41 + 41 is clearly divisible by 41. The incredible formula n2 − 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, −79 and 1601, is −126479. Considering quadratics of the form: n² + an + b, where |a| &lt; 1000 and |b| &lt; 1000 where |n| is the modulus/absolute value of ne.g. |11| = 11 and |−4| = 4 Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0. """ import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. Returns boolean representing primality of given number num (i.e., if the result is true, then the number is indeed prime else it is not). >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(2999) True >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(-10) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True def solution(a_limit: int = 1000, b_limit: int = 1000) -> int: """ >>> solution(1000, 1000) -59231 >>> solution(200, 1000) -59231 >>> solution(200, 200) -4925 >>> solution(-1000, 1000) 0 >>> solution(-1000, -1000) 0 """ longest = [0, 0, 0] # length, a, b for a in range((a_limit * -1) + 1, a_limit): for b in range(2, b_limit): if is_prime(b): count = 0 n = 0 while is_prime((n**2) + (a * n) + b): count += 1 n += 1 if count > longest[0]: longest = [count, a, b] ans = longest[1] * longest[2] return ans if __name__ == "__main__": print(solution(1000, 1000))
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# Reference: https://www.geeksforgeeks.org/position-of-rightmost-set-bit/ def get_index_of_rightmost_set_bit(number: int) -> int: """ Take in a positive integer 'number'. Returns the zero-based index of first set bit in that 'number' from right. Returns -1, If no set bit found. >>> get_index_of_rightmost_set_bit(0) -1 >>> get_index_of_rightmost_set_bit(5) 0 >>> get_index_of_rightmost_set_bit(36) 2 >>> get_index_of_rightmost_set_bit(8) 3 >>> get_index_of_rightmost_set_bit(-18) Traceback (most recent call last): ... ValueError: Input must be a non-negative integer >>> get_index_of_rightmost_set_bit('test') Traceback (most recent call last): ... ValueError: Input must be a non-negative integer >>> get_index_of_rightmost_set_bit(1.25) Traceback (most recent call last): ... ValueError: Input must be a non-negative integer """ if not isinstance(number, int) or number < 0: raise ValueError("Input must be a non-negative integer") intermediate = number & ~(number - 1) index = 0 while intermediate: intermediate >>= 1 index += 1 return index - 1 if __name__ == "__main__": """ Finding the index of rightmost set bit has some very peculiar use-cases, especially in finding missing or/and repeating numbers in a list of positive integers. """ import doctest doctest.testmod(verbose=True)
# Reference: https://www.geeksforgeeks.org/position-of-rightmost-set-bit/ def get_index_of_rightmost_set_bit(number: int) -> int: """ Take in a positive integer 'number'. Returns the zero-based index of first set bit in that 'number' from right. Returns -1, If no set bit found. >>> get_index_of_rightmost_set_bit(0) -1 >>> get_index_of_rightmost_set_bit(5) 0 >>> get_index_of_rightmost_set_bit(36) 2 >>> get_index_of_rightmost_set_bit(8) 3 >>> get_index_of_rightmost_set_bit(-18) Traceback (most recent call last): ... ValueError: Input must be a non-negative integer >>> get_index_of_rightmost_set_bit('test') Traceback (most recent call last): ... ValueError: Input must be a non-negative integer >>> get_index_of_rightmost_set_bit(1.25) Traceback (most recent call last): ... ValueError: Input must be a non-negative integer """ if not isinstance(number, int) or number < 0: raise ValueError("Input must be a non-negative integer") intermediate = number & ~(number - 1) index = 0 while intermediate: intermediate >>= 1 index += 1 return index - 1 if __name__ == "__main__": """ Finding the index of rightmost set bit has some very peculiar use-cases, especially in finding missing or/and repeating numbers in a list of positive integers. """ import doctest doctest.testmod(verbose=True)
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
#!/usr/bin/env python3 """ Build quantum teleportation circuit using three quantum bits and 1 classical bit. The main idea is to send one qubit from Alice to Bob using the entanglement properties. This experiment run in IBM Q simulator with 1000 shots. . References: https://en.wikipedia.org/wiki/Quantum_teleportation https://qiskit.org/textbook/ch-algorithms/teleportation.html """ import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def quantum_teleportation( theta: float = np.pi / 2, phi: float = np.pi / 2, lam: float = np.pi / 2 ) -> qiskit.result.counts.Counts: """ # >>> quantum_teleportation() #{'00': 500, '11': 500} # ideally # ┌─────────────────┐ ┌───┐ #qr_0: ┤ U(π/2,π/2,π/2) ├───────■──┤ H ├─■───────── # └──────┬───┬──────┘ ┌─┴─┐└───┘ │ #qr_1: ───────┤ H ├─────────■──┤ X ├──────┼───■───── # └───┘ ┌─┴─┐└───┘ │ ┌─┴─┐┌─┐ #qr_2: ───────────────────┤ X ├───────────■─┤ X ├┤M├ # └───┘ └───┘└╥┘ #cr: 1/═══════════════════════════════════════════╩═ Args: theta (float): Single qubit rotation U Gate theta parameter. Default to np.pi/2 phi (float): Single qubit rotation U Gate phi parameter. Default to np.pi/2 lam (float): Single qubit rotation U Gate lam parameter. Default to np.pi/2 Returns: qiskit.result.counts.Counts: Teleported qubit counts. """ qr = QuantumRegister(3, "qr") # Define the number of quantum bits cr = ClassicalRegister(1, "cr") # Define the number of classical bits quantum_circuit = QuantumCircuit(qr, cr) # Define the quantum circuit. # Build the circuit quantum_circuit.u(theta, phi, lam, 0) # Quantum State to teleport quantum_circuit.h(1) # add hadamard gate quantum_circuit.cx( 1, 2 ) # add control gate with qubit 1 as control and 2 as target. quantum_circuit.cx(0, 1) quantum_circuit.h(0) quantum_circuit.cz(0, 2) # add control z gate. quantum_circuit.cx(1, 2) quantum_circuit.measure([2], [0]) # measure the qubit. # Simulate the circuit using qasm simulator backend = Aer.get_backend("aer_simulator") job = execute(quantum_circuit, backend, shots=1000) return job.result().get_counts(quantum_circuit) if __name__ == "__main__": print( "Total count for teleported state is: " f"{quantum_teleportation(np.pi/2, np.pi/2, np.pi/2)}" )
#!/usr/bin/env python3 """ Build quantum teleportation circuit using three quantum bits and 1 classical bit. The main idea is to send one qubit from Alice to Bob using the entanglement properties. This experiment run in IBM Q simulator with 1000 shots. . References: https://en.wikipedia.org/wiki/Quantum_teleportation https://qiskit.org/textbook/ch-algorithms/teleportation.html """ import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def quantum_teleportation( theta: float = np.pi / 2, phi: float = np.pi / 2, lam: float = np.pi / 2 ) -> qiskit.result.counts.Counts: """ # >>> quantum_teleportation() #{'00': 500, '11': 500} # ideally # ┌─────────────────┐ ┌───┐ #qr_0: ┤ U(π/2,π/2,π/2) ├───────■──┤ H ├─■───────── # └──────┬───┬──────┘ ┌─┴─┐└───┘ │ #qr_1: ───────┤ H ├─────────■──┤ X ├──────┼───■───── # └───┘ ┌─┴─┐└───┘ │ ┌─┴─┐┌─┐ #qr_2: ───────────────────┤ X ├───────────■─┤ X ├┤M├ # └───┘ └───┘└╥┘ #cr: 1/═══════════════════════════════════════════╩═ Args: theta (float): Single qubit rotation U Gate theta parameter. Default to np.pi/2 phi (float): Single qubit rotation U Gate phi parameter. Default to np.pi/2 lam (float): Single qubit rotation U Gate lam parameter. Default to np.pi/2 Returns: qiskit.result.counts.Counts: Teleported qubit counts. """ qr = QuantumRegister(3, "qr") # Define the number of quantum bits cr = ClassicalRegister(1, "cr") # Define the number of classical bits quantum_circuit = QuantumCircuit(qr, cr) # Define the quantum circuit. # Build the circuit quantum_circuit.u(theta, phi, lam, 0) # Quantum State to teleport quantum_circuit.h(1) # add hadamard gate quantum_circuit.cx( 1, 2 ) # add control gate with qubit 1 as control and 2 as target. quantum_circuit.cx(0, 1) quantum_circuit.h(0) quantum_circuit.cz(0, 2) # add control z gate. quantum_circuit.cx(1, 2) quantum_circuit.measure([2], [0]) # measure the qubit. # Simulate the circuit using qasm simulator backend = Aer.get_backend("aer_simulator") job = execute(quantum_circuit, backend, shots=1000) return job.result().get_counts(quantum_circuit) if __name__ == "__main__": print( "Total count for teleported state is: " f"{quantum_teleportation(np.pi/2, np.pi/2, np.pi/2)}" )
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# https://en.wikipedia.org/wiki/Wheatstone_bridge from __future__ import annotations def wheatstone_solver( resistance_1: float, resistance_2: float, resistance_3: float ) -> float: """ This function can calculate the unknown resistance in an wheatstone network, given that the three other resistances in the network are known. The formula to calculate the same is: --------------- |Rx=(R2/R1)*R3| --------------- Usage examples: >>> wheatstone_solver(resistance_1=2, resistance_2=4, resistance_3=5) 10.0 >>> wheatstone_solver(resistance_1=356, resistance_2=234, resistance_3=976) 641.5280898876405 >>> wheatstone_solver(resistance_1=2, resistance_2=-1, resistance_3=2) Traceback (most recent call last): ... ValueError: All resistance values must be positive >>> wheatstone_solver(resistance_1=0, resistance_2=0, resistance_3=2) Traceback (most recent call last): ... ValueError: All resistance values must be positive """ if resistance_1 <= 0 or resistance_2 <= 0 or resistance_3 <= 0: raise ValueError("All resistance values must be positive") else: return float((resistance_2 / resistance_1) * resistance_3) if __name__ == "__main__": import doctest doctest.testmod()
# https://en.wikipedia.org/wiki/Wheatstone_bridge from __future__ import annotations def wheatstone_solver( resistance_1: float, resistance_2: float, resistance_3: float ) -> float: """ This function can calculate the unknown resistance in an wheatstone network, given that the three other resistances in the network are known. The formula to calculate the same is: --------------- |Rx=(R2/R1)*R3| --------------- Usage examples: >>> wheatstone_solver(resistance_1=2, resistance_2=4, resistance_3=5) 10.0 >>> wheatstone_solver(resistance_1=356, resistance_2=234, resistance_3=976) 641.5280898876405 >>> wheatstone_solver(resistance_1=2, resistance_2=-1, resistance_3=2) Traceback (most recent call last): ... ValueError: All resistance values must be positive >>> wheatstone_solver(resistance_1=0, resistance_2=0, resistance_3=2) Traceback (most recent call last): ... ValueError: All resistance values must be positive """ if resistance_1 <= 0 or resistance_2 <= 0 or resistance_3 <= 0: raise ValueError("All resistance values must be positive") else: return float((resistance_2 / resistance_1) * resistance_3) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from copy import deepcopy class FenwickTree: """ Fenwick Tree More info: https://en.wikipedia.org/wiki/Fenwick_tree """ def __init__(self, arr: list[int] | None = None, size: int | None = None) -> None: """ Constructor for the Fenwick tree Parameters: arr (list): list of elements to initialize the tree with (optional) size (int): size of the Fenwick tree (if arr is None) """ if arr is None and size is not None: self.size = size self.tree = [0] * size elif arr is not None: self.init(arr) else: raise ValueError("Either arr or size must be specified") def init(self, arr: list[int]) -> None: """ Initialize the Fenwick tree with arr in O(N) Parameters: arr (list): list of elements to initialize the tree with Returns: None >>> a = [1, 2, 3, 4, 5] >>> f1 = FenwickTree(a) >>> f2 = FenwickTree(size=len(a)) >>> for index, value in enumerate(a): ... f2.add(index, value) >>> f1.tree == f2.tree True """ self.size = len(arr) self.tree = deepcopy(arr) for i in range(1, self.size): j = self.next_(i) if j < self.size: self.tree[j] += self.tree[i] def get_array(self) -> list[int]: """ Get the Normal Array of the Fenwick tree in O(N) Returns: list: Normal Array of the Fenwick tree >>> a = [i for i in range(128)] >>> f = FenwickTree(a) >>> f.get_array() == a True """ arr = self.tree[:] for i in range(self.size - 1, 0, -1): j = self.next_(i) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def next_(index: int) -> int: return index + (index & (-index)) @staticmethod def prev(index: int) -> int: return index - (index & (-index)) def add(self, index: int, value: int) -> None: """ Add a value to index in O(lg N) Parameters: index (int): index to add value to value (int): value to add to index Returns: None >>> f = FenwickTree([1, 2, 3, 4, 5]) >>> f.add(0, 1) >>> f.add(1, 2) >>> f.add(2, 3) >>> f.add(3, 4) >>> f.add(4, 5) >>> f.get_array() [2, 4, 6, 8, 10] """ if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value index = self.next_(index) def update(self, index: int, value: int) -> None: """ Set the value of index in O(lg N) Parameters: index (int): index to set value to value (int): value to set in index Returns: None >>> f = FenwickTree([5, 4, 3, 2, 1]) >>> f.update(0, 1) >>> f.update(1, 2) >>> f.update(2, 3) >>> f.update(3, 4) >>> f.update(4, 5) >>> f.get_array() [1, 2, 3, 4, 5] """ self.add(index, value - self.get(index)) def prefix(self, right: int) -> int: """ Prefix sum of all elements in [0, right) in O(lg N) Parameters: right (int): right bound of the query (exclusive) Returns: int: sum of all elements in [0, right) >>> a = [i for i in range(128)] >>> f = FenwickTree(a) >>> res = True >>> for i in range(len(a)): ... res = res and f.prefix(i) == sum(a[:i]) >>> res True """ if right == 0: return 0 result = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] right = self.prev(right) return result def query(self, left: int, right: int) -> int: """ Query the sum of all elements in [left, right) in O(lg N) Parameters: left (int): left bound of the query (inclusive) right (int): right bound of the query (exclusive) Returns: int: sum of all elements in [left, right) >>> a = [i for i in range(128)] >>> f = FenwickTree(a) >>> res = True >>> for i in range(len(a)): ... for j in range(i + 1, len(a)): ... res = res and f.query(i, j) == sum(a[i:j]) >>> res True """ return self.prefix(right) - self.prefix(left) def get(self, index: int) -> int: """ Get value at index in O(lg N) Parameters: index (int): index to get the value Returns: int: Value of element at index >>> a = [i for i in range(128)] >>> f = FenwickTree(a) >>> res = True >>> for i in range(len(a)): ... res = res and f.get(i) == a[i] >>> res True """ return self.query(index, index + 1) def rank_query(self, value: int) -> int: """ Find the largest index with prefix(i) <= value in O(lg N) NOTE: Requires that all values are non-negative! Parameters: value (int): value to find the largest index of Returns: -1: if value is smaller than all elements in prefix sum int: largest index with prefix(i) <= value >>> f = FenwickTree([1, 2, 0, 3, 0, 5]) >>> f.rank_query(0) -1 >>> f.rank_query(2) 0 >>> f.rank_query(1) 0 >>> f.rank_query(3) 2 >>> f.rank_query(5) 2 >>> f.rank_query(6) 4 >>> f.rank_query(11) 5 """ value -= self.tree[0] if value < 0: return -1 j = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 i = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
from copy import deepcopy class FenwickTree: """ Fenwick Tree More info: https://en.wikipedia.org/wiki/Fenwick_tree """ def __init__(self, arr: list[int] | None = None, size: int | None = None) -> None: """ Constructor for the Fenwick tree Parameters: arr (list): list of elements to initialize the tree with (optional) size (int): size of the Fenwick tree (if arr is None) """ if arr is None and size is not None: self.size = size self.tree = [0] * size elif arr is not None: self.init(arr) else: raise ValueError("Either arr or size must be specified") def init(self, arr: list[int]) -> None: """ Initialize the Fenwick tree with arr in O(N) Parameters: arr (list): list of elements to initialize the tree with Returns: None >>> a = [1, 2, 3, 4, 5] >>> f1 = FenwickTree(a) >>> f2 = FenwickTree(size=len(a)) >>> for index, value in enumerate(a): ... f2.add(index, value) >>> f1.tree == f2.tree True """ self.size = len(arr) self.tree = deepcopy(arr) for i in range(1, self.size): j = self.next_(i) if j < self.size: self.tree[j] += self.tree[i] def get_array(self) -> list[int]: """ Get the Normal Array of the Fenwick tree in O(N) Returns: list: Normal Array of the Fenwick tree >>> a = [i for i in range(128)] >>> f = FenwickTree(a) >>> f.get_array() == a True """ arr = self.tree[:] for i in range(self.size - 1, 0, -1): j = self.next_(i) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def next_(index: int) -> int: return index + (index & (-index)) @staticmethod def prev(index: int) -> int: return index - (index & (-index)) def add(self, index: int, value: int) -> None: """ Add a value to index in O(lg N) Parameters: index (int): index to add value to value (int): value to add to index Returns: None >>> f = FenwickTree([1, 2, 3, 4, 5]) >>> f.add(0, 1) >>> f.add(1, 2) >>> f.add(2, 3) >>> f.add(3, 4) >>> f.add(4, 5) >>> f.get_array() [2, 4, 6, 8, 10] """ if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value index = self.next_(index) def update(self, index: int, value: int) -> None: """ Set the value of index in O(lg N) Parameters: index (int): index to set value to value (int): value to set in index Returns: None >>> f = FenwickTree([5, 4, 3, 2, 1]) >>> f.update(0, 1) >>> f.update(1, 2) >>> f.update(2, 3) >>> f.update(3, 4) >>> f.update(4, 5) >>> f.get_array() [1, 2, 3, 4, 5] """ self.add(index, value - self.get(index)) def prefix(self, right: int) -> int: """ Prefix sum of all elements in [0, right) in O(lg N) Parameters: right (int): right bound of the query (exclusive) Returns: int: sum of all elements in [0, right) >>> a = [i for i in range(128)] >>> f = FenwickTree(a) >>> res = True >>> for i in range(len(a)): ... res = res and f.prefix(i) == sum(a[:i]) >>> res True """ if right == 0: return 0 result = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] right = self.prev(right) return result def query(self, left: int, right: int) -> int: """ Query the sum of all elements in [left, right) in O(lg N) Parameters: left (int): left bound of the query (inclusive) right (int): right bound of the query (exclusive) Returns: int: sum of all elements in [left, right) >>> a = [i for i in range(128)] >>> f = FenwickTree(a) >>> res = True >>> for i in range(len(a)): ... for j in range(i + 1, len(a)): ... res = res and f.query(i, j) == sum(a[i:j]) >>> res True """ return self.prefix(right) - self.prefix(left) def get(self, index: int) -> int: """ Get value at index in O(lg N) Parameters: index (int): index to get the value Returns: int: Value of element at index >>> a = [i for i in range(128)] >>> f = FenwickTree(a) >>> res = True >>> for i in range(len(a)): ... res = res and f.get(i) == a[i] >>> res True """ return self.query(index, index + 1) def rank_query(self, value: int) -> int: """ Find the largest index with prefix(i) <= value in O(lg N) NOTE: Requires that all values are non-negative! Parameters: value (int): value to find the largest index of Returns: -1: if value is smaller than all elements in prefix sum int: largest index with prefix(i) <= value >>> f = FenwickTree([1, 2, 0, 3, 0, 5]) >>> f.rank_query(0) -1 >>> f.rank_query(2) 0 >>> f.rank_query(1) 0 >>> f.rank_query(3) 2 >>> f.rank_query(5) 2 >>> f.rank_query(6) 4 >>> f.rank_query(11) 5 """ value -= self.tree[0] if value < 0: return -1 j = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 i = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Pure Python implementation of the jump search algorithm. This algorithm iterates through a sorted collection with a step of n^(1/2), until the element compared is bigger than the one searched. It will then perform a linear search until it matches the wanted number. If not found, it returns -1. https://en.wikipedia.org/wiki/Jump_search """ import math from collections.abc import Sequence from typing import Any, Protocol, TypeVar class Comparable(Protocol): def __lt__(self, other: Any, /) -> bool: ... T = TypeVar("T", bound=Comparable) def jump_search(arr: Sequence[T], item: T) -> int: """ Python implementation of the jump search algorithm. Return the index if the `item` is found, otherwise return -1. Examples: >>> jump_search([0, 1, 2, 3, 4, 5], 3) 3 >>> jump_search([-5, -2, -1], -1) 2 >>> jump_search([0, 5, 10, 20], 8) -1 >>> jump_search([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610], 55) 10 >>> jump_search(["aa", "bb", "cc", "dd", "ee", "ff"], "ee") 4 """ arr_size = len(arr) block_size = int(math.sqrt(arr_size)) prev = 0 step = block_size while arr[min(step, arr_size) - 1] < item: prev = step step += block_size if prev >= arr_size: return -1 while arr[prev] < item: prev += 1 if prev == min(step, arr_size): return -1 if arr[prev] == item: return prev return -1 if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() array = [int(item) for item in user_input.split(",")] x = int(input("Enter the number to be searched:\n")) res = jump_search(array, x) if res == -1: print("Number not found!") else: print(f"Number {x} is at index {res}")
""" Pure Python implementation of the jump search algorithm. This algorithm iterates through a sorted collection with a step of n^(1/2), until the element compared is bigger than the one searched. It will then perform a linear search until it matches the wanted number. If not found, it returns -1. https://en.wikipedia.org/wiki/Jump_search """ import math from collections.abc import Sequence from typing import Any, Protocol, TypeVar class Comparable(Protocol): def __lt__(self, other: Any, /) -> bool: ... T = TypeVar("T", bound=Comparable) def jump_search(arr: Sequence[T], item: T) -> int: """ Python implementation of the jump search algorithm. Return the index if the `item` is found, otherwise return -1. Examples: >>> jump_search([0, 1, 2, 3, 4, 5], 3) 3 >>> jump_search([-5, -2, -1], -1) 2 >>> jump_search([0, 5, 10, 20], 8) -1 >>> jump_search([0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610], 55) 10 >>> jump_search(["aa", "bb", "cc", "dd", "ee", "ff"], "ee") 4 """ arr_size = len(arr) block_size = int(math.sqrt(arr_size)) prev = 0 step = block_size while arr[min(step, arr_size) - 1] < item: prev = step step += block_size if prev >= arr_size: return -1 while arr[prev] < item: prev += 1 if prev == min(step, arr_size): return -1 if arr[prev] == item: return prev return -1 if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() array = [int(item) for item in user_input.split(",")] x = int(input("Enter the number to be searched:\n")) res = jump_search(array, x) if res == -1: print("Number not found!") else: print(f"Number {x} is at index {res}")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Test cases: Do you want to enter your denominations ? (Y/N) :N Enter the change you want to make in Indian Currency: 987 Following is minimal change for 987 : 500 100 100 100 100 50 20 10 5 2 Do you want to enter your denominations ? (Y/N) :Y Enter number of denomination:10 1 5 10 20 50 100 200 500 1000 2000 Enter the change you want to make: 18745 Following is minimal change for 18745 : 2000 2000 2000 2000 2000 2000 2000 2000 2000 500 200 20 20 5 Do you want to enter your denominations ? (Y/N) :N Enter the change you want to make: 0 The total value cannot be zero or negative. Do you want to enter your denominations ? (Y/N) :N Enter the change you want to make: -98 The total value cannot be zero or negative. Do you want to enter your denominations ? (Y/N) :Y Enter number of denomination:5 1 5 100 500 1000 Enter the change you want to make: 456 Following is minimal change for 456 : 100 100 100 100 5 5 5 5 5 5 5 5 5 5 5 1 """ def find_minimum_change(denominations: list[int], value: str) -> list[int]: """ Find the minimum change from the given denominations and value >>> find_minimum_change([1, 5, 10, 20, 50, 100, 200, 500, 1000,2000], 18745) [2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 500, 200, 20, 20, 5] >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], 987) [500, 100, 100, 100, 100, 50, 20, 10, 5, 2] >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], 0) [] >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], -98) [] >>> find_minimum_change([1, 5, 100, 500, 1000], 456) [100, 100, 100, 100, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1] """ total_value = int(value) # Initialize Result answer = [] # Traverse through all denomination for denomination in reversed(denominations): # Find denominations while int(total_value) >= int(denomination): total_value -= int(denomination) answer.append(denomination) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": denominations = [] value = "0" if ( input("Do you want to enter your denominations ? (yY/n): ").strip().lower() == "y" ): n = int(input("Enter the number of denominations you want to add: ").strip()) for i in range(n): denominations.append(int(input(f"Denomination {i}: ").strip())) value = input("Enter the change you want to make in Indian Currency: ").strip() else: # All denominations of Indian Currency if user does not enter denominations = [1, 2, 5, 10, 20, 50, 100, 500, 2000] value = input("Enter the change you want to make: ").strip() if int(value) == 0 or int(value) < 0: print("The total value cannot be zero or negative.") else: print(f"Following is minimal change for {value}: ") answer = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=" ")
""" Test cases: Do you want to enter your denominations ? (Y/N) :N Enter the change you want to make in Indian Currency: 987 Following is minimal change for 987 : 500 100 100 100 100 50 20 10 5 2 Do you want to enter your denominations ? (Y/N) :Y Enter number of denomination:10 1 5 10 20 50 100 200 500 1000 2000 Enter the change you want to make: 18745 Following is minimal change for 18745 : 2000 2000 2000 2000 2000 2000 2000 2000 2000 500 200 20 20 5 Do you want to enter your denominations ? (Y/N) :N Enter the change you want to make: 0 The total value cannot be zero or negative. Do you want to enter your denominations ? (Y/N) :N Enter the change you want to make: -98 The total value cannot be zero or negative. Do you want to enter your denominations ? (Y/N) :Y Enter number of denomination:5 1 5 100 500 1000 Enter the change you want to make: 456 Following is minimal change for 456 : 100 100 100 100 5 5 5 5 5 5 5 5 5 5 5 1 """ def find_minimum_change(denominations: list[int], value: str) -> list[int]: """ Find the minimum change from the given denominations and value >>> find_minimum_change([1, 5, 10, 20, 50, 100, 200, 500, 1000,2000], 18745) [2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 500, 200, 20, 20, 5] >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], 987) [500, 100, 100, 100, 100, 50, 20, 10, 5, 2] >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], 0) [] >>> find_minimum_change([1, 2, 5, 10, 20, 50, 100, 500, 2000], -98) [] >>> find_minimum_change([1, 5, 100, 500, 1000], 456) [100, 100, 100, 100, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1] """ total_value = int(value) # Initialize Result answer = [] # Traverse through all denomination for denomination in reversed(denominations): # Find denominations while int(total_value) >= int(denomination): total_value -= int(denomination) answer.append(denomination) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": denominations = [] value = "0" if ( input("Do you want to enter your denominations ? (yY/n): ").strip().lower() == "y" ): n = int(input("Enter the number of denominations you want to add: ").strip()) for i in range(n): denominations.append(int(input(f"Denomination {i}: ").strip())) value = input("Enter the change you want to make in Indian Currency: ").strip() else: # All denominations of Indian Currency if user does not enter denominations = [1, 2, 5, 10, 20, 50, 100, 500, 2000] value = input("Enter the change you want to make: ").strip() if int(value) == 0 or int(value) < 0: print("The total value cannot be zero or negative.") else: print(f"Following is minimal change for {value}: ") answer = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=" ")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 6: https://projecteuler.net/problem=6 Sum square difference The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ import math def solution(n: int = 100) -> int: """ Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. >>> solution(10) 2640 >>> solution(15) 13160 >>> solution(20) 41230 >>> solution(50) 1582700 """ sum_of_squares = sum(i * i for i in range(1, n + 1)) square_of_sum = int(math.pow(sum(range(1, n + 1)), 2)) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 6: https://projecteuler.net/problem=6 Sum square difference The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ import math def solution(n: int = 100) -> int: """ Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. >>> solution(10) 2640 >>> solution(15) 13160 >>> solution(20) 41230 >>> solution(50) 1582700 """ sum_of_squares = sum(i * i for i in range(1, n + 1)) square_of_sum = int(math.pow(sum(range(1, n + 1)), 2)) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 6: https://projecteuler.net/problem=6 Sum square difference The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ def solution(n: int = 100) -> int: """ Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. >>> solution(10) 2640 >>> solution(15) 13160 >>> solution(20) 41230 >>> solution(50) 1582700 """ sum_of_squares = n * (n + 1) * (2 * n + 1) / 6 square_of_sum = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 6: https://projecteuler.net/problem=6 Sum square difference The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 55^2 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. """ def solution(n: int = 100) -> int: """ Returns the difference between the sum of the squares of the first n natural numbers and the square of the sum. >>> solution(10) 2640 >>> solution(15) 13160 >>> solution(20) 41230 >>> solution(50) 1582700 """ sum_of_squares = n * (n + 1) * (2 * n + 1) / 6 square_of_sum = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Hash map with open addressing. https://en.wikipedia.org/wiki/Hash_table Another hash map implementation, with a good explanation. Modern Dictionaries by Raymond Hettinger https://www.youtube.com/watch?v=p33CVV29OG8 """ from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar KEY = TypeVar("KEY") VAL = TypeVar("VAL") @dataclass(frozen=True, slots=True) class _Item(Generic[KEY, VAL]): key: KEY val: VAL class _DeletedItem(_Item): def __init__(self) -> None: super().__init__(None, None) def __bool__(self) -> bool: return False _deleted = _DeletedItem() class HashMap(MutableMapping[KEY, VAL]): """ Hash map with open addressing. """ def __init__( self, initial_block_size: int = 8, capacity_factor: float = 0.75 ) -> None: self._initial_block_size = initial_block_size self._buckets: list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 self._capacity_factor = capacity_factor self._len = 0 def _get_bucket_index(self, key: KEY) -> int: return hash(key) % len(self._buckets) def _get_next_ind(self, ind: int) -> int: """ Get next index. Implements linear open addressing. """ return (ind + 1) % len(self._buckets) def _try_set(self, ind: int, key: KEY, val: VAL) -> bool: """ Try to add value to the bucket. If bucket is empty or key is the same, does insert and return True. If bucket has another key or deleted placeholder, that means that we need to check next bucket. """ stored = self._buckets[ind] if not stored: self._buckets[ind] = _Item(key, val) self._len += 1 return True elif stored.key == key: self._buckets[ind] = _Item(key, val) return True else: return False def _is_full(self) -> bool: """ Return true if we have reached safe capacity. So we need to increase the number of buckets to avoid collisions. """ limit = len(self._buckets) * self._capacity_factor return len(self) >= int(limit) def _is_sparse(self) -> bool: """Return true if we need twice fewer buckets when we have now.""" if len(self._buckets) <= self._initial_block_size: return False limit = len(self._buckets) * self._capacity_factor / 2 return len(self) < limit def _resize(self, new_size: int) -> None: old_buckets = self._buckets self._buckets = [None] * new_size self._len = 0 for item in old_buckets: if item: self._add_item(item.key, item.val) def _size_up(self) -> None: self._resize(len(self._buckets) * 2) def _size_down(self) -> None: self._resize(len(self._buckets) // 2) def _iterate_buckets(self, key: KEY) -> Iterator[int]: ind = self._get_bucket_index(key) for _ in range(len(self._buckets)): yield ind ind = self._get_next_ind(ind) def _add_item(self, key: KEY, val: VAL) -> None: for ind in self._iterate_buckets(key): if self._try_set(ind, key, val): break def __setitem__(self, key: KEY, val: VAL) -> None: if self._is_full(): self._size_up() self._add_item(key, val) def __delitem__(self, key: KEY) -> None: for ind in self._iterate_buckets(key): item = self._buckets[ind] if item is None: raise KeyError(key) if item is _deleted: continue if item.key == key: self._buckets[ind] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__(self, key: KEY) -> VAL: for ind in self._iterate_buckets(key): item = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(key) def __len__(self) -> int: return self._len def __iter__(self) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__(self) -> str: val_string = " ,".join( f"{item.key}: {item.val}" for item in self._buckets if item ) return f"HashMap({val_string})"
""" Hash map with open addressing. https://en.wikipedia.org/wiki/Hash_table Another hash map implementation, with a good explanation. Modern Dictionaries by Raymond Hettinger https://www.youtube.com/watch?v=p33CVV29OG8 """ from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar KEY = TypeVar("KEY") VAL = TypeVar("VAL") @dataclass(frozen=True, slots=True) class _Item(Generic[KEY, VAL]): key: KEY val: VAL class _DeletedItem(_Item): def __init__(self) -> None: super().__init__(None, None) def __bool__(self) -> bool: return False _deleted = _DeletedItem() class HashMap(MutableMapping[KEY, VAL]): """ Hash map with open addressing. """ def __init__( self, initial_block_size: int = 8, capacity_factor: float = 0.75 ) -> None: self._initial_block_size = initial_block_size self._buckets: list[_Item | None] = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 self._capacity_factor = capacity_factor self._len = 0 def _get_bucket_index(self, key: KEY) -> int: return hash(key) % len(self._buckets) def _get_next_ind(self, ind: int) -> int: """ Get next index. Implements linear open addressing. """ return (ind + 1) % len(self._buckets) def _try_set(self, ind: int, key: KEY, val: VAL) -> bool: """ Try to add value to the bucket. If bucket is empty or key is the same, does insert and return True. If bucket has another key or deleted placeholder, that means that we need to check next bucket. """ stored = self._buckets[ind] if not stored: self._buckets[ind] = _Item(key, val) self._len += 1 return True elif stored.key == key: self._buckets[ind] = _Item(key, val) return True else: return False def _is_full(self) -> bool: """ Return true if we have reached safe capacity. So we need to increase the number of buckets to avoid collisions. """ limit = len(self._buckets) * self._capacity_factor return len(self) >= int(limit) def _is_sparse(self) -> bool: """Return true if we need twice fewer buckets when we have now.""" if len(self._buckets) <= self._initial_block_size: return False limit = len(self._buckets) * self._capacity_factor / 2 return len(self) < limit def _resize(self, new_size: int) -> None: old_buckets = self._buckets self._buckets = [None] * new_size self._len = 0 for item in old_buckets: if item: self._add_item(item.key, item.val) def _size_up(self) -> None: self._resize(len(self._buckets) * 2) def _size_down(self) -> None: self._resize(len(self._buckets) // 2) def _iterate_buckets(self, key: KEY) -> Iterator[int]: ind = self._get_bucket_index(key) for _ in range(len(self._buckets)): yield ind ind = self._get_next_ind(ind) def _add_item(self, key: KEY, val: VAL) -> None: for ind in self._iterate_buckets(key): if self._try_set(ind, key, val): break def __setitem__(self, key: KEY, val: VAL) -> None: if self._is_full(): self._size_up() self._add_item(key, val) def __delitem__(self, key: KEY) -> None: for ind in self._iterate_buckets(key): item = self._buckets[ind] if item is None: raise KeyError(key) if item is _deleted: continue if item.key == key: self._buckets[ind] = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__(self, key: KEY) -> VAL: for ind in self._iterate_buckets(key): item = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(key) def __len__(self) -> int: return self._len def __iter__(self) -> Iterator[KEY]: yield from (item.key for item in self._buckets if item) def __repr__(self) -> str: val_string = " ,".join( f"{item.key}: {item.val}" for item in self._buckets if item ) return f"HashMap({val_string})"
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from graphs.minimum_spanning_tree_kruskal import kruskal def test_kruskal_successful_result(): num_nodes = 9 edges = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] result = kruskal(num_nodes, edges) expected = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(expected) == sorted(result)
from graphs.minimum_spanning_tree_kruskal import kruskal def test_kruskal_successful_result(): num_nodes = 9 edges = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] result = kruskal(num_nodes, edges) expected = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(expected) == sorted(result)
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
"""Convert a Decimal Number to a Binary Number.""" def decimal_to_binary_iterative(num: int) -> str: """ Convert an Integer Decimal Number to a Binary Number as str. >>> decimal_to_binary_iterative(0) '0b0' >>> decimal_to_binary_iterative(2) '0b10' >>> decimal_to_binary_iterative(7) '0b111' >>> decimal_to_binary_iterative(35) '0b100011' >>> # negatives work too >>> decimal_to_binary_iterative(-2) '-0b10' >>> # other floats will error >>> decimal_to_binary_iterative(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> # strings will error as well >>> decimal_to_binary_iterative('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'str' object cannot be interpreted as an integer """ if isinstance(num, float): raise TypeError("'float' object cannot be interpreted as an integer") if isinstance(num, str): raise TypeError("'str' object cannot be interpreted as an integer") if num == 0: return "0b0" negative = False if num < 0: negative = True num = -num binary: list[int] = [] while num > 0: binary.insert(0, num % 2) num >>= 1 if negative: return "-0b" + "".join(str(e) for e in binary) return "0b" + "".join(str(e) for e in binary) def decimal_to_binary_recursive_helper(decimal: int) -> str: """ Take a positive integer value and return its binary equivalent. >>> decimal_to_binary_recursive_helper(1000) '1111101000' >>> decimal_to_binary_recursive_helper("72") '1001000' >>> decimal_to_binary_recursive_helper("number") Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: 'number' """ decimal = int(decimal) if decimal in (0, 1): # Exit cases for the recursion return str(decimal) div, mod = divmod(decimal, 2) return decimal_to_binary_recursive_helper(div) + str(mod) def decimal_to_binary_recursive(number: str) -> str: """ Take an integer value and raise ValueError for wrong inputs, call the function above and return the output with prefix "0b" & "-0b" for positive and negative integers respectively. >>> decimal_to_binary_recursive(0) '0b0' >>> decimal_to_binary_recursive(40) '0b101000' >>> decimal_to_binary_recursive(-40) '-0b101000' >>> decimal_to_binary_recursive(40.8) Traceback (most recent call last): ... ValueError: Input value is not an integer >>> decimal_to_binary_recursive("forty") Traceback (most recent call last): ... ValueError: Input value is not an integer """ number = str(number).strip() if not number: raise ValueError("No input value was provided") negative = "-" if number.startswith("-") else "" number = number.lstrip("-") if not number.isnumeric(): raise ValueError("Input value is not an integer") return f"{negative}0b{decimal_to_binary_recursive_helper(int(number))}" if __name__ == "__main__": import doctest doctest.testmod() print(decimal_to_binary_recursive(input("Input a decimal number: ")))
"""Convert a Decimal Number to a Binary Number.""" def decimal_to_binary_iterative(num: int) -> str: """ Convert an Integer Decimal Number to a Binary Number as str. >>> decimal_to_binary_iterative(0) '0b0' >>> decimal_to_binary_iterative(2) '0b10' >>> decimal_to_binary_iterative(7) '0b111' >>> decimal_to_binary_iterative(35) '0b100011' >>> # negatives work too >>> decimal_to_binary_iterative(-2) '-0b10' >>> # other floats will error >>> decimal_to_binary_iterative(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object cannot be interpreted as an integer >>> # strings will error as well >>> decimal_to_binary_iterative('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'str' object cannot be interpreted as an integer """ if isinstance(num, float): raise TypeError("'float' object cannot be interpreted as an integer") if isinstance(num, str): raise TypeError("'str' object cannot be interpreted as an integer") if num == 0: return "0b0" negative = False if num < 0: negative = True num = -num binary: list[int] = [] while num > 0: binary.insert(0, num % 2) num >>= 1 if negative: return "-0b" + "".join(str(e) for e in binary) return "0b" + "".join(str(e) for e in binary) def decimal_to_binary_recursive_helper(decimal: int) -> str: """ Take a positive integer value and return its binary equivalent. >>> decimal_to_binary_recursive_helper(1000) '1111101000' >>> decimal_to_binary_recursive_helper("72") '1001000' >>> decimal_to_binary_recursive_helper("number") Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: 'number' """ decimal = int(decimal) if decimal in (0, 1): # Exit cases for the recursion return str(decimal) div, mod = divmod(decimal, 2) return decimal_to_binary_recursive_helper(div) + str(mod) def decimal_to_binary_recursive(number: str) -> str: """ Take an integer value and raise ValueError for wrong inputs, call the function above and return the output with prefix "0b" & "-0b" for positive and negative integers respectively. >>> decimal_to_binary_recursive(0) '0b0' >>> decimal_to_binary_recursive(40) '0b101000' >>> decimal_to_binary_recursive(-40) '-0b101000' >>> decimal_to_binary_recursive(40.8) Traceback (most recent call last): ... ValueError: Input value is not an integer >>> decimal_to_binary_recursive("forty") Traceback (most recent call last): ... ValueError: Input value is not an integer """ number = str(number).strip() if not number: raise ValueError("No input value was provided") negative = "-" if number.startswith("-") else "" number = number.lstrip("-") if not number.isnumeric(): raise ValueError("Input value is not an integer") return f"{negative}0b{decimal_to_binary_recursive_helper(int(number))}" if __name__ == "__main__": import doctest doctest.testmod() print(decimal_to_binary_recursive(input("Input a decimal number: ")))
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 115: https://projecteuler.net/problem=115 NOTE: This is a more difficult version of Problem 114 (https://projecteuler.net/problem=114). A row measuring n units in length has red blocks with a minimum length of m units placed on it, such that any two red blocks (which are allowed to be different lengths) are separated by at least one black square. Let the fill-count function, F(m, n), represent the number of ways that a row can be filled. For example, F(3, 29) = 673135 and F(3, 30) = 1089155. That is, for m = 3, it can be seen that n = 30 is the smallest value for which the fill-count function first exceeds one million. In the same way, for m = 10, it can be verified that F(10, 56) = 880711 and F(10, 57) = 1148904, so n = 57 is the least value for which the fill-count function first exceeds one million. For m = 50, find the least value of n for which the fill-count function first exceeds one million. """ from itertools import count def solution(min_block_length: int = 50) -> int: """ Returns for given minimum block length the least value of n for which the fill-count function first exceeds one million >>> solution(3) 30 >>> solution(10) 57 """ fill_count_functions = [1] * min_block_length for n in count(min_block_length): fill_count_functions.append(1) for block_length in range(min_block_length, n + 1): for block_start in range(n - block_length): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_000_000: break return n if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 115: https://projecteuler.net/problem=115 NOTE: This is a more difficult version of Problem 114 (https://projecteuler.net/problem=114). A row measuring n units in length has red blocks with a minimum length of m units placed on it, such that any two red blocks (which are allowed to be different lengths) are separated by at least one black square. Let the fill-count function, F(m, n), represent the number of ways that a row can be filled. For example, F(3, 29) = 673135 and F(3, 30) = 1089155. That is, for m = 3, it can be seen that n = 30 is the smallest value for which the fill-count function first exceeds one million. In the same way, for m = 10, it can be verified that F(10, 56) = 880711 and F(10, 57) = 1148904, so n = 57 is the least value for which the fill-count function first exceeds one million. For m = 50, find the least value of n for which the fill-count function first exceeds one million. """ from itertools import count def solution(min_block_length: int = 50) -> int: """ Returns for given minimum block length the least value of n for which the fill-count function first exceeds one million >>> solution(3) 30 >>> solution(10) 57 """ fill_count_functions = [1] * min_block_length for n in count(min_block_length): fill_count_functions.append(1) for block_length in range(min_block_length, n + 1): for block_start in range(n - block_length): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1_000_000: break return n if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) * Description: Convert a Octal number to Binary. References for better understanding: https://en.wikipedia.org/wiki/Binary_number https://en.wikipedia.org/wiki/Octal """ def octal_to_binary(octal_number: str) -> str: """ Convert an Octal number to Binary. >>> octal_to_binary("17") '001111' >>> octal_to_binary("7") '111' >>> octal_to_binary("Av") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> octal_to_binary("@#") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> octal_to_binary("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function """ if not octal_number: raise ValueError("Empty string was passed to the function") binary_number = "" octal_digits = "01234567" for digit in octal_number: if digit not in octal_digits: raise ValueError("Non-octal value was passed to the function") binary_digit = "" value = int(digit) for _ in range(3): binary_digit = str(value % 2) + binary_digit value //= 2 binary_number += binary_digit return binary_number if __name__ == "__main__": import doctest doctest.testmod()
""" * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) * Description: Convert a Octal number to Binary. References for better understanding: https://en.wikipedia.org/wiki/Binary_number https://en.wikipedia.org/wiki/Octal """ def octal_to_binary(octal_number: str) -> str: """ Convert an Octal number to Binary. >>> octal_to_binary("17") '001111' >>> octal_to_binary("7") '111' >>> octal_to_binary("Av") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> octal_to_binary("@#") Traceback (most recent call last): ... ValueError: Non-octal value was passed to the function >>> octal_to_binary("") Traceback (most recent call last): ... ValueError: Empty string was passed to the function """ if not octal_number: raise ValueError("Empty string was passed to the function") binary_number = "" octal_digits = "01234567" for digit in octal_number: if digit not in octal_digits: raise ValueError("Non-octal value was passed to the function") binary_digit = "" value = int(digit) for _ in range(3): binary_digit = str(value % 2) + binary_digit value //= 2 binary_number += binary_digit return binary_number if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from __future__ import annotations from cmath import sqrt def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]: """ Given the numerical coefficients a, b and c, calculates the roots for any quadratic equation of the form ax^2 + bx + c >>> quadratic_roots(a=1, b=3, c=-4) (1.0, -4.0) >>> quadratic_roots(5, 6, 1) (-0.2, -1.0) >>> quadratic_roots(1, -6, 25) ((3+4j), (3-4j)) """ if a == 0: raise ValueError("Coefficient 'a' must not be zero.") delta = b * b - 4 * a * c root_1 = (-b + sqrt(delta)) / (2 * a) root_2 = (-b - sqrt(delta)) / (2 * a) return ( root_1.real if not root_1.imag else root_1, root_2.real if not root_2.imag else root_2, ) def main(): solution1, solution2 = quadratic_roots(a=5, b=6, c=1) print(f"The solutions are: {solution1} and {solution2}") if __name__ == "__main__": main()
from __future__ import annotations from cmath import sqrt def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]: """ Given the numerical coefficients a, b and c, calculates the roots for any quadratic equation of the form ax^2 + bx + c >>> quadratic_roots(a=1, b=3, c=-4) (1.0, -4.0) >>> quadratic_roots(5, 6, 1) (-0.2, -1.0) >>> quadratic_roots(1, -6, 25) ((3+4j), (3-4j)) """ if a == 0: raise ValueError("Coefficient 'a' must not be zero.") delta = b * b - 4 * a * c root_1 = (-b + sqrt(delta)) / (2 * a) root_2 = (-b - sqrt(delta)) / (2 * a) return ( root_1.real if not root_1.imag else root_1, root_2.real if not root_2.imag else root_2, ) def main(): solution1, solution2 = quadratic_roots(a=5, b=6, c=1) print(f"The solutions are: {solution1} and {solution2}") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
10,572
Converted tests into doctests
### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
AksharGoyal
"2023-10-16T03:30:49Z"
"2023-10-16T07:21:44Z"
cc0405d05cb4c5009e8bf826e3f641c427ba70d5
f4ff73b1bdaa4349315beaf44e093c59f6c87fd3
Converted tests into doctests. ### Describe your change: Turned tests into doctests in the Boolean Algebra section for consistency and as an improved way of testing. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? * [x] Changed code ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged 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 include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
9,707
Fix mypy errors in circular_linked_list.py and swap_nodes.py
### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-10-04T14:51:39Z"
"2023-10-04T16:05:01Z"
3fd3497f15982a7286326b520b5e7b52767da1f3
dfdd78135df938d948ba3044aca628aca08886e7
Fix mypy errors in circular_linked_list.py and swap_nodes.py. ### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
## Arithmetic Analysis * [Bisection](arithmetic_analysis/bisection.py) * [Gaussian Elimination](arithmetic_analysis/gaussian_elimination.py) * [In Static Equilibrium](arithmetic_analysis/in_static_equilibrium.py) * [Intersection](arithmetic_analysis/intersection.py) * [Jacobi Iteration Method](arithmetic_analysis/jacobi_iteration_method.py) * [Lu Decomposition](arithmetic_analysis/lu_decomposition.py) * [Newton Forward Interpolation](arithmetic_analysis/newton_forward_interpolation.py) * [Newton Method](arithmetic_analysis/newton_method.py) * [Newton Raphson](arithmetic_analysis/newton_raphson.py) * [Newton Raphson New](arithmetic_analysis/newton_raphson_new.py) * [Secant Method](arithmetic_analysis/secant_method.py) ## Audio Filters * [Butterworth Filter](audio_filters/butterworth_filter.py) * [Iir Filter](audio_filters/iir_filter.py) * [Show Response](audio_filters/show_response.py) ## Backtracking * [All Combinations](backtracking/all_combinations.py) * [All Permutations](backtracking/all_permutations.py) * [All Subsequences](backtracking/all_subsequences.py) * [Coloring](backtracking/coloring.py) * [Combination Sum](backtracking/combination_sum.py) * [Hamiltonian Cycle](backtracking/hamiltonian_cycle.py) * [Knight Tour](backtracking/knight_tour.py) * [Minimax](backtracking/minimax.py) * [N Queens](backtracking/n_queens.py) * [N Queens Math](backtracking/n_queens_math.py) * [Power Sum](backtracking/power_sum.py) * [Rat In Maze](backtracking/rat_in_maze.py) * [Sudoku](backtracking/sudoku.py) * [Sum Of Subsets](backtracking/sum_of_subsets.py) * [Word Search](backtracking/word_search.py) ## Bit Manipulation * [Binary And Operator](bit_manipulation/binary_and_operator.py) * [Binary Count Setbits](bit_manipulation/binary_count_setbits.py) * [Binary Count Trailing Zeros](bit_manipulation/binary_count_trailing_zeros.py) * [Binary Or Operator](bit_manipulation/binary_or_operator.py) * [Binary Shifts](bit_manipulation/binary_shifts.py) * [Binary Twos Complement](bit_manipulation/binary_twos_complement.py) * [Binary Xor Operator](bit_manipulation/binary_xor_operator.py) * [Bitwise Addition Recursive](bit_manipulation/bitwise_addition_recursive.py) * [Count 1S Brian Kernighan Method](bit_manipulation/count_1s_brian_kernighan_method.py) * [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py) * [Gray Code Sequence](bit_manipulation/gray_code_sequence.py) * [Highest Set Bit](bit_manipulation/highest_set_bit.py) * [Index Of Rightmost Set Bit](bit_manipulation/index_of_rightmost_set_bit.py) * [Is Even](bit_manipulation/is_even.py) * [Is Power Of Two](bit_manipulation/is_power_of_two.py) * [Missing Number](bit_manipulation/missing_number.py) * [Numbers Different Signs](bit_manipulation/numbers_different_signs.py) * [Reverse Bits](bit_manipulation/reverse_bits.py) * [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py) ## Blockchain * [Chinese Remainder Theorem](blockchain/chinese_remainder_theorem.py) * [Diophantine Equation](blockchain/diophantine_equation.py) * [Modular Division](blockchain/modular_division.py) ## Boolean Algebra * [And Gate](boolean_algebra/and_gate.py) * [Nand Gate](boolean_algebra/nand_gate.py) * [Nor Gate](boolean_algebra/nor_gate.py) * [Not Gate](boolean_algebra/not_gate.py) * [Or Gate](boolean_algebra/or_gate.py) * [Quine Mc Cluskey](boolean_algebra/quine_mc_cluskey.py) * [Xnor Gate](boolean_algebra/xnor_gate.py) * [Xor Gate](boolean_algebra/xor_gate.py) ## Cellular Automata * [Conways Game Of Life](cellular_automata/conways_game_of_life.py) * [Game Of Life](cellular_automata/game_of_life.py) * [Langtons Ant](cellular_automata/langtons_ant.py) * [Nagel Schrekenberg](cellular_automata/nagel_schrekenberg.py) * [One Dimensional](cellular_automata/one_dimensional.py) * [Wa Tor](cellular_automata/wa_tor.py) ## Ciphers * [A1Z26](ciphers/a1z26.py) * [Affine Cipher](ciphers/affine_cipher.py) * [Atbash](ciphers/atbash.py) * [Autokey](ciphers/autokey.py) * [Baconian Cipher](ciphers/baconian_cipher.py) * [Base16](ciphers/base16.py) * [Base32](ciphers/base32.py) * [Base64](ciphers/base64.py) * [Base85](ciphers/base85.py) * [Beaufort Cipher](ciphers/beaufort_cipher.py) * [Bifid](ciphers/bifid.py) * [Brute Force Caesar Cipher](ciphers/brute_force_caesar_cipher.py) * [Caesar Cipher](ciphers/caesar_cipher.py) * [Cryptomath Module](ciphers/cryptomath_module.py) * [Decrypt Caesar With Chi Squared](ciphers/decrypt_caesar_with_chi_squared.py) * [Deterministic Miller Rabin](ciphers/deterministic_miller_rabin.py) * [Diffie](ciphers/diffie.py) * [Diffie Hellman](ciphers/diffie_hellman.py) * [Elgamal Key Generator](ciphers/elgamal_key_generator.py) * [Enigma Machine2](ciphers/enigma_machine2.py) * [Hill Cipher](ciphers/hill_cipher.py) * [Mixed Keyword Cypher](ciphers/mixed_keyword_cypher.py) * [Mono Alphabetic Ciphers](ciphers/mono_alphabetic_ciphers.py) * [Morse Code](ciphers/morse_code.py) * [Onepad Cipher](ciphers/onepad_cipher.py) * [Playfair Cipher](ciphers/playfair_cipher.py) * [Polybius](ciphers/polybius.py) * [Porta Cipher](ciphers/porta_cipher.py) * [Rabin Miller](ciphers/rabin_miller.py) * [Rail Fence Cipher](ciphers/rail_fence_cipher.py) * [Rot13](ciphers/rot13.py) * [Rsa Cipher](ciphers/rsa_cipher.py) * [Rsa Factorization](ciphers/rsa_factorization.py) * [Rsa Key Generator](ciphers/rsa_key_generator.py) * [Shuffled Shift Cipher](ciphers/shuffled_shift_cipher.py) * [Simple Keyword Cypher](ciphers/simple_keyword_cypher.py) * [Simple Substitution Cipher](ciphers/simple_substitution_cipher.py) * [Trafid Cipher](ciphers/trafid_cipher.py) * [Transposition Cipher](ciphers/transposition_cipher.py) * [Transposition Cipher Encrypt Decrypt File](ciphers/transposition_cipher_encrypt_decrypt_file.py) * [Vigenere Cipher](ciphers/vigenere_cipher.py) * [Xor Cipher](ciphers/xor_cipher.py) ## Compression * [Burrows Wheeler](compression/burrows_wheeler.py) * [Huffman](compression/huffman.py) * [Lempel Ziv](compression/lempel_ziv.py) * [Lempel Ziv Decompress](compression/lempel_ziv_decompress.py) * [Lz77](compression/lz77.py) * [Peak Signal To Noise Ratio](compression/peak_signal_to_noise_ratio.py) * [Run Length Encoding](compression/run_length_encoding.py) ## Computer Vision * [Flip Augmentation](computer_vision/flip_augmentation.py) * [Haralick Descriptors](computer_vision/haralick_descriptors.py) * [Harris Corner](computer_vision/harris_corner.py) * [Horn Schunck](computer_vision/horn_schunck.py) * [Mean Threshold](computer_vision/mean_threshold.py) * [Mosaic Augmentation](computer_vision/mosaic_augmentation.py) * [Pooling Functions](computer_vision/pooling_functions.py) ## Conversions * [Astronomical Length Scale Conversion](conversions/astronomical_length_scale_conversion.py) * [Binary To Decimal](conversions/binary_to_decimal.py) * [Binary To Hexadecimal](conversions/binary_to_hexadecimal.py) * [Binary To Octal](conversions/binary_to_octal.py) * [Convert Number To Words](conversions/convert_number_to_words.py) * [Decimal To Any](conversions/decimal_to_any.py) * [Decimal To Binary](conversions/decimal_to_binary.py) * [Decimal To Hexadecimal](conversions/decimal_to_hexadecimal.py) * [Decimal To Octal](conversions/decimal_to_octal.py) * [Energy Conversions](conversions/energy_conversions.py) * [Excel Title To Column](conversions/excel_title_to_column.py) * [Hex To Bin](conversions/hex_to_bin.py) * [Hexadecimal To Decimal](conversions/hexadecimal_to_decimal.py) * [Length Conversion](conversions/length_conversion.py) * [Molecular Chemistry](conversions/molecular_chemistry.py) * [Octal To Binary](conversions/octal_to_binary.py) * [Octal To Decimal](conversions/octal_to_decimal.py) * [Prefix Conversions](conversions/prefix_conversions.py) * [Prefix Conversions String](conversions/prefix_conversions_string.py) * [Pressure Conversions](conversions/pressure_conversions.py) * [Rgb Hsv Conversion](conversions/rgb_hsv_conversion.py) * [Roman Numerals](conversions/roman_numerals.py) * [Speed Conversions](conversions/speed_conversions.py) * [Temperature Conversions](conversions/temperature_conversions.py) * [Volume Conversions](conversions/volume_conversions.py) * [Weight Conversion](conversions/weight_conversion.py) ## Data Structures * Arrays * [Permutations](data_structures/arrays/permutations.py) * [Prefix Sum](data_structures/arrays/prefix_sum.py) * [Product Sum](data_structures/arrays/product_sum.py) * Binary Tree * [Avl Tree](data_structures/binary_tree/avl_tree.py) * [Basic Binary Tree](data_structures/binary_tree/basic_binary_tree.py) * [Binary Search Tree](data_structures/binary_tree/binary_search_tree.py) * [Binary Search Tree Recursive](data_structures/binary_tree/binary_search_tree_recursive.py) * [Binary Tree Mirror](data_structures/binary_tree/binary_tree_mirror.py) * [Binary Tree Node Sum](data_structures/binary_tree/binary_tree_node_sum.py) * [Binary Tree Path Sum](data_structures/binary_tree/binary_tree_path_sum.py) * [Binary Tree Traversals](data_structures/binary_tree/binary_tree_traversals.py) * [Diff Views Of Binary Tree](data_structures/binary_tree/diff_views_of_binary_tree.py) * [Distribute Coins](data_structures/binary_tree/distribute_coins.py) * [Fenwick Tree](data_structures/binary_tree/fenwick_tree.py) * [Inorder Tree Traversal 2022](data_structures/binary_tree/inorder_tree_traversal_2022.py) * [Is Bst](data_structures/binary_tree/is_bst.py) * [Lazy Segment Tree](data_structures/binary_tree/lazy_segment_tree.py) * [Lowest Common Ancestor](data_structures/binary_tree/lowest_common_ancestor.py) * [Maximum Fenwick Tree](data_structures/binary_tree/maximum_fenwick_tree.py) * [Merge Two Binary Trees](data_structures/binary_tree/merge_two_binary_trees.py) * [Non Recursive Segment Tree](data_structures/binary_tree/non_recursive_segment_tree.py) * [Number Of Possible Binary Trees](data_structures/binary_tree/number_of_possible_binary_trees.py) * [Red Black Tree](data_structures/binary_tree/red_black_tree.py) * [Segment Tree](data_structures/binary_tree/segment_tree.py) * [Segment Tree Other](data_structures/binary_tree/segment_tree_other.py) * [Treap](data_structures/binary_tree/treap.py) * [Wavelet Tree](data_structures/binary_tree/wavelet_tree.py) * Disjoint Set * [Alternate Disjoint Set](data_structures/disjoint_set/alternate_disjoint_set.py) * [Disjoint Set](data_structures/disjoint_set/disjoint_set.py) * Hashing * [Bloom Filter](data_structures/hashing/bloom_filter.py) * [Double Hash](data_structures/hashing/double_hash.py) * [Hash Map](data_structures/hashing/hash_map.py) * [Hash Table](data_structures/hashing/hash_table.py) * [Hash Table With Linked List](data_structures/hashing/hash_table_with_linked_list.py) * Number Theory * [Prime Numbers](data_structures/hashing/number_theory/prime_numbers.py) * [Quadratic Probing](data_structures/hashing/quadratic_probing.py) * Tests * [Test Hash Map](data_structures/hashing/tests/test_hash_map.py) * Heap * [Binomial Heap](data_structures/heap/binomial_heap.py) * [Heap](data_structures/heap/heap.py) * [Heap Generic](data_structures/heap/heap_generic.py) * [Max Heap](data_structures/heap/max_heap.py) * [Min Heap](data_structures/heap/min_heap.py) * [Randomized Heap](data_structures/heap/randomized_heap.py) * [Skew Heap](data_structures/heap/skew_heap.py) * Linked List * [Circular Linked List](data_structures/linked_list/circular_linked_list.py) * [Deque Doubly](data_structures/linked_list/deque_doubly.py) * [Doubly Linked List](data_structures/linked_list/doubly_linked_list.py) * [Doubly Linked List Two](data_structures/linked_list/doubly_linked_list_two.py) * [From Sequence](data_structures/linked_list/from_sequence.py) * [Has Loop](data_structures/linked_list/has_loop.py) * [Is Palindrome](data_structures/linked_list/is_palindrome.py) * [Merge Two Lists](data_structures/linked_list/merge_two_lists.py) * [Middle Element Of Linked List](data_structures/linked_list/middle_element_of_linked_list.py) * [Print Reverse](data_structures/linked_list/print_reverse.py) * [Reverse K Group](data_structures/linked_list/reverse_k_group.py) * [Rotate To The Right](data_structures/linked_list/rotate_to_the_right.py) * [Singly Linked List](data_structures/linked_list/singly_linked_list.py) * [Skip List](data_structures/linked_list/skip_list.py) * [Swap Nodes](data_structures/linked_list/swap_nodes.py) * Queue * [Circular Queue](data_structures/queue/circular_queue.py) * [Circular Queue Linked List](data_structures/queue/circular_queue_linked_list.py) * [Double Ended Queue](data_structures/queue/double_ended_queue.py) * [Linked Queue](data_structures/queue/linked_queue.py) * [Priority Queue Using List](data_structures/queue/priority_queue_using_list.py) * [Queue By List](data_structures/queue/queue_by_list.py) * [Queue By Two Stacks](data_structures/queue/queue_by_two_stacks.py) * [Queue On Pseudo Stack](data_structures/queue/queue_on_pseudo_stack.py) * Stacks * [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py) * [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py) * [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py) * [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py) * [Next Greater Element](data_structures/stacks/next_greater_element.py) * [Postfix Evaluation](data_structures/stacks/postfix_evaluation.py) * [Prefix Evaluation](data_structures/stacks/prefix_evaluation.py) * [Stack](data_structures/stacks/stack.py) * [Stack With Doubly Linked List](data_structures/stacks/stack_with_doubly_linked_list.py) * [Stack With Singly Linked List](data_structures/stacks/stack_with_singly_linked_list.py) * [Stock Span Problem](data_structures/stacks/stock_span_problem.py) * Trie * [Radix Tree](data_structures/trie/radix_tree.py) * [Trie](data_structures/trie/trie.py) ## Digital Image Processing * [Change Brightness](digital_image_processing/change_brightness.py) * [Change Contrast](digital_image_processing/change_contrast.py) * [Convert To Negative](digital_image_processing/convert_to_negative.py) * Dithering * [Burkes](digital_image_processing/dithering/burkes.py) * Edge Detection * [Canny](digital_image_processing/edge_detection/canny.py) * Filters * [Bilateral Filter](digital_image_processing/filters/bilateral_filter.py) * [Convolve](digital_image_processing/filters/convolve.py) * [Gabor Filter](digital_image_processing/filters/gabor_filter.py) * [Gaussian Filter](digital_image_processing/filters/gaussian_filter.py) * [Local Binary Pattern](digital_image_processing/filters/local_binary_pattern.py) * [Median Filter](digital_image_processing/filters/median_filter.py) * [Sobel Filter](digital_image_processing/filters/sobel_filter.py) * Histogram Equalization * [Histogram Stretch](digital_image_processing/histogram_equalization/histogram_stretch.py) * [Index Calculation](digital_image_processing/index_calculation.py) * Morphological Operations * [Dilation Operation](digital_image_processing/morphological_operations/dilation_operation.py) * [Erosion Operation](digital_image_processing/morphological_operations/erosion_operation.py) * Resize * [Resize](digital_image_processing/resize/resize.py) * Rotation * [Rotation](digital_image_processing/rotation/rotation.py) * [Sepia](digital_image_processing/sepia.py) * [Test Digital Image Processing](digital_image_processing/test_digital_image_processing.py) ## Divide And Conquer * [Closest Pair Of Points](divide_and_conquer/closest_pair_of_points.py) * [Convex Hull](divide_and_conquer/convex_hull.py) * [Heaps Algorithm](divide_and_conquer/heaps_algorithm.py) * [Heaps Algorithm Iterative](divide_and_conquer/heaps_algorithm_iterative.py) * [Inversions](divide_and_conquer/inversions.py) * [Kth Order Statistic](divide_and_conquer/kth_order_statistic.py) * [Max Difference Pair](divide_and_conquer/max_difference_pair.py) * [Max Subarray](divide_and_conquer/max_subarray.py) * [Mergesort](divide_and_conquer/mergesort.py) * [Peak](divide_and_conquer/peak.py) * [Power](divide_and_conquer/power.py) * [Strassen Matrix Multiplication](divide_and_conquer/strassen_matrix_multiplication.py) ## Dynamic Programming * [Abbreviation](dynamic_programming/abbreviation.py) * [All Construct](dynamic_programming/all_construct.py) * [Bitmask](dynamic_programming/bitmask.py) * [Catalan Numbers](dynamic_programming/catalan_numbers.py) * [Climbing Stairs](dynamic_programming/climbing_stairs.py) * [Combination Sum Iv](dynamic_programming/combination_sum_iv.py) * [Edit Distance](dynamic_programming/edit_distance.py) * [Factorial](dynamic_programming/factorial.py) * [Fast Fibonacci](dynamic_programming/fast_fibonacci.py) * [Fibonacci](dynamic_programming/fibonacci.py) * [Fizz Buzz](dynamic_programming/fizz_buzz.py) * [Floyd Warshall](dynamic_programming/floyd_warshall.py) * [Integer Partition](dynamic_programming/integer_partition.py) * [Iterating Through Submasks](dynamic_programming/iterating_through_submasks.py) * [Knapsack](dynamic_programming/knapsack.py) * [Longest Common Subsequence](dynamic_programming/longest_common_subsequence.py) * [Longest Common Substring](dynamic_programming/longest_common_substring.py) * [Longest Increasing Subsequence](dynamic_programming/longest_increasing_subsequence.py) * [Longest Increasing Subsequence O(Nlogn)](dynamic_programming/longest_increasing_subsequence_o(nlogn).py) * [Longest Sub Array](dynamic_programming/longest_sub_array.py) * [Matrix Chain Order](dynamic_programming/matrix_chain_order.py) * [Max Non Adjacent Sum](dynamic_programming/max_non_adjacent_sum.py) * [Max Product Subarray](dynamic_programming/max_product_subarray.py) * [Max Subarray Sum](dynamic_programming/max_subarray_sum.py) * [Min Distance Up Bottom](dynamic_programming/min_distance_up_bottom.py) * [Minimum Coin Change](dynamic_programming/minimum_coin_change.py) * [Minimum Cost Path](dynamic_programming/minimum_cost_path.py) * [Minimum Partition](dynamic_programming/minimum_partition.py) * [Minimum Size Subarray Sum](dynamic_programming/minimum_size_subarray_sum.py) * [Minimum Squares To Represent A Number](dynamic_programming/minimum_squares_to_represent_a_number.py) * [Minimum Steps To One](dynamic_programming/minimum_steps_to_one.py) * [Minimum Tickets Cost](dynamic_programming/minimum_tickets_cost.py) * [Optimal Binary Search Tree](dynamic_programming/optimal_binary_search_tree.py) * [Palindrome Partitioning](dynamic_programming/palindrome_partitioning.py) * [Regex Match](dynamic_programming/regex_match.py) * [Rod Cutting](dynamic_programming/rod_cutting.py) * [Smith Waterman](dynamic_programming/smith_waterman.py) * [Subset Generation](dynamic_programming/subset_generation.py) * [Sum Of Subset](dynamic_programming/sum_of_subset.py) * [Tribonacci](dynamic_programming/tribonacci.py) * [Viterbi](dynamic_programming/viterbi.py) * [Word Break](dynamic_programming/word_break.py) ## Electronics * [Apparent Power](electronics/apparent_power.py) * [Builtin Voltage](electronics/builtin_voltage.py) * [Carrier Concentration](electronics/carrier_concentration.py) * [Circular Convolution](electronics/circular_convolution.py) * [Coulombs Law](electronics/coulombs_law.py) * [Electric Conductivity](electronics/electric_conductivity.py) * [Electric Power](electronics/electric_power.py) * [Electrical Impedance](electronics/electrical_impedance.py) * [Ind Reactance](electronics/ind_reactance.py) * [Ohms Law](electronics/ohms_law.py) * [Real And Reactive Power](electronics/real_and_reactive_power.py) * [Resistor Equivalence](electronics/resistor_equivalence.py) * [Resonant Frequency](electronics/resonant_frequency.py) ## File Transfer * [Receive File](file_transfer/receive_file.py) * [Send File](file_transfer/send_file.py) * Tests * [Test Send File](file_transfer/tests/test_send_file.py) ## Financial * [Equated Monthly Installments](financial/equated_monthly_installments.py) * [Interest](financial/interest.py) * [Present Value](financial/present_value.py) * [Price Plus Tax](financial/price_plus_tax.py) ## Fractals * [Julia Sets](fractals/julia_sets.py) * [Koch Snowflake](fractals/koch_snowflake.py) * [Mandelbrot](fractals/mandelbrot.py) * [Sierpinski Triangle](fractals/sierpinski_triangle.py) ## Genetic Algorithm * [Basic String](genetic_algorithm/basic_string.py) ## Geodesy * [Haversine Distance](geodesy/haversine_distance.py) * [Lamberts Ellipsoidal Distance](geodesy/lamberts_ellipsoidal_distance.py) ## Graphics * [Bezier Curve](graphics/bezier_curve.py) * [Vector3 For 2D Rendering](graphics/vector3_for_2d_rendering.py) ## Graphs * [A Star](graphs/a_star.py) * [Articulation Points](graphs/articulation_points.py) * [Basic Graphs](graphs/basic_graphs.py) * [Bellman Ford](graphs/bellman_ford.py) * [Bi Directional Dijkstra](graphs/bi_directional_dijkstra.py) * [Bidirectional A Star](graphs/bidirectional_a_star.py) * [Bidirectional Breadth First Search](graphs/bidirectional_breadth_first_search.py) * [Boruvka](graphs/boruvka.py) * [Breadth First Search](graphs/breadth_first_search.py) * [Breadth First Search 2](graphs/breadth_first_search_2.py) * [Breadth First Search Shortest Path](graphs/breadth_first_search_shortest_path.py) * [Breadth First Search Shortest Path 2](graphs/breadth_first_search_shortest_path_2.py) * [Breadth First Search Zero One Shortest Path](graphs/breadth_first_search_zero_one_shortest_path.py) * [Check Bipartite Graph Bfs](graphs/check_bipartite_graph_bfs.py) * [Check Bipartite Graph Dfs](graphs/check_bipartite_graph_dfs.py) * [Check Cycle](graphs/check_cycle.py) * [Connected Components](graphs/connected_components.py) * [Depth First Search](graphs/depth_first_search.py) * [Depth First Search 2](graphs/depth_first_search_2.py) * [Dijkstra](graphs/dijkstra.py) * [Dijkstra 2](graphs/dijkstra_2.py) * [Dijkstra Algorithm](graphs/dijkstra_algorithm.py) * [Dijkstra Alternate](graphs/dijkstra_alternate.py) * [Dijkstra Binary Grid](graphs/dijkstra_binary_grid.py) * [Dinic](graphs/dinic.py) * [Directed And Undirected (Weighted) Graph](graphs/directed_and_undirected_(weighted)_graph.py) * [Edmonds Karp Multiple Source And Sink](graphs/edmonds_karp_multiple_source_and_sink.py) * [Eulerian Path And Circuit For Undirected Graph](graphs/eulerian_path_and_circuit_for_undirected_graph.py) * [Even Tree](graphs/even_tree.py) * [Finding Bridges](graphs/finding_bridges.py) * [Frequent Pattern Graph Miner](graphs/frequent_pattern_graph_miner.py) * [G Topological Sort](graphs/g_topological_sort.py) * [Gale Shapley Bigraph](graphs/gale_shapley_bigraph.py) * [Graph Adjacency List](graphs/graph_adjacency_list.py) * [Graph Adjacency Matrix](graphs/graph_adjacency_matrix.py) * [Graph List](graphs/graph_list.py) * [Graphs Floyd Warshall](graphs/graphs_floyd_warshall.py) * [Greedy Best First](graphs/greedy_best_first.py) * [Greedy Min Vertex Cover](graphs/greedy_min_vertex_cover.py) * [Kahns Algorithm Long](graphs/kahns_algorithm_long.py) * [Kahns Algorithm Topo](graphs/kahns_algorithm_topo.py) * [Karger](graphs/karger.py) * [Markov Chain](graphs/markov_chain.py) * [Matching Min Vertex Cover](graphs/matching_min_vertex_cover.py) * [Minimum Path Sum](graphs/minimum_path_sum.py) * [Minimum Spanning Tree Boruvka](graphs/minimum_spanning_tree_boruvka.py) * [Minimum Spanning Tree Kruskal](graphs/minimum_spanning_tree_kruskal.py) * [Minimum Spanning Tree Kruskal2](graphs/minimum_spanning_tree_kruskal2.py) * [Minimum Spanning Tree Prims](graphs/minimum_spanning_tree_prims.py) * [Minimum Spanning Tree Prims2](graphs/minimum_spanning_tree_prims2.py) * [Multi Heuristic Astar](graphs/multi_heuristic_astar.py) * [Page Rank](graphs/page_rank.py) * [Prim](graphs/prim.py) * [Random Graph Generator](graphs/random_graph_generator.py) * [Scc Kosaraju](graphs/scc_kosaraju.py) * [Strongly Connected Components](graphs/strongly_connected_components.py) * [Tarjans Scc](graphs/tarjans_scc.py) * Tests * [Test Min Spanning Tree Kruskal](graphs/tests/test_min_spanning_tree_kruskal.py) * [Test Min Spanning Tree Prim](graphs/tests/test_min_spanning_tree_prim.py) ## Greedy Methods * [Fractional Knapsack](greedy_methods/fractional_knapsack.py) * [Fractional Knapsack 2](greedy_methods/fractional_knapsack_2.py) * [Minimum Waiting Time](greedy_methods/minimum_waiting_time.py) * [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py) ## Hashes * [Adler32](hashes/adler32.py) * [Chaos Machine](hashes/chaos_machine.py) * [Djb2](hashes/djb2.py) * [Elf](hashes/elf.py) * [Enigma Machine](hashes/enigma_machine.py) * [Hamming Code](hashes/hamming_code.py) * [Luhn](hashes/luhn.py) * [Md5](hashes/md5.py) * [Sdbm](hashes/sdbm.py) * [Sha1](hashes/sha1.py) * [Sha256](hashes/sha256.py) ## Knapsack * [Greedy Knapsack](knapsack/greedy_knapsack.py) * [Knapsack](knapsack/knapsack.py) * [Recursive Approach Knapsack](knapsack/recursive_approach_knapsack.py) * Tests * [Test Greedy Knapsack](knapsack/tests/test_greedy_knapsack.py) * [Test Knapsack](knapsack/tests/test_knapsack.py) ## Linear Algebra * Src * [Conjugate Gradient](linear_algebra/src/conjugate_gradient.py) * [Lib](linear_algebra/src/lib.py) * [Polynom For Points](linear_algebra/src/polynom_for_points.py) * [Power Iteration](linear_algebra/src/power_iteration.py) * [Rank Of Matrix](linear_algebra/src/rank_of_matrix.py) * [Rayleigh Quotient](linear_algebra/src/rayleigh_quotient.py) * [Schur Complement](linear_algebra/src/schur_complement.py) * [Test Linear Algebra](linear_algebra/src/test_linear_algebra.py) * [Transformations 2D](linear_algebra/src/transformations_2d.py) ## Linear Programming * [Simplex](linear_programming/simplex.py) ## Machine Learning * [Astar](machine_learning/astar.py) * [Data Transformations](machine_learning/data_transformations.py) * [Decision Tree](machine_learning/decision_tree.py) * [Dimensionality Reduction](machine_learning/dimensionality_reduction.py) * Forecasting * [Run](machine_learning/forecasting/run.py) * [Gradient Descent](machine_learning/gradient_descent.py) * [K Means Clust](machine_learning/k_means_clust.py) * [K Nearest Neighbours](machine_learning/k_nearest_neighbours.py) * [Linear Discriminant Analysis](machine_learning/linear_discriminant_analysis.py) * [Linear Regression](machine_learning/linear_regression.py) * Local Weighted Learning * [Local Weighted Learning](machine_learning/local_weighted_learning/local_weighted_learning.py) * [Logistic Regression](machine_learning/logistic_regression.py) * [Mfcc](machine_learning/mfcc.py) * [Multilayer Perceptron Classifier](machine_learning/multilayer_perceptron_classifier.py) * [Polynomial Regression](machine_learning/polynomial_regression.py) * [Scoring Functions](machine_learning/scoring_functions.py) * [Self Organizing Map](machine_learning/self_organizing_map.py) * [Sequential Minimum Optimization](machine_learning/sequential_minimum_optimization.py) * [Similarity Search](machine_learning/similarity_search.py) * [Support Vector Machines](machine_learning/support_vector_machines.py) * [Word Frequency Functions](machine_learning/word_frequency_functions.py) * [Xgboost Classifier](machine_learning/xgboost_classifier.py) * [Xgboost Regressor](machine_learning/xgboost_regressor.py) ## Maths * [Abs](maths/abs.py) * [Addition Without Arithmetic](maths/addition_without_arithmetic.py) * [Aliquot Sum](maths/aliquot_sum.py) * [Allocation Number](maths/allocation_number.py) * [Arc Length](maths/arc_length.py) * [Area](maths/area.py) * [Area Under Curve](maths/area_under_curve.py) * [Armstrong Numbers](maths/armstrong_numbers.py) * [Automorphic Number](maths/automorphic_number.py) * [Average Absolute Deviation](maths/average_absolute_deviation.py) * [Average Mean](maths/average_mean.py) * [Average Median](maths/average_median.py) * [Average Mode](maths/average_mode.py) * [Bailey Borwein Plouffe](maths/bailey_borwein_plouffe.py) * [Basic Maths](maths/basic_maths.py) * [Binary Exp Mod](maths/binary_exp_mod.py) * [Binary Exponentiation](maths/binary_exponentiation.py) * [Binary Exponentiation 2](maths/binary_exponentiation_2.py) * [Binary Exponentiation 3](maths/binary_exponentiation_3.py) * [Binomial Coefficient](maths/binomial_coefficient.py) * [Binomial Distribution](maths/binomial_distribution.py) * [Bisection](maths/bisection.py) * [Carmichael Number](maths/carmichael_number.py) * [Catalan Number](maths/catalan_number.py) * [Ceil](maths/ceil.py) * [Check Polygon](maths/check_polygon.py) * [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py) * [Collatz Sequence](maths/collatz_sequence.py) * [Combinations](maths/combinations.py) * [Continued Fraction](maths/continued_fraction.py) * [Decimal Isolate](maths/decimal_isolate.py) * [Decimal To Fraction](maths/decimal_to_fraction.py) * [Dodecahedron](maths/dodecahedron.py) * [Double Factorial Iterative](maths/double_factorial_iterative.py) * [Double Factorial Recursive](maths/double_factorial_recursive.py) * [Dual Number Automatic Differentiation](maths/dual_number_automatic_differentiation.py) * [Entropy](maths/entropy.py) * [Euclidean Distance](maths/euclidean_distance.py) * [Euler Method](maths/euler_method.py) * [Euler Modified](maths/euler_modified.py) * [Eulers Totient](maths/eulers_totient.py) * [Extended Euclidean Algorithm](maths/extended_euclidean_algorithm.py) * [Factorial](maths/factorial.py) * [Factors](maths/factors.py) * [Fermat Little Theorem](maths/fermat_little_theorem.py) * [Fibonacci](maths/fibonacci.py) * [Find Max](maths/find_max.py) * [Find Min](maths/find_min.py) * [Floor](maths/floor.py) * [Gamma](maths/gamma.py) * [Gamma Recursive](maths/gamma_recursive.py) * [Gaussian](maths/gaussian.py) * [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py) * [Gcd Of N Numbers](maths/gcd_of_n_numbers.py) * [Greatest Common Divisor](maths/greatest_common_divisor.py) * [Greedy Coin Change](maths/greedy_coin_change.py) * [Hamming Numbers](maths/hamming_numbers.py) * [Hardy Ramanujanalgo](maths/hardy_ramanujanalgo.py) * [Harshad Numbers](maths/harshad_numbers.py) * [Hexagonal Number](maths/hexagonal_number.py) * [Integration By Simpson Approx](maths/integration_by_simpson_approx.py) * [Interquartile Range](maths/interquartile_range.py) * [Is Int Palindrome](maths/is_int_palindrome.py) * [Is Ip V4 Address Valid](maths/is_ip_v4_address_valid.py) * [Is Square Free](maths/is_square_free.py) * [Jaccard Similarity](maths/jaccard_similarity.py) * [Juggler Sequence](maths/juggler_sequence.py) * [Karatsuba](maths/karatsuba.py) * [Krishnamurthy Number](maths/krishnamurthy_number.py) * [Kth Lexicographic Permutation](maths/kth_lexicographic_permutation.py) * [Largest Of Very Large Numbers](maths/largest_of_very_large_numbers.py) * [Least Common Multiple](maths/least_common_multiple.py) * [Line Length](maths/line_length.py) * [Liouville Lambda](maths/liouville_lambda.py) * [Lucas Lehmer Primality Test](maths/lucas_lehmer_primality_test.py) * [Lucas Series](maths/lucas_series.py) * [Maclaurin Series](maths/maclaurin_series.py) * [Manhattan Distance](maths/manhattan_distance.py) * [Matrix Exponentiation](maths/matrix_exponentiation.py) * [Max Sum Sliding Window](maths/max_sum_sliding_window.py) * [Median Of Two Arrays](maths/median_of_two_arrays.py) * [Mobius Function](maths/mobius_function.py) * [Modular Exponential](maths/modular_exponential.py) * [Monte Carlo](maths/monte_carlo.py) * [Monte Carlo Dice](maths/monte_carlo_dice.py) * [Nevilles Method](maths/nevilles_method.py) * [Newton Raphson](maths/newton_raphson.py) * [Number Of Digits](maths/number_of_digits.py) * [Numerical Integration](maths/numerical_integration.py) * [Odd Sieve](maths/odd_sieve.py) * [Perfect Cube](maths/perfect_cube.py) * [Perfect Number](maths/perfect_number.py) * [Perfect Square](maths/perfect_square.py) * [Persistence](maths/persistence.py) * [Pi Generator](maths/pi_generator.py) * [Pi Monte Carlo Estimation](maths/pi_monte_carlo_estimation.py) * [Points Are Collinear 3D](maths/points_are_collinear_3d.py) * [Pollard Rho](maths/pollard_rho.py) * [Polygonal Numbers](maths/polygonal_numbers.py) * [Polynomial Evaluation](maths/polynomial_evaluation.py) * Polynomials * [Single Indeterminate Operations](maths/polynomials/single_indeterminate_operations.py) * [Power Using Recursion](maths/power_using_recursion.py) * [Prime Check](maths/prime_check.py) * [Prime Factors](maths/prime_factors.py) * [Prime Numbers](maths/prime_numbers.py) * [Prime Sieve Eratosthenes](maths/prime_sieve_eratosthenes.py) * [Primelib](maths/primelib.py) * [Print Multiplication Table](maths/print_multiplication_table.py) * [Pronic Number](maths/pronic_number.py) * [Proth Number](maths/proth_number.py) * [Pythagoras](maths/pythagoras.py) * [Qr Decomposition](maths/qr_decomposition.py) * [Quadratic Equations Complex Numbers](maths/quadratic_equations_complex_numbers.py) * [Radians](maths/radians.py) * [Radix2 Fft](maths/radix2_fft.py) * [Relu](maths/relu.py) * [Remove Digit](maths/remove_digit.py) * [Runge Kutta](maths/runge_kutta.py) * [Segmented Sieve](maths/segmented_sieve.py) * Series * [Arithmetic](maths/series/arithmetic.py) * [Geometric](maths/series/geometric.py) * [Geometric Series](maths/series/geometric_series.py) * [Harmonic](maths/series/harmonic.py) * [Harmonic Series](maths/series/harmonic_series.py) * [Hexagonal Numbers](maths/series/hexagonal_numbers.py) * [P Series](maths/series/p_series.py) * [Sieve Of Eratosthenes](maths/sieve_of_eratosthenes.py) * [Sigmoid](maths/sigmoid.py) * [Sigmoid Linear Unit](maths/sigmoid_linear_unit.py) * [Signum](maths/signum.py) * [Simpson Rule](maths/simpson_rule.py) * [Simultaneous Linear Equation Solver](maths/simultaneous_linear_equation_solver.py) * [Sin](maths/sin.py) * [Sock Merchant](maths/sock_merchant.py) * [Softmax](maths/softmax.py) * [Square Root](maths/square_root.py) * [Sum Of Arithmetic Series](maths/sum_of_arithmetic_series.py) * [Sum Of Digits](maths/sum_of_digits.py) * [Sum Of Geometric Progression](maths/sum_of_geometric_progression.py) * [Sum Of Harmonic Series](maths/sum_of_harmonic_series.py) * [Sumset](maths/sumset.py) * [Sylvester Sequence](maths/sylvester_sequence.py) * [Tanh](maths/tanh.py) * [Test Prime Check](maths/test_prime_check.py) * [Three Sum](maths/three_sum.py) * [Trapezoidal Rule](maths/trapezoidal_rule.py) * [Triplet Sum](maths/triplet_sum.py) * [Twin Prime](maths/twin_prime.py) * [Two Pointer](maths/two_pointer.py) * [Two Sum](maths/two_sum.py) * [Ugly Numbers](maths/ugly_numbers.py) * [Volume](maths/volume.py) * [Weird Number](maths/weird_number.py) * [Zellers Congruence](maths/zellers_congruence.py) ## Matrix * [Binary Search Matrix](matrix/binary_search_matrix.py) * [Count Islands In Matrix](matrix/count_islands_in_matrix.py) * [Count Negative Numbers In Sorted Matrix](matrix/count_negative_numbers_in_sorted_matrix.py) * [Count Paths](matrix/count_paths.py) * [Cramers Rule 2X2](matrix/cramers_rule_2x2.py) * [Inverse Of Matrix](matrix/inverse_of_matrix.py) * [Largest Square Area In Matrix](matrix/largest_square_area_in_matrix.py) * [Matrix Class](matrix/matrix_class.py) * [Matrix Operation](matrix/matrix_operation.py) * [Max Area Of Island](matrix/max_area_of_island.py) * [Nth Fibonacci Using Matrix Exponentiation](matrix/nth_fibonacci_using_matrix_exponentiation.py) * [Pascal Triangle](matrix/pascal_triangle.py) * [Rotate Matrix](matrix/rotate_matrix.py) * [Searching In Sorted Matrix](matrix/searching_in_sorted_matrix.py) * [Sherman Morrison](matrix/sherman_morrison.py) * [Spiral Print](matrix/spiral_print.py) * Tests * [Test Matrix Operation](matrix/tests/test_matrix_operation.py) ## Networking Flow * [Ford Fulkerson](networking_flow/ford_fulkerson.py) * [Minimum Cut](networking_flow/minimum_cut.py) ## Neural Network * [2 Hidden Layers Neural Network](neural_network/2_hidden_layers_neural_network.py) * Activation Functions * [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py) * [Leaky Rectified Linear Unit](neural_network/activation_functions/leaky_rectified_linear_unit.py) * [Scaled Exponential Linear Unit](neural_network/activation_functions/scaled_exponential_linear_unit.py) * [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py) * [Convolution Neural Network](neural_network/convolution_neural_network.py) * [Perceptron](neural_network/perceptron.py) * [Simple Neural Network](neural_network/simple_neural_network.py) ## Other * [Activity Selection](other/activity_selection.py) * [Alternative List Arrange](other/alternative_list_arrange.py) * [Davisb Putnamb Logemannb Loveland](other/davisb_putnamb_logemannb_loveland.py) * [Dijkstra Bankers Algorithm](other/dijkstra_bankers_algorithm.py) * [Doomsday](other/doomsday.py) * [Fischer Yates Shuffle](other/fischer_yates_shuffle.py) * [Gauss Easter](other/gauss_easter.py) * [Graham Scan](other/graham_scan.py) * [Greedy](other/greedy.py) * [Guess The Number Search](other/guess_the_number_search.py) * [H Index](other/h_index.py) * [Least Recently Used](other/least_recently_used.py) * [Lfu Cache](other/lfu_cache.py) * [Linear Congruential Generator](other/linear_congruential_generator.py) * [Lru Cache](other/lru_cache.py) * [Magicdiamondpattern](other/magicdiamondpattern.py) * [Maximum Subsequence](other/maximum_subsequence.py) * [Nested Brackets](other/nested_brackets.py) * [Number Container System](other/number_container_system.py) * [Password](other/password.py) * [Quine](other/quine.py) * [Scoring Algorithm](other/scoring_algorithm.py) * [Sdes](other/sdes.py) * [Tower Of Hanoi](other/tower_of_hanoi.py) * [Word Search](other/word_search.py) ## Physics * [Altitude Pressure](physics/altitude_pressure.py) * [Archimedes Principle](physics/archimedes_principle.py) * [Basic Orbital Capture](physics/basic_orbital_capture.py) * [Casimir Effect](physics/casimir_effect.py) * [Centripetal Force](physics/centripetal_force.py) * [Coulombs Law](physics/coulombs_law.py) * [Grahams Law](physics/grahams_law.py) * [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py) * [Hubble Parameter](physics/hubble_parameter.py) * [Ideal Gas Law](physics/ideal_gas_law.py) * [Kinetic Energy](physics/kinetic_energy.py) * [Lorentz Transformation Four Vector](physics/lorentz_transformation_four_vector.py) * [Malus Law](physics/malus_law.py) * [N Body Simulation](physics/n_body_simulation.py) * [Newtons Law Of Gravitation](physics/newtons_law_of_gravitation.py) * [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py) * [Potential Energy](physics/potential_energy.py) * [Rms Speed Of Molecule](physics/rms_speed_of_molecule.py) * [Shear Stress](physics/shear_stress.py) * [Speed Of Sound](physics/speed_of_sound.py) ## Project Euler * Problem 001 * [Sol1](project_euler/problem_001/sol1.py) * [Sol2](project_euler/problem_001/sol2.py) * [Sol3](project_euler/problem_001/sol3.py) * [Sol4](project_euler/problem_001/sol4.py) * [Sol5](project_euler/problem_001/sol5.py) * [Sol6](project_euler/problem_001/sol6.py) * [Sol7](project_euler/problem_001/sol7.py) * Problem 002 * [Sol1](project_euler/problem_002/sol1.py) * [Sol2](project_euler/problem_002/sol2.py) * [Sol3](project_euler/problem_002/sol3.py) * [Sol4](project_euler/problem_002/sol4.py) * [Sol5](project_euler/problem_002/sol5.py) * Problem 003 * [Sol1](project_euler/problem_003/sol1.py) * [Sol2](project_euler/problem_003/sol2.py) * [Sol3](project_euler/problem_003/sol3.py) * Problem 004 * [Sol1](project_euler/problem_004/sol1.py) * [Sol2](project_euler/problem_004/sol2.py) * Problem 005 * [Sol1](project_euler/problem_005/sol1.py) * [Sol2](project_euler/problem_005/sol2.py) * Problem 006 * [Sol1](project_euler/problem_006/sol1.py) * [Sol2](project_euler/problem_006/sol2.py) * [Sol3](project_euler/problem_006/sol3.py) * [Sol4](project_euler/problem_006/sol4.py) * Problem 007 * [Sol1](project_euler/problem_007/sol1.py) * [Sol2](project_euler/problem_007/sol2.py) * [Sol3](project_euler/problem_007/sol3.py) * Problem 008 * [Sol1](project_euler/problem_008/sol1.py) * [Sol2](project_euler/problem_008/sol2.py) * [Sol3](project_euler/problem_008/sol3.py) * Problem 009 * [Sol1](project_euler/problem_009/sol1.py) * [Sol2](project_euler/problem_009/sol2.py) * [Sol3](project_euler/problem_009/sol3.py) * Problem 010 * [Sol1](project_euler/problem_010/sol1.py) * [Sol2](project_euler/problem_010/sol2.py) * [Sol3](project_euler/problem_010/sol3.py) * Problem 011 * [Sol1](project_euler/problem_011/sol1.py) * [Sol2](project_euler/problem_011/sol2.py) * Problem 012 * [Sol1](project_euler/problem_012/sol1.py) * [Sol2](project_euler/problem_012/sol2.py) * Problem 013 * [Sol1](project_euler/problem_013/sol1.py) * Problem 014 * [Sol1](project_euler/problem_014/sol1.py) * [Sol2](project_euler/problem_014/sol2.py) * Problem 015 * [Sol1](project_euler/problem_015/sol1.py) * Problem 016 * [Sol1](project_euler/problem_016/sol1.py) * [Sol2](project_euler/problem_016/sol2.py) * Problem 017 * [Sol1](project_euler/problem_017/sol1.py) * Problem 018 * [Solution](project_euler/problem_018/solution.py) * Problem 019 * [Sol1](project_euler/problem_019/sol1.py) * Problem 020 * [Sol1](project_euler/problem_020/sol1.py) * [Sol2](project_euler/problem_020/sol2.py) * [Sol3](project_euler/problem_020/sol3.py) * [Sol4](project_euler/problem_020/sol4.py) * Problem 021 * [Sol1](project_euler/problem_021/sol1.py) * Problem 022 * [Sol1](project_euler/problem_022/sol1.py) * [Sol2](project_euler/problem_022/sol2.py) * Problem 023 * [Sol1](project_euler/problem_023/sol1.py) * Problem 024 * [Sol1](project_euler/problem_024/sol1.py) * Problem 025 * [Sol1](project_euler/problem_025/sol1.py) * [Sol2](project_euler/problem_025/sol2.py) * [Sol3](project_euler/problem_025/sol3.py) * Problem 026 * [Sol1](project_euler/problem_026/sol1.py) * Problem 027 * [Sol1](project_euler/problem_027/sol1.py) * Problem 028 * [Sol1](project_euler/problem_028/sol1.py) * Problem 029 * [Sol1](project_euler/problem_029/sol1.py) * Problem 030 * [Sol1](project_euler/problem_030/sol1.py) * Problem 031 * [Sol1](project_euler/problem_031/sol1.py) * [Sol2](project_euler/problem_031/sol2.py) * Problem 032 * [Sol32](project_euler/problem_032/sol32.py) * Problem 033 * [Sol1](project_euler/problem_033/sol1.py) * Problem 034 * [Sol1](project_euler/problem_034/sol1.py) * Problem 035 * [Sol1](project_euler/problem_035/sol1.py) * Problem 036 * [Sol1](project_euler/problem_036/sol1.py) * Problem 037 * [Sol1](project_euler/problem_037/sol1.py) * Problem 038 * [Sol1](project_euler/problem_038/sol1.py) * Problem 039 * [Sol1](project_euler/problem_039/sol1.py) * Problem 040 * [Sol1](project_euler/problem_040/sol1.py) * Problem 041 * [Sol1](project_euler/problem_041/sol1.py) * Problem 042 * [Solution42](project_euler/problem_042/solution42.py) * Problem 043 * [Sol1](project_euler/problem_043/sol1.py) * Problem 044 * [Sol1](project_euler/problem_044/sol1.py) * Problem 045 * [Sol1](project_euler/problem_045/sol1.py) * Problem 046 * [Sol1](project_euler/problem_046/sol1.py) * Problem 047 * [Sol1](project_euler/problem_047/sol1.py) * Problem 048 * [Sol1](project_euler/problem_048/sol1.py) * Problem 049 * [Sol1](project_euler/problem_049/sol1.py) * Problem 050 * [Sol1](project_euler/problem_050/sol1.py) * Problem 051 * [Sol1](project_euler/problem_051/sol1.py) * Problem 052 * [Sol1](project_euler/problem_052/sol1.py) * Problem 053 * [Sol1](project_euler/problem_053/sol1.py) * Problem 054 * [Sol1](project_euler/problem_054/sol1.py) * [Test Poker Hand](project_euler/problem_054/test_poker_hand.py) * Problem 055 * [Sol1](project_euler/problem_055/sol1.py) * Problem 056 * [Sol1](project_euler/problem_056/sol1.py) * Problem 057 * [Sol1](project_euler/problem_057/sol1.py) * Problem 058 * [Sol1](project_euler/problem_058/sol1.py) * Problem 059 * [Sol1](project_euler/problem_059/sol1.py) * Problem 062 * [Sol1](project_euler/problem_062/sol1.py) * Problem 063 * [Sol1](project_euler/problem_063/sol1.py) * Problem 064 * [Sol1](project_euler/problem_064/sol1.py) * Problem 065 * [Sol1](project_euler/problem_065/sol1.py) * Problem 067 * [Sol1](project_euler/problem_067/sol1.py) * [Sol2](project_euler/problem_067/sol2.py) * Problem 068 * [Sol1](project_euler/problem_068/sol1.py) * Problem 069 * [Sol1](project_euler/problem_069/sol1.py) * Problem 070 * [Sol1](project_euler/problem_070/sol1.py) * Problem 071 * [Sol1](project_euler/problem_071/sol1.py) * Problem 072 * [Sol1](project_euler/problem_072/sol1.py) * [Sol2](project_euler/problem_072/sol2.py) * Problem 073 * [Sol1](project_euler/problem_073/sol1.py) * Problem 074 * [Sol1](project_euler/problem_074/sol1.py) * [Sol2](project_euler/problem_074/sol2.py) * Problem 075 * [Sol1](project_euler/problem_075/sol1.py) * Problem 076 * [Sol1](project_euler/problem_076/sol1.py) * Problem 077 * [Sol1](project_euler/problem_077/sol1.py) * Problem 078 * [Sol1](project_euler/problem_078/sol1.py) * Problem 079 * [Sol1](project_euler/problem_079/sol1.py) * Problem 080 * [Sol1](project_euler/problem_080/sol1.py) * Problem 081 * [Sol1](project_euler/problem_081/sol1.py) * Problem 082 * [Sol1](project_euler/problem_082/sol1.py) * Problem 085 * [Sol1](project_euler/problem_085/sol1.py) * Problem 086 * [Sol1](project_euler/problem_086/sol1.py) * Problem 087 * [Sol1](project_euler/problem_087/sol1.py) * Problem 089 * [Sol1](project_euler/problem_089/sol1.py) * Problem 091 * [Sol1](project_euler/problem_091/sol1.py) * Problem 092 * [Sol1](project_euler/problem_092/sol1.py) * Problem 094 * [Sol1](project_euler/problem_094/sol1.py) * Problem 097 * [Sol1](project_euler/problem_097/sol1.py) * Problem 099 * [Sol1](project_euler/problem_099/sol1.py) * Problem 100 * [Sol1](project_euler/problem_100/sol1.py) * Problem 101 * [Sol1](project_euler/problem_101/sol1.py) * Problem 102 * [Sol1](project_euler/problem_102/sol1.py) * Problem 104 * [Sol1](project_euler/problem_104/sol1.py) * Problem 107 * [Sol1](project_euler/problem_107/sol1.py) * Problem 109 * [Sol1](project_euler/problem_109/sol1.py) * Problem 112 * [Sol1](project_euler/problem_112/sol1.py) * Problem 113 * [Sol1](project_euler/problem_113/sol1.py) * Problem 114 * [Sol1](project_euler/problem_114/sol1.py) * Problem 115 * [Sol1](project_euler/problem_115/sol1.py) * Problem 116 * [Sol1](project_euler/problem_116/sol1.py) * Problem 117 * [Sol1](project_euler/problem_117/sol1.py) * Problem 119 * [Sol1](project_euler/problem_119/sol1.py) * Problem 120 * [Sol1](project_euler/problem_120/sol1.py) * Problem 121 * [Sol1](project_euler/problem_121/sol1.py) * Problem 123 * [Sol1](project_euler/problem_123/sol1.py) * Problem 125 * [Sol1](project_euler/problem_125/sol1.py) * Problem 129 * [Sol1](project_euler/problem_129/sol1.py) * Problem 131 * [Sol1](project_euler/problem_131/sol1.py) * Problem 135 * [Sol1](project_euler/problem_135/sol1.py) * Problem 144 * [Sol1](project_euler/problem_144/sol1.py) * Problem 145 * [Sol1](project_euler/problem_145/sol1.py) * Problem 173 * [Sol1](project_euler/problem_173/sol1.py) * Problem 174 * [Sol1](project_euler/problem_174/sol1.py) * Problem 180 * [Sol1](project_euler/problem_180/sol1.py) * Problem 187 * [Sol1](project_euler/problem_187/sol1.py) * Problem 188 * [Sol1](project_euler/problem_188/sol1.py) * Problem 191 * [Sol1](project_euler/problem_191/sol1.py) * Problem 203 * [Sol1](project_euler/problem_203/sol1.py) * Problem 205 * [Sol1](project_euler/problem_205/sol1.py) * Problem 206 * [Sol1](project_euler/problem_206/sol1.py) * Problem 207 * [Sol1](project_euler/problem_207/sol1.py) * Problem 234 * [Sol1](project_euler/problem_234/sol1.py) * Problem 301 * [Sol1](project_euler/problem_301/sol1.py) * Problem 493 * [Sol1](project_euler/problem_493/sol1.py) * Problem 551 * [Sol1](project_euler/problem_551/sol1.py) * Problem 587 * [Sol1](project_euler/problem_587/sol1.py) * Problem 686 * [Sol1](project_euler/problem_686/sol1.py) * Problem 800 * [Sol1](project_euler/problem_800/sol1.py) ## Quantum * [Q Fourier Transform](quantum/q_fourier_transform.py) ## Scheduling * [First Come First Served](scheduling/first_come_first_served.py) * [Highest Response Ratio Next](scheduling/highest_response_ratio_next.py) * [Job Sequencing With Deadline](scheduling/job_sequencing_with_deadline.py) * [Multi Level Feedback Queue](scheduling/multi_level_feedback_queue.py) * [Non Preemptive Shortest Job First](scheduling/non_preemptive_shortest_job_first.py) * [Round Robin](scheduling/round_robin.py) * [Shortest Job First](scheduling/shortest_job_first.py) ## Searches * [Binary Search](searches/binary_search.py) * [Binary Tree Traversal](searches/binary_tree_traversal.py) * [Double Linear Search](searches/double_linear_search.py) * [Double Linear Search Recursion](searches/double_linear_search_recursion.py) * [Fibonacci Search](searches/fibonacci_search.py) * [Hill Climbing](searches/hill_climbing.py) * [Interpolation Search](searches/interpolation_search.py) * [Jump Search](searches/jump_search.py) * [Linear Search](searches/linear_search.py) * [Quick Select](searches/quick_select.py) * [Sentinel Linear Search](searches/sentinel_linear_search.py) * [Simple Binary Search](searches/simple_binary_search.py) * [Simulated Annealing](searches/simulated_annealing.py) * [Tabu Search](searches/tabu_search.py) * [Ternary Search](searches/ternary_search.py) ## Sorts * [Bead Sort](sorts/bead_sort.py) * [Binary Insertion Sort](sorts/binary_insertion_sort.py) * [Bitonic Sort](sorts/bitonic_sort.py) * [Bogo Sort](sorts/bogo_sort.py) * [Bubble Sort](sorts/bubble_sort.py) * [Bucket Sort](sorts/bucket_sort.py) * [Circle Sort](sorts/circle_sort.py) * [Cocktail Shaker Sort](sorts/cocktail_shaker_sort.py) * [Comb Sort](sorts/comb_sort.py) * [Counting Sort](sorts/counting_sort.py) * [Cycle Sort](sorts/cycle_sort.py) * [Double Sort](sorts/double_sort.py) * [Dutch National Flag Sort](sorts/dutch_national_flag_sort.py) * [Exchange Sort](sorts/exchange_sort.py) * [External Sort](sorts/external_sort.py) * [Gnome Sort](sorts/gnome_sort.py) * [Heap Sort](sorts/heap_sort.py) * [Insertion Sort](sorts/insertion_sort.py) * [Intro Sort](sorts/intro_sort.py) * [Iterative Merge Sort](sorts/iterative_merge_sort.py) * [Merge Insertion Sort](sorts/merge_insertion_sort.py) * [Merge Sort](sorts/merge_sort.py) * [Msd Radix Sort](sorts/msd_radix_sort.py) * [Natural Sort](sorts/natural_sort.py) * [Odd Even Sort](sorts/odd_even_sort.py) * [Odd Even Transposition Parallel](sorts/odd_even_transposition_parallel.py) * [Odd Even Transposition Single Threaded](sorts/odd_even_transposition_single_threaded.py) * [Pancake Sort](sorts/pancake_sort.py) * [Patience Sort](sorts/patience_sort.py) * [Pigeon Sort](sorts/pigeon_sort.py) * [Pigeonhole Sort](sorts/pigeonhole_sort.py) * [Quick Sort](sorts/quick_sort.py) * [Quick Sort 3 Partition](sorts/quick_sort_3_partition.py) * [Radix Sort](sorts/radix_sort.py) * [Recursive Bubble Sort](sorts/recursive_bubble_sort.py) * [Recursive Insertion Sort](sorts/recursive_insertion_sort.py) * [Recursive Mergesort Array](sorts/recursive_mergesort_array.py) * [Recursive Quick Sort](sorts/recursive_quick_sort.py) * [Selection Sort](sorts/selection_sort.py) * [Shell Sort](sorts/shell_sort.py) * [Shrink Shell Sort](sorts/shrink_shell_sort.py) * [Slowsort](sorts/slowsort.py) * [Stooge Sort](sorts/stooge_sort.py) * [Strand Sort](sorts/strand_sort.py) * [Tim Sort](sorts/tim_sort.py) * [Topological Sort](sorts/topological_sort.py) * [Tree Sort](sorts/tree_sort.py) * [Unknown Sort](sorts/unknown_sort.py) * [Wiggle Sort](sorts/wiggle_sort.py) ## Strings * [Aho Corasick](strings/aho_corasick.py) * [Alternative String Arrange](strings/alternative_string_arrange.py) * [Anagrams](strings/anagrams.py) * [Autocomplete Using Trie](strings/autocomplete_using_trie.py) * [Barcode Validator](strings/barcode_validator.py) * [Boyer Moore Search](strings/boyer_moore_search.py) * [Can String Be Rearranged As Palindrome](strings/can_string_be_rearranged_as_palindrome.py) * [Capitalize](strings/capitalize.py) * [Check Anagrams](strings/check_anagrams.py) * [Credit Card Validator](strings/credit_card_validator.py) * [Detecting English Programmatically](strings/detecting_english_programmatically.py) * [Dna](strings/dna.py) * [Frequency Finder](strings/frequency_finder.py) * [Hamming Distance](strings/hamming_distance.py) * [Indian Phone Validator](strings/indian_phone_validator.py) * [Is Contains Unique Chars](strings/is_contains_unique_chars.py) * [Is Isogram](strings/is_isogram.py) * [Is Pangram](strings/is_pangram.py) * [Is Spain National Id](strings/is_spain_national_id.py) * [Is Srilankan Phone Number](strings/is_srilankan_phone_number.py) * [Is Valid Email Address](strings/is_valid_email_address.py) * [Jaro Winkler](strings/jaro_winkler.py) * [Join](strings/join.py) * [Knuth Morris Pratt](strings/knuth_morris_pratt.py) * [Levenshtein Distance](strings/levenshtein_distance.py) * [Lower](strings/lower.py) * [Manacher](strings/manacher.py) * [Min Cost String Conversion](strings/min_cost_string_conversion.py) * [Naive String Search](strings/naive_string_search.py) * [Ngram](strings/ngram.py) * [Palindrome](strings/palindrome.py) * [Prefix Function](strings/prefix_function.py) * [Rabin Karp](strings/rabin_karp.py) * [Remove Duplicate](strings/remove_duplicate.py) * [Reverse Letters](strings/reverse_letters.py) * [Reverse Long Words](strings/reverse_long_words.py) * [Reverse Words](strings/reverse_words.py) * [Snake Case To Camel Pascal Case](strings/snake_case_to_camel_pascal_case.py) * [Split](strings/split.py) * [String Switch Case](strings/string_switch_case.py) * [Text Justification](strings/text_justification.py) * [Top K Frequent Words](strings/top_k_frequent_words.py) * [Upper](strings/upper.py) * [Wave](strings/wave.py) * [Wildcard Pattern Matching](strings/wildcard_pattern_matching.py) * [Word Occurrence](strings/word_occurrence.py) * [Word Patterns](strings/word_patterns.py) * [Z Function](strings/z_function.py) ## Web Programming * [Co2 Emission](web_programming/co2_emission.py) * [Covid Stats Via Xpath](web_programming/covid_stats_via_xpath.py) * [Crawl Google Results](web_programming/crawl_google_results.py) * [Crawl Google Scholar Citation](web_programming/crawl_google_scholar_citation.py) * [Currency Converter](web_programming/currency_converter.py) * [Current Stock Price](web_programming/current_stock_price.py) * [Current Weather](web_programming/current_weather.py) * [Daily Horoscope](web_programming/daily_horoscope.py) * [Download Images From Google Query](web_programming/download_images_from_google_query.py) * [Emails From Url](web_programming/emails_from_url.py) * [Fetch Anime And Play](web_programming/fetch_anime_and_play.py) * [Fetch Bbc News](web_programming/fetch_bbc_news.py) * [Fetch Github Info](web_programming/fetch_github_info.py) * [Fetch Jobs](web_programming/fetch_jobs.py) * [Fetch Quotes](web_programming/fetch_quotes.py) * [Fetch Well Rx Price](web_programming/fetch_well_rx_price.py) * [Get Amazon Product Data](web_programming/get_amazon_product_data.py) * [Get Imdb Top 250 Movies Csv](web_programming/get_imdb_top_250_movies_csv.py) * [Get Imdbtop](web_programming/get_imdbtop.py) * [Get Top Billionaires](web_programming/get_top_billionaires.py) * [Get Top Hn Posts](web_programming/get_top_hn_posts.py) * [Get User Tweets](web_programming/get_user_tweets.py) * [Giphy](web_programming/giphy.py) * [Instagram Crawler](web_programming/instagram_crawler.py) * [Instagram Pic](web_programming/instagram_pic.py) * [Instagram Video](web_programming/instagram_video.py) * [Nasa Data](web_programming/nasa_data.py) * [Open Google Results](web_programming/open_google_results.py) * [Random Anime Character](web_programming/random_anime_character.py) * [Recaptcha Verification](web_programming/recaptcha_verification.py) * [Reddit](web_programming/reddit.py) * [Search Books By Isbn](web_programming/search_books_by_isbn.py) * [Slack Message](web_programming/slack_message.py) * [Test Fetch Github Info](web_programming/test_fetch_github_info.py) * [World Covid19 Stats](web_programming/world_covid19_stats.py)
## Arithmetic Analysis * [Bisection](arithmetic_analysis/bisection.py) * [Gaussian Elimination](arithmetic_analysis/gaussian_elimination.py) * [In Static Equilibrium](arithmetic_analysis/in_static_equilibrium.py) * [Intersection](arithmetic_analysis/intersection.py) * [Jacobi Iteration Method](arithmetic_analysis/jacobi_iteration_method.py) * [Lu Decomposition](arithmetic_analysis/lu_decomposition.py) * [Newton Forward Interpolation](arithmetic_analysis/newton_forward_interpolation.py) * [Newton Method](arithmetic_analysis/newton_method.py) * [Newton Raphson](arithmetic_analysis/newton_raphson.py) * [Newton Raphson New](arithmetic_analysis/newton_raphson_new.py) * [Secant Method](arithmetic_analysis/secant_method.py) ## Audio Filters * [Butterworth Filter](audio_filters/butterworth_filter.py) * [Iir Filter](audio_filters/iir_filter.py) * [Show Response](audio_filters/show_response.py) ## Backtracking * [All Combinations](backtracking/all_combinations.py) * [All Permutations](backtracking/all_permutations.py) * [All Subsequences](backtracking/all_subsequences.py) * [Coloring](backtracking/coloring.py) * [Combination Sum](backtracking/combination_sum.py) * [Hamiltonian Cycle](backtracking/hamiltonian_cycle.py) * [Knight Tour](backtracking/knight_tour.py) * [Minimax](backtracking/minimax.py) * [N Queens](backtracking/n_queens.py) * [N Queens Math](backtracking/n_queens_math.py) * [Power Sum](backtracking/power_sum.py) * [Rat In Maze](backtracking/rat_in_maze.py) * [Sudoku](backtracking/sudoku.py) * [Sum Of Subsets](backtracking/sum_of_subsets.py) * [Word Search](backtracking/word_search.py) ## Bit Manipulation * [Binary And Operator](bit_manipulation/binary_and_operator.py) * [Binary Count Setbits](bit_manipulation/binary_count_setbits.py) * [Binary Count Trailing Zeros](bit_manipulation/binary_count_trailing_zeros.py) * [Binary Or Operator](bit_manipulation/binary_or_operator.py) * [Binary Shifts](bit_manipulation/binary_shifts.py) * [Binary Twos Complement](bit_manipulation/binary_twos_complement.py) * [Binary Xor Operator](bit_manipulation/binary_xor_operator.py) * [Bitwise Addition Recursive](bit_manipulation/bitwise_addition_recursive.py) * [Count 1S Brian Kernighan Method](bit_manipulation/count_1s_brian_kernighan_method.py) * [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py) * [Gray Code Sequence](bit_manipulation/gray_code_sequence.py) * [Highest Set Bit](bit_manipulation/highest_set_bit.py) * [Index Of Rightmost Set Bit](bit_manipulation/index_of_rightmost_set_bit.py) * [Is Even](bit_manipulation/is_even.py) * [Is Power Of Two](bit_manipulation/is_power_of_two.py) * [Missing Number](bit_manipulation/missing_number.py) * [Numbers Different Signs](bit_manipulation/numbers_different_signs.py) * [Reverse Bits](bit_manipulation/reverse_bits.py) * [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py) ## Blockchain * [Chinese Remainder Theorem](blockchain/chinese_remainder_theorem.py) * [Diophantine Equation](blockchain/diophantine_equation.py) * [Modular Division](blockchain/modular_division.py) ## Boolean Algebra * [And Gate](boolean_algebra/and_gate.py) * [Nand Gate](boolean_algebra/nand_gate.py) * [Nor Gate](boolean_algebra/nor_gate.py) * [Not Gate](boolean_algebra/not_gate.py) * [Or Gate](boolean_algebra/or_gate.py) * [Quine Mc Cluskey](boolean_algebra/quine_mc_cluskey.py) * [Xnor Gate](boolean_algebra/xnor_gate.py) * [Xor Gate](boolean_algebra/xor_gate.py) ## Cellular Automata * [Conways Game Of Life](cellular_automata/conways_game_of_life.py) * [Game Of Life](cellular_automata/game_of_life.py) * [Langtons Ant](cellular_automata/langtons_ant.py) * [Nagel Schrekenberg](cellular_automata/nagel_schrekenberg.py) * [One Dimensional](cellular_automata/one_dimensional.py) * [Wa Tor](cellular_automata/wa_tor.py) ## Ciphers * [A1Z26](ciphers/a1z26.py) * [Affine Cipher](ciphers/affine_cipher.py) * [Atbash](ciphers/atbash.py) * [Autokey](ciphers/autokey.py) * [Baconian Cipher](ciphers/baconian_cipher.py) * [Base16](ciphers/base16.py) * [Base32](ciphers/base32.py) * [Base64](ciphers/base64.py) * [Base85](ciphers/base85.py) * [Beaufort Cipher](ciphers/beaufort_cipher.py) * [Bifid](ciphers/bifid.py) * [Brute Force Caesar Cipher](ciphers/brute_force_caesar_cipher.py) * [Caesar Cipher](ciphers/caesar_cipher.py) * [Cryptomath Module](ciphers/cryptomath_module.py) * [Decrypt Caesar With Chi Squared](ciphers/decrypt_caesar_with_chi_squared.py) * [Deterministic Miller Rabin](ciphers/deterministic_miller_rabin.py) * [Diffie](ciphers/diffie.py) * [Diffie Hellman](ciphers/diffie_hellman.py) * [Elgamal Key Generator](ciphers/elgamal_key_generator.py) * [Enigma Machine2](ciphers/enigma_machine2.py) * [Hill Cipher](ciphers/hill_cipher.py) * [Mixed Keyword Cypher](ciphers/mixed_keyword_cypher.py) * [Mono Alphabetic Ciphers](ciphers/mono_alphabetic_ciphers.py) * [Morse Code](ciphers/morse_code.py) * [Onepad Cipher](ciphers/onepad_cipher.py) * [Playfair Cipher](ciphers/playfair_cipher.py) * [Polybius](ciphers/polybius.py) * [Porta Cipher](ciphers/porta_cipher.py) * [Rabin Miller](ciphers/rabin_miller.py) * [Rail Fence Cipher](ciphers/rail_fence_cipher.py) * [Rot13](ciphers/rot13.py) * [Rsa Cipher](ciphers/rsa_cipher.py) * [Rsa Factorization](ciphers/rsa_factorization.py) * [Rsa Key Generator](ciphers/rsa_key_generator.py) * [Shuffled Shift Cipher](ciphers/shuffled_shift_cipher.py) * [Simple Keyword Cypher](ciphers/simple_keyword_cypher.py) * [Simple Substitution Cipher](ciphers/simple_substitution_cipher.py) * [Trafid Cipher](ciphers/trafid_cipher.py) * [Transposition Cipher](ciphers/transposition_cipher.py) * [Transposition Cipher Encrypt Decrypt File](ciphers/transposition_cipher_encrypt_decrypt_file.py) * [Vigenere Cipher](ciphers/vigenere_cipher.py) * [Xor Cipher](ciphers/xor_cipher.py) ## Compression * [Burrows Wheeler](compression/burrows_wheeler.py) * [Huffman](compression/huffman.py) * [Lempel Ziv](compression/lempel_ziv.py) * [Lempel Ziv Decompress](compression/lempel_ziv_decompress.py) * [Lz77](compression/lz77.py) * [Peak Signal To Noise Ratio](compression/peak_signal_to_noise_ratio.py) * [Run Length Encoding](compression/run_length_encoding.py) ## Computer Vision * [Flip Augmentation](computer_vision/flip_augmentation.py) * [Haralick Descriptors](computer_vision/haralick_descriptors.py) * [Harris Corner](computer_vision/harris_corner.py) * [Horn Schunck](computer_vision/horn_schunck.py) * [Mean Threshold](computer_vision/mean_threshold.py) * [Mosaic Augmentation](computer_vision/mosaic_augmentation.py) * [Pooling Functions](computer_vision/pooling_functions.py) ## Conversions * [Astronomical Length Scale Conversion](conversions/astronomical_length_scale_conversion.py) * [Binary To Decimal](conversions/binary_to_decimal.py) * [Binary To Hexadecimal](conversions/binary_to_hexadecimal.py) * [Binary To Octal](conversions/binary_to_octal.py) * [Convert Number To Words](conversions/convert_number_to_words.py) * [Decimal To Any](conversions/decimal_to_any.py) * [Decimal To Binary](conversions/decimal_to_binary.py) * [Decimal To Hexadecimal](conversions/decimal_to_hexadecimal.py) * [Decimal To Octal](conversions/decimal_to_octal.py) * [Energy Conversions](conversions/energy_conversions.py) * [Excel Title To Column](conversions/excel_title_to_column.py) * [Hex To Bin](conversions/hex_to_bin.py) * [Hexadecimal To Decimal](conversions/hexadecimal_to_decimal.py) * [Length Conversion](conversions/length_conversion.py) * [Molecular Chemistry](conversions/molecular_chemistry.py) * [Octal To Binary](conversions/octal_to_binary.py) * [Octal To Decimal](conversions/octal_to_decimal.py) * [Prefix Conversions](conversions/prefix_conversions.py) * [Prefix Conversions String](conversions/prefix_conversions_string.py) * [Pressure Conversions](conversions/pressure_conversions.py) * [Rgb Hsv Conversion](conversions/rgb_hsv_conversion.py) * [Roman Numerals](conversions/roman_numerals.py) * [Speed Conversions](conversions/speed_conversions.py) * [Temperature Conversions](conversions/temperature_conversions.py) * [Volume Conversions](conversions/volume_conversions.py) * [Weight Conversion](conversions/weight_conversion.py) ## Data Structures * Arrays * [Permutations](data_structures/arrays/permutations.py) * [Prefix Sum](data_structures/arrays/prefix_sum.py) * [Product Sum](data_structures/arrays/product_sum.py) * Binary Tree * [Avl Tree](data_structures/binary_tree/avl_tree.py) * [Basic Binary Tree](data_structures/binary_tree/basic_binary_tree.py) * [Binary Search Tree](data_structures/binary_tree/binary_search_tree.py) * [Binary Search Tree Recursive](data_structures/binary_tree/binary_search_tree_recursive.py) * [Binary Tree Mirror](data_structures/binary_tree/binary_tree_mirror.py) * [Binary Tree Node Sum](data_structures/binary_tree/binary_tree_node_sum.py) * [Binary Tree Path Sum](data_structures/binary_tree/binary_tree_path_sum.py) * [Binary Tree Traversals](data_structures/binary_tree/binary_tree_traversals.py) * [Diff Views Of Binary Tree](data_structures/binary_tree/diff_views_of_binary_tree.py) * [Distribute Coins](data_structures/binary_tree/distribute_coins.py) * [Fenwick Tree](data_structures/binary_tree/fenwick_tree.py) * [Inorder Tree Traversal 2022](data_structures/binary_tree/inorder_tree_traversal_2022.py) * [Is Bst](data_structures/binary_tree/is_bst.py) * [Lazy Segment Tree](data_structures/binary_tree/lazy_segment_tree.py) * [Lowest Common Ancestor](data_structures/binary_tree/lowest_common_ancestor.py) * [Maximum Fenwick Tree](data_structures/binary_tree/maximum_fenwick_tree.py) * [Merge Two Binary Trees](data_structures/binary_tree/merge_two_binary_trees.py) * [Non Recursive Segment Tree](data_structures/binary_tree/non_recursive_segment_tree.py) * [Number Of Possible Binary Trees](data_structures/binary_tree/number_of_possible_binary_trees.py) * [Red Black Tree](data_structures/binary_tree/red_black_tree.py) * [Segment Tree](data_structures/binary_tree/segment_tree.py) * [Segment Tree Other](data_structures/binary_tree/segment_tree_other.py) * [Treap](data_structures/binary_tree/treap.py) * [Wavelet Tree](data_structures/binary_tree/wavelet_tree.py) * Disjoint Set * [Alternate Disjoint Set](data_structures/disjoint_set/alternate_disjoint_set.py) * [Disjoint Set](data_structures/disjoint_set/disjoint_set.py) * Hashing * [Bloom Filter](data_structures/hashing/bloom_filter.py) * [Double Hash](data_structures/hashing/double_hash.py) * [Hash Map](data_structures/hashing/hash_map.py) * [Hash Table](data_structures/hashing/hash_table.py) * [Hash Table With Linked List](data_structures/hashing/hash_table_with_linked_list.py) * Number Theory * [Prime Numbers](data_structures/hashing/number_theory/prime_numbers.py) * [Quadratic Probing](data_structures/hashing/quadratic_probing.py) * Tests * [Test Hash Map](data_structures/hashing/tests/test_hash_map.py) * Heap * [Binomial Heap](data_structures/heap/binomial_heap.py) * [Heap](data_structures/heap/heap.py) * [Heap Generic](data_structures/heap/heap_generic.py) * [Max Heap](data_structures/heap/max_heap.py) * [Min Heap](data_structures/heap/min_heap.py) * [Randomized Heap](data_structures/heap/randomized_heap.py) * [Skew Heap](data_structures/heap/skew_heap.py) * Linked List * [Circular Linked List](data_structures/linked_list/circular_linked_list.py) * [Deque Doubly](data_structures/linked_list/deque_doubly.py) * [Doubly Linked List](data_structures/linked_list/doubly_linked_list.py) * [Doubly Linked List Two](data_structures/linked_list/doubly_linked_list_two.py) * [From Sequence](data_structures/linked_list/from_sequence.py) * [Has Loop](data_structures/linked_list/has_loop.py) * [Is Palindrome](data_structures/linked_list/is_palindrome.py) * [Merge Two Lists](data_structures/linked_list/merge_two_lists.py) * [Middle Element Of Linked List](data_structures/linked_list/middle_element_of_linked_list.py) * [Print Reverse](data_structures/linked_list/print_reverse.py) * [Reverse K Group](data_structures/linked_list/reverse_k_group.py) * [Rotate To The Right](data_structures/linked_list/rotate_to_the_right.py) * [Singly Linked List](data_structures/linked_list/singly_linked_list.py) * [Skip List](data_structures/linked_list/skip_list.py) * [Swap Nodes](data_structures/linked_list/swap_nodes.py) * Queue * [Circular Queue](data_structures/queue/circular_queue.py) * [Circular Queue Linked List](data_structures/queue/circular_queue_linked_list.py) * [Double Ended Queue](data_structures/queue/double_ended_queue.py) * [Linked Queue](data_structures/queue/linked_queue.py) * [Priority Queue Using List](data_structures/queue/priority_queue_using_list.py) * [Queue By List](data_structures/queue/queue_by_list.py) * [Queue By Two Stacks](data_structures/queue/queue_by_two_stacks.py) * [Queue On Pseudo Stack](data_structures/queue/queue_on_pseudo_stack.py) * Stacks * [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py) * [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py) * [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py) * [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py) * [Next Greater Element](data_structures/stacks/next_greater_element.py) * [Postfix Evaluation](data_structures/stacks/postfix_evaluation.py) * [Prefix Evaluation](data_structures/stacks/prefix_evaluation.py) * [Stack](data_structures/stacks/stack.py) * [Stack With Doubly Linked List](data_structures/stacks/stack_with_doubly_linked_list.py) * [Stack With Singly Linked List](data_structures/stacks/stack_with_singly_linked_list.py) * [Stock Span Problem](data_structures/stacks/stock_span_problem.py) * Trie * [Radix Tree](data_structures/trie/radix_tree.py) * [Trie](data_structures/trie/trie.py) ## Digital Image Processing * [Change Brightness](digital_image_processing/change_brightness.py) * [Change Contrast](digital_image_processing/change_contrast.py) * [Convert To Negative](digital_image_processing/convert_to_negative.py) * Dithering * [Burkes](digital_image_processing/dithering/burkes.py) * Edge Detection * [Canny](digital_image_processing/edge_detection/canny.py) * Filters * [Bilateral Filter](digital_image_processing/filters/bilateral_filter.py) * [Convolve](digital_image_processing/filters/convolve.py) * [Gabor Filter](digital_image_processing/filters/gabor_filter.py) * [Gaussian Filter](digital_image_processing/filters/gaussian_filter.py) * [Local Binary Pattern](digital_image_processing/filters/local_binary_pattern.py) * [Median Filter](digital_image_processing/filters/median_filter.py) * [Sobel Filter](digital_image_processing/filters/sobel_filter.py) * Histogram Equalization * [Histogram Stretch](digital_image_processing/histogram_equalization/histogram_stretch.py) * [Index Calculation](digital_image_processing/index_calculation.py) * Morphological Operations * [Dilation Operation](digital_image_processing/morphological_operations/dilation_operation.py) * [Erosion Operation](digital_image_processing/morphological_operations/erosion_operation.py) * Resize * [Resize](digital_image_processing/resize/resize.py) * Rotation * [Rotation](digital_image_processing/rotation/rotation.py) * [Sepia](digital_image_processing/sepia.py) * [Test Digital Image Processing](digital_image_processing/test_digital_image_processing.py) ## Divide And Conquer * [Closest Pair Of Points](divide_and_conquer/closest_pair_of_points.py) * [Convex Hull](divide_and_conquer/convex_hull.py) * [Heaps Algorithm](divide_and_conquer/heaps_algorithm.py) * [Heaps Algorithm Iterative](divide_and_conquer/heaps_algorithm_iterative.py) * [Inversions](divide_and_conquer/inversions.py) * [Kth Order Statistic](divide_and_conquer/kth_order_statistic.py) * [Max Difference Pair](divide_and_conquer/max_difference_pair.py) * [Max Subarray](divide_and_conquer/max_subarray.py) * [Mergesort](divide_and_conquer/mergesort.py) * [Peak](divide_and_conquer/peak.py) * [Power](divide_and_conquer/power.py) * [Strassen Matrix Multiplication](divide_and_conquer/strassen_matrix_multiplication.py) ## Dynamic Programming * [Abbreviation](dynamic_programming/abbreviation.py) * [All Construct](dynamic_programming/all_construct.py) * [Bitmask](dynamic_programming/bitmask.py) * [Catalan Numbers](dynamic_programming/catalan_numbers.py) * [Climbing Stairs](dynamic_programming/climbing_stairs.py) * [Combination Sum Iv](dynamic_programming/combination_sum_iv.py) * [Edit Distance](dynamic_programming/edit_distance.py) * [Factorial](dynamic_programming/factorial.py) * [Fast Fibonacci](dynamic_programming/fast_fibonacci.py) * [Fibonacci](dynamic_programming/fibonacci.py) * [Fizz Buzz](dynamic_programming/fizz_buzz.py) * [Floyd Warshall](dynamic_programming/floyd_warshall.py) * [Integer Partition](dynamic_programming/integer_partition.py) * [Iterating Through Submasks](dynamic_programming/iterating_through_submasks.py) * [Knapsack](dynamic_programming/knapsack.py) * [Longest Common Subsequence](dynamic_programming/longest_common_subsequence.py) * [Longest Common Substring](dynamic_programming/longest_common_substring.py) * [Longest Increasing Subsequence](dynamic_programming/longest_increasing_subsequence.py) * [Longest Increasing Subsequence O(Nlogn)](dynamic_programming/longest_increasing_subsequence_o(nlogn).py) * [Longest Sub Array](dynamic_programming/longest_sub_array.py) * [Matrix Chain Order](dynamic_programming/matrix_chain_order.py) * [Max Non Adjacent Sum](dynamic_programming/max_non_adjacent_sum.py) * [Max Product Subarray](dynamic_programming/max_product_subarray.py) * [Max Subarray Sum](dynamic_programming/max_subarray_sum.py) * [Min Distance Up Bottom](dynamic_programming/min_distance_up_bottom.py) * [Minimum Coin Change](dynamic_programming/minimum_coin_change.py) * [Minimum Cost Path](dynamic_programming/minimum_cost_path.py) * [Minimum Partition](dynamic_programming/minimum_partition.py) * [Minimum Size Subarray Sum](dynamic_programming/minimum_size_subarray_sum.py) * [Minimum Squares To Represent A Number](dynamic_programming/minimum_squares_to_represent_a_number.py) * [Minimum Steps To One](dynamic_programming/minimum_steps_to_one.py) * [Minimum Tickets Cost](dynamic_programming/minimum_tickets_cost.py) * [Optimal Binary Search Tree](dynamic_programming/optimal_binary_search_tree.py) * [Palindrome Partitioning](dynamic_programming/palindrome_partitioning.py) * [Regex Match](dynamic_programming/regex_match.py) * [Rod Cutting](dynamic_programming/rod_cutting.py) * [Smith Waterman](dynamic_programming/smith_waterman.py) * [Subset Generation](dynamic_programming/subset_generation.py) * [Sum Of Subset](dynamic_programming/sum_of_subset.py) * [Tribonacci](dynamic_programming/tribonacci.py) * [Viterbi](dynamic_programming/viterbi.py) * [Word Break](dynamic_programming/word_break.py) ## Electronics * [Apparent Power](electronics/apparent_power.py) * [Builtin Voltage](electronics/builtin_voltage.py) * [Carrier Concentration](electronics/carrier_concentration.py) * [Circular Convolution](electronics/circular_convolution.py) * [Coulombs Law](electronics/coulombs_law.py) * [Electric Conductivity](electronics/electric_conductivity.py) * [Electric Power](electronics/electric_power.py) * [Electrical Impedance](electronics/electrical_impedance.py) * [Ind Reactance](electronics/ind_reactance.py) * [Ohms Law](electronics/ohms_law.py) * [Real And Reactive Power](electronics/real_and_reactive_power.py) * [Resistor Equivalence](electronics/resistor_equivalence.py) * [Resonant Frequency](electronics/resonant_frequency.py) ## File Transfer * [Receive File](file_transfer/receive_file.py) * [Send File](file_transfer/send_file.py) * Tests * [Test Send File](file_transfer/tests/test_send_file.py) ## Financial * [Equated Monthly Installments](financial/equated_monthly_installments.py) * [Interest](financial/interest.py) * [Present Value](financial/present_value.py) * [Price Plus Tax](financial/price_plus_tax.py) ## Fractals * [Julia Sets](fractals/julia_sets.py) * [Koch Snowflake](fractals/koch_snowflake.py) * [Mandelbrot](fractals/mandelbrot.py) * [Sierpinski Triangle](fractals/sierpinski_triangle.py) ## Genetic Algorithm * [Basic String](genetic_algorithm/basic_string.py) ## Geodesy * [Haversine Distance](geodesy/haversine_distance.py) * [Lamberts Ellipsoidal Distance](geodesy/lamberts_ellipsoidal_distance.py) ## Graphics * [Bezier Curve](graphics/bezier_curve.py) * [Vector3 For 2D Rendering](graphics/vector3_for_2d_rendering.py) ## Graphs * [A Star](graphs/a_star.py) * [Articulation Points](graphs/articulation_points.py) * [Basic Graphs](graphs/basic_graphs.py) * [Bellman Ford](graphs/bellman_ford.py) * [Bi Directional Dijkstra](graphs/bi_directional_dijkstra.py) * [Bidirectional A Star](graphs/bidirectional_a_star.py) * [Bidirectional Breadth First Search](graphs/bidirectional_breadth_first_search.py) * [Boruvka](graphs/boruvka.py) * [Breadth First Search](graphs/breadth_first_search.py) * [Breadth First Search 2](graphs/breadth_first_search_2.py) * [Breadth First Search Shortest Path](graphs/breadth_first_search_shortest_path.py) * [Breadth First Search Shortest Path 2](graphs/breadth_first_search_shortest_path_2.py) * [Breadth First Search Zero One Shortest Path](graphs/breadth_first_search_zero_one_shortest_path.py) * [Check Bipartite Graph Bfs](graphs/check_bipartite_graph_bfs.py) * [Check Bipartite Graph Dfs](graphs/check_bipartite_graph_dfs.py) * [Check Cycle](graphs/check_cycle.py) * [Connected Components](graphs/connected_components.py) * [Depth First Search](graphs/depth_first_search.py) * [Depth First Search 2](graphs/depth_first_search_2.py) * [Dijkstra](graphs/dijkstra.py) * [Dijkstra 2](graphs/dijkstra_2.py) * [Dijkstra Algorithm](graphs/dijkstra_algorithm.py) * [Dijkstra Alternate](graphs/dijkstra_alternate.py) * [Dijkstra Binary Grid](graphs/dijkstra_binary_grid.py) * [Dinic](graphs/dinic.py) * [Directed And Undirected (Weighted) Graph](graphs/directed_and_undirected_(weighted)_graph.py) * [Edmonds Karp Multiple Source And Sink](graphs/edmonds_karp_multiple_source_and_sink.py) * [Eulerian Path And Circuit For Undirected Graph](graphs/eulerian_path_and_circuit_for_undirected_graph.py) * [Even Tree](graphs/even_tree.py) * [Finding Bridges](graphs/finding_bridges.py) * [Frequent Pattern Graph Miner](graphs/frequent_pattern_graph_miner.py) * [G Topological Sort](graphs/g_topological_sort.py) * [Gale Shapley Bigraph](graphs/gale_shapley_bigraph.py) * [Graph Adjacency List](graphs/graph_adjacency_list.py) * [Graph Adjacency Matrix](graphs/graph_adjacency_matrix.py) * [Graph List](graphs/graph_list.py) * [Graphs Floyd Warshall](graphs/graphs_floyd_warshall.py) * [Greedy Best First](graphs/greedy_best_first.py) * [Greedy Min Vertex Cover](graphs/greedy_min_vertex_cover.py) * [Kahns Algorithm Long](graphs/kahns_algorithm_long.py) * [Kahns Algorithm Topo](graphs/kahns_algorithm_topo.py) * [Karger](graphs/karger.py) * [Markov Chain](graphs/markov_chain.py) * [Matching Min Vertex Cover](graphs/matching_min_vertex_cover.py) * [Minimum Path Sum](graphs/minimum_path_sum.py) * [Minimum Spanning Tree Boruvka](graphs/minimum_spanning_tree_boruvka.py) * [Minimum Spanning Tree Kruskal](graphs/minimum_spanning_tree_kruskal.py) * [Minimum Spanning Tree Kruskal2](graphs/minimum_spanning_tree_kruskal2.py) * [Minimum Spanning Tree Prims](graphs/minimum_spanning_tree_prims.py) * [Minimum Spanning Tree Prims2](graphs/minimum_spanning_tree_prims2.py) * [Multi Heuristic Astar](graphs/multi_heuristic_astar.py) * [Page Rank](graphs/page_rank.py) * [Prim](graphs/prim.py) * [Random Graph Generator](graphs/random_graph_generator.py) * [Scc Kosaraju](graphs/scc_kosaraju.py) * [Strongly Connected Components](graphs/strongly_connected_components.py) * [Tarjans Scc](graphs/tarjans_scc.py) * Tests * [Test Min Spanning Tree Kruskal](graphs/tests/test_min_spanning_tree_kruskal.py) * [Test Min Spanning Tree Prim](graphs/tests/test_min_spanning_tree_prim.py) ## Greedy Methods * [Fractional Knapsack](greedy_methods/fractional_knapsack.py) * [Fractional Knapsack 2](greedy_methods/fractional_knapsack_2.py) * [Minimum Waiting Time](greedy_methods/minimum_waiting_time.py) * [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py) ## Hashes * [Adler32](hashes/adler32.py) * [Chaos Machine](hashes/chaos_machine.py) * [Djb2](hashes/djb2.py) * [Elf](hashes/elf.py) * [Enigma Machine](hashes/enigma_machine.py) * [Hamming Code](hashes/hamming_code.py) * [Luhn](hashes/luhn.py) * [Md5](hashes/md5.py) * [Sdbm](hashes/sdbm.py) * [Sha1](hashes/sha1.py) * [Sha256](hashes/sha256.py) ## Knapsack * [Greedy Knapsack](knapsack/greedy_knapsack.py) * [Knapsack](knapsack/knapsack.py) * [Recursive Approach Knapsack](knapsack/recursive_approach_knapsack.py) * Tests * [Test Greedy Knapsack](knapsack/tests/test_greedy_knapsack.py) * [Test Knapsack](knapsack/tests/test_knapsack.py) ## Linear Algebra * Src * [Conjugate Gradient](linear_algebra/src/conjugate_gradient.py) * [Lib](linear_algebra/src/lib.py) * [Polynom For Points](linear_algebra/src/polynom_for_points.py) * [Power Iteration](linear_algebra/src/power_iteration.py) * [Rank Of Matrix](linear_algebra/src/rank_of_matrix.py) * [Rayleigh Quotient](linear_algebra/src/rayleigh_quotient.py) * [Schur Complement](linear_algebra/src/schur_complement.py) * [Test Linear Algebra](linear_algebra/src/test_linear_algebra.py) * [Transformations 2D](linear_algebra/src/transformations_2d.py) ## Linear Programming * [Simplex](linear_programming/simplex.py) ## Machine Learning * [Astar](machine_learning/astar.py) * [Data Transformations](machine_learning/data_transformations.py) * [Decision Tree](machine_learning/decision_tree.py) * [Dimensionality Reduction](machine_learning/dimensionality_reduction.py) * Forecasting * [Run](machine_learning/forecasting/run.py) * [Gradient Descent](machine_learning/gradient_descent.py) * [K Means Clust](machine_learning/k_means_clust.py) * [K Nearest Neighbours](machine_learning/k_nearest_neighbours.py) * [Linear Discriminant Analysis](machine_learning/linear_discriminant_analysis.py) * [Linear Regression](machine_learning/linear_regression.py) * Local Weighted Learning * [Local Weighted Learning](machine_learning/local_weighted_learning/local_weighted_learning.py) * [Logistic Regression](machine_learning/logistic_regression.py) * [Mfcc](machine_learning/mfcc.py) * [Multilayer Perceptron Classifier](machine_learning/multilayer_perceptron_classifier.py) * [Polynomial Regression](machine_learning/polynomial_regression.py) * [Scoring Functions](machine_learning/scoring_functions.py) * [Self Organizing Map](machine_learning/self_organizing_map.py) * [Sequential Minimum Optimization](machine_learning/sequential_minimum_optimization.py) * [Similarity Search](machine_learning/similarity_search.py) * [Support Vector Machines](machine_learning/support_vector_machines.py) * [Word Frequency Functions](machine_learning/word_frequency_functions.py) * [Xgboost Classifier](machine_learning/xgboost_classifier.py) * [Xgboost Regressor](machine_learning/xgboost_regressor.py) ## Maths * [Abs](maths/abs.py) * [Addition Without Arithmetic](maths/addition_without_arithmetic.py) * [Aliquot Sum](maths/aliquot_sum.py) * [Allocation Number](maths/allocation_number.py) * [Arc Length](maths/arc_length.py) * [Area](maths/area.py) * [Area Under Curve](maths/area_under_curve.py) * [Armstrong Numbers](maths/armstrong_numbers.py) * [Automorphic Number](maths/automorphic_number.py) * [Average Absolute Deviation](maths/average_absolute_deviation.py) * [Average Mean](maths/average_mean.py) * [Average Median](maths/average_median.py) * [Average Mode](maths/average_mode.py) * [Bailey Borwein Plouffe](maths/bailey_borwein_plouffe.py) * [Basic Maths](maths/basic_maths.py) * [Binary Exp Mod](maths/binary_exp_mod.py) * [Binary Exponentiation](maths/binary_exponentiation.py) * [Binary Exponentiation 3](maths/binary_exponentiation_3.py) * [Binary Multiplication](maths/binary_multiplication.py) * [Binomial Coefficient](maths/binomial_coefficient.py) * [Binomial Distribution](maths/binomial_distribution.py) * [Bisection](maths/bisection.py) * [Carmichael Number](maths/carmichael_number.py) * [Catalan Number](maths/catalan_number.py) * [Ceil](maths/ceil.py) * [Check Polygon](maths/check_polygon.py) * [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py) * [Collatz Sequence](maths/collatz_sequence.py) * [Combinations](maths/combinations.py) * [Continued Fraction](maths/continued_fraction.py) * [Decimal Isolate](maths/decimal_isolate.py) * [Decimal To Fraction](maths/decimal_to_fraction.py) * [Dodecahedron](maths/dodecahedron.py) * [Double Factorial](maths/double_factorial.py) * [Dual Number Automatic Differentiation](maths/dual_number_automatic_differentiation.py) * [Entropy](maths/entropy.py) * [Euclidean Distance](maths/euclidean_distance.py) * [Euler Method](maths/euler_method.py) * [Euler Modified](maths/euler_modified.py) * [Eulers Totient](maths/eulers_totient.py) * [Extended Euclidean Algorithm](maths/extended_euclidean_algorithm.py) * [Factorial](maths/factorial.py) * [Factors](maths/factors.py) * [Fermat Little Theorem](maths/fermat_little_theorem.py) * [Fibonacci](maths/fibonacci.py) * [Find Max](maths/find_max.py) * [Find Min](maths/find_min.py) * [Floor](maths/floor.py) * [Gamma](maths/gamma.py) * [Gamma Recursive](maths/gamma_recursive.py) * [Gaussian](maths/gaussian.py) * [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py) * [Gcd Of N Numbers](maths/gcd_of_n_numbers.py) * [Greatest Common Divisor](maths/greatest_common_divisor.py) * [Greedy Coin Change](maths/greedy_coin_change.py) * [Hamming Numbers](maths/hamming_numbers.py) * [Hardy Ramanujanalgo](maths/hardy_ramanujanalgo.py) * [Harshad Numbers](maths/harshad_numbers.py) * [Hexagonal Number](maths/hexagonal_number.py) * [Integration By Simpson Approx](maths/integration_by_simpson_approx.py) * [Interquartile Range](maths/interquartile_range.py) * [Is Int Palindrome](maths/is_int_palindrome.py) * [Is Ip V4 Address Valid](maths/is_ip_v4_address_valid.py) * [Is Square Free](maths/is_square_free.py) * [Jaccard Similarity](maths/jaccard_similarity.py) * [Juggler Sequence](maths/juggler_sequence.py) * [Karatsuba](maths/karatsuba.py) * [Krishnamurthy Number](maths/krishnamurthy_number.py) * [Kth Lexicographic Permutation](maths/kth_lexicographic_permutation.py) * [Largest Of Very Large Numbers](maths/largest_of_very_large_numbers.py) * [Least Common Multiple](maths/least_common_multiple.py) * [Line Length](maths/line_length.py) * [Liouville Lambda](maths/liouville_lambda.py) * [Lucas Lehmer Primality Test](maths/lucas_lehmer_primality_test.py) * [Lucas Series](maths/lucas_series.py) * [Maclaurin Series](maths/maclaurin_series.py) * [Manhattan Distance](maths/manhattan_distance.py) * [Matrix Exponentiation](maths/matrix_exponentiation.py) * [Max Sum Sliding Window](maths/max_sum_sliding_window.py) * [Median Of Two Arrays](maths/median_of_two_arrays.py) * [Mobius Function](maths/mobius_function.py) * [Modular Exponential](maths/modular_exponential.py) * [Monte Carlo](maths/monte_carlo.py) * [Monte Carlo Dice](maths/monte_carlo_dice.py) * [Nevilles Method](maths/nevilles_method.py) * [Newton Raphson](maths/newton_raphson.py) * [Number Of Digits](maths/number_of_digits.py) * [Numerical Integration](maths/numerical_integration.py) * [Odd Sieve](maths/odd_sieve.py) * [Perfect Cube](maths/perfect_cube.py) * [Perfect Number](maths/perfect_number.py) * [Perfect Square](maths/perfect_square.py) * [Persistence](maths/persistence.py) * [Pi Generator](maths/pi_generator.py) * [Pi Monte Carlo Estimation](maths/pi_monte_carlo_estimation.py) * [Points Are Collinear 3D](maths/points_are_collinear_3d.py) * [Pollard Rho](maths/pollard_rho.py) * [Polygonal Numbers](maths/polygonal_numbers.py) * [Polynomial Evaluation](maths/polynomial_evaluation.py) * Polynomials * [Single Indeterminate Operations](maths/polynomials/single_indeterminate_operations.py) * [Power Using Recursion](maths/power_using_recursion.py) * [Prime Check](maths/prime_check.py) * [Prime Factors](maths/prime_factors.py) * [Prime Numbers](maths/prime_numbers.py) * [Prime Sieve Eratosthenes](maths/prime_sieve_eratosthenes.py) * [Primelib](maths/primelib.py) * [Print Multiplication Table](maths/print_multiplication_table.py) * [Pronic Number](maths/pronic_number.py) * [Proth Number](maths/proth_number.py) * [Pythagoras](maths/pythagoras.py) * [Qr Decomposition](maths/qr_decomposition.py) * [Quadratic Equations Complex Numbers](maths/quadratic_equations_complex_numbers.py) * [Radians](maths/radians.py) * [Radix2 Fft](maths/radix2_fft.py) * [Relu](maths/relu.py) * [Remove Digit](maths/remove_digit.py) * [Runge Kutta](maths/runge_kutta.py) * [Segmented Sieve](maths/segmented_sieve.py) * Series * [Arithmetic](maths/series/arithmetic.py) * [Geometric](maths/series/geometric.py) * [Geometric Series](maths/series/geometric_series.py) * [Harmonic](maths/series/harmonic.py) * [Harmonic Series](maths/series/harmonic_series.py) * [Hexagonal Numbers](maths/series/hexagonal_numbers.py) * [P Series](maths/series/p_series.py) * [Sieve Of Eratosthenes](maths/sieve_of_eratosthenes.py) * [Sigmoid](maths/sigmoid.py) * [Sigmoid Linear Unit](maths/sigmoid_linear_unit.py) * [Signum](maths/signum.py) * [Simpson Rule](maths/simpson_rule.py) * [Simultaneous Linear Equation Solver](maths/simultaneous_linear_equation_solver.py) * [Sin](maths/sin.py) * [Sock Merchant](maths/sock_merchant.py) * [Softmax](maths/softmax.py) * [Square Root](maths/square_root.py) * [Sum Of Arithmetic Series](maths/sum_of_arithmetic_series.py) * [Sum Of Digits](maths/sum_of_digits.py) * [Sum Of Geometric Progression](maths/sum_of_geometric_progression.py) * [Sum Of Harmonic Series](maths/sum_of_harmonic_series.py) * [Sumset](maths/sumset.py) * [Sylvester Sequence](maths/sylvester_sequence.py) * [Tanh](maths/tanh.py) * [Test Prime Check](maths/test_prime_check.py) * [Three Sum](maths/three_sum.py) * [Trapezoidal Rule](maths/trapezoidal_rule.py) * [Triplet Sum](maths/triplet_sum.py) * [Twin Prime](maths/twin_prime.py) * [Two Pointer](maths/two_pointer.py) * [Two Sum](maths/two_sum.py) * [Ugly Numbers](maths/ugly_numbers.py) * [Volume](maths/volume.py) * [Weird Number](maths/weird_number.py) * [Zellers Congruence](maths/zellers_congruence.py) ## Matrix * [Binary Search Matrix](matrix/binary_search_matrix.py) * [Count Islands In Matrix](matrix/count_islands_in_matrix.py) * [Count Negative Numbers In Sorted Matrix](matrix/count_negative_numbers_in_sorted_matrix.py) * [Count Paths](matrix/count_paths.py) * [Cramers Rule 2X2](matrix/cramers_rule_2x2.py) * [Inverse Of Matrix](matrix/inverse_of_matrix.py) * [Largest Square Area In Matrix](matrix/largest_square_area_in_matrix.py) * [Matrix Class](matrix/matrix_class.py) * [Matrix Operation](matrix/matrix_operation.py) * [Max Area Of Island](matrix/max_area_of_island.py) * [Nth Fibonacci Using Matrix Exponentiation](matrix/nth_fibonacci_using_matrix_exponentiation.py) * [Pascal Triangle](matrix/pascal_triangle.py) * [Rotate Matrix](matrix/rotate_matrix.py) * [Searching In Sorted Matrix](matrix/searching_in_sorted_matrix.py) * [Sherman Morrison](matrix/sherman_morrison.py) * [Spiral Print](matrix/spiral_print.py) * Tests * [Test Matrix Operation](matrix/tests/test_matrix_operation.py) ## Networking Flow * [Ford Fulkerson](networking_flow/ford_fulkerson.py) * [Minimum Cut](networking_flow/minimum_cut.py) ## Neural Network * [2 Hidden Layers Neural Network](neural_network/2_hidden_layers_neural_network.py) * Activation Functions * [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py) * [Leaky Rectified Linear Unit](neural_network/activation_functions/leaky_rectified_linear_unit.py) * [Scaled Exponential Linear Unit](neural_network/activation_functions/scaled_exponential_linear_unit.py) * [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py) * [Convolution Neural Network](neural_network/convolution_neural_network.py) * [Perceptron](neural_network/perceptron.py) * [Simple Neural Network](neural_network/simple_neural_network.py) ## Other * [Activity Selection](other/activity_selection.py) * [Alternative List Arrange](other/alternative_list_arrange.py) * [Davisb Putnamb Logemannb Loveland](other/davisb_putnamb_logemannb_loveland.py) * [Dijkstra Bankers Algorithm](other/dijkstra_bankers_algorithm.py) * [Doomsday](other/doomsday.py) * [Fischer Yates Shuffle](other/fischer_yates_shuffle.py) * [Gauss Easter](other/gauss_easter.py) * [Graham Scan](other/graham_scan.py) * [Greedy](other/greedy.py) * [Guess The Number Search](other/guess_the_number_search.py) * [H Index](other/h_index.py) * [Least Recently Used](other/least_recently_used.py) * [Lfu Cache](other/lfu_cache.py) * [Linear Congruential Generator](other/linear_congruential_generator.py) * [Lru Cache](other/lru_cache.py) * [Magicdiamondpattern](other/magicdiamondpattern.py) * [Maximum Subsequence](other/maximum_subsequence.py) * [Nested Brackets](other/nested_brackets.py) * [Number Container System](other/number_container_system.py) * [Password](other/password.py) * [Quine](other/quine.py) * [Scoring Algorithm](other/scoring_algorithm.py) * [Sdes](other/sdes.py) * [Tower Of Hanoi](other/tower_of_hanoi.py) * [Word Search](other/word_search.py) ## Physics * [Altitude Pressure](physics/altitude_pressure.py) * [Archimedes Principle](physics/archimedes_principle.py) * [Basic Orbital Capture](physics/basic_orbital_capture.py) * [Casimir Effect](physics/casimir_effect.py) * [Centripetal Force](physics/centripetal_force.py) * [Coulombs Law](physics/coulombs_law.py) * [Grahams Law](physics/grahams_law.py) * [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py) * [Hubble Parameter](physics/hubble_parameter.py) * [Ideal Gas Law](physics/ideal_gas_law.py) * [Kinetic Energy](physics/kinetic_energy.py) * [Lorentz Transformation Four Vector](physics/lorentz_transformation_four_vector.py) * [Malus Law](physics/malus_law.py) * [N Body Simulation](physics/n_body_simulation.py) * [Newtons Law Of Gravitation](physics/newtons_law_of_gravitation.py) * [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py) * [Potential Energy](physics/potential_energy.py) * [Rms Speed Of Molecule](physics/rms_speed_of_molecule.py) * [Shear Stress](physics/shear_stress.py) * [Speed Of Sound](physics/speed_of_sound.py) ## Project Euler * Problem 001 * [Sol1](project_euler/problem_001/sol1.py) * [Sol2](project_euler/problem_001/sol2.py) * [Sol3](project_euler/problem_001/sol3.py) * [Sol4](project_euler/problem_001/sol4.py) * [Sol5](project_euler/problem_001/sol5.py) * [Sol6](project_euler/problem_001/sol6.py) * [Sol7](project_euler/problem_001/sol7.py) * Problem 002 * [Sol1](project_euler/problem_002/sol1.py) * [Sol2](project_euler/problem_002/sol2.py) * [Sol3](project_euler/problem_002/sol3.py) * [Sol4](project_euler/problem_002/sol4.py) * [Sol5](project_euler/problem_002/sol5.py) * Problem 003 * [Sol1](project_euler/problem_003/sol1.py) * [Sol2](project_euler/problem_003/sol2.py) * [Sol3](project_euler/problem_003/sol3.py) * Problem 004 * [Sol1](project_euler/problem_004/sol1.py) * [Sol2](project_euler/problem_004/sol2.py) * Problem 005 * [Sol1](project_euler/problem_005/sol1.py) * [Sol2](project_euler/problem_005/sol2.py) * Problem 006 * [Sol1](project_euler/problem_006/sol1.py) * [Sol2](project_euler/problem_006/sol2.py) * [Sol3](project_euler/problem_006/sol3.py) * [Sol4](project_euler/problem_006/sol4.py) * Problem 007 * [Sol1](project_euler/problem_007/sol1.py) * [Sol2](project_euler/problem_007/sol2.py) * [Sol3](project_euler/problem_007/sol3.py) * Problem 008 * [Sol1](project_euler/problem_008/sol1.py) * [Sol2](project_euler/problem_008/sol2.py) * [Sol3](project_euler/problem_008/sol3.py) * Problem 009 * [Sol1](project_euler/problem_009/sol1.py) * [Sol2](project_euler/problem_009/sol2.py) * [Sol3](project_euler/problem_009/sol3.py) * Problem 010 * [Sol1](project_euler/problem_010/sol1.py) * [Sol2](project_euler/problem_010/sol2.py) * [Sol3](project_euler/problem_010/sol3.py) * Problem 011 * [Sol1](project_euler/problem_011/sol1.py) * [Sol2](project_euler/problem_011/sol2.py) * Problem 012 * [Sol1](project_euler/problem_012/sol1.py) * [Sol2](project_euler/problem_012/sol2.py) * Problem 013 * [Sol1](project_euler/problem_013/sol1.py) * Problem 014 * [Sol1](project_euler/problem_014/sol1.py) * [Sol2](project_euler/problem_014/sol2.py) * Problem 015 * [Sol1](project_euler/problem_015/sol1.py) * Problem 016 * [Sol1](project_euler/problem_016/sol1.py) * [Sol2](project_euler/problem_016/sol2.py) * Problem 017 * [Sol1](project_euler/problem_017/sol1.py) * Problem 018 * [Solution](project_euler/problem_018/solution.py) * Problem 019 * [Sol1](project_euler/problem_019/sol1.py) * Problem 020 * [Sol1](project_euler/problem_020/sol1.py) * [Sol2](project_euler/problem_020/sol2.py) * [Sol3](project_euler/problem_020/sol3.py) * [Sol4](project_euler/problem_020/sol4.py) * Problem 021 * [Sol1](project_euler/problem_021/sol1.py) * Problem 022 * [Sol1](project_euler/problem_022/sol1.py) * [Sol2](project_euler/problem_022/sol2.py) * Problem 023 * [Sol1](project_euler/problem_023/sol1.py) * Problem 024 * [Sol1](project_euler/problem_024/sol1.py) * Problem 025 * [Sol1](project_euler/problem_025/sol1.py) * [Sol2](project_euler/problem_025/sol2.py) * [Sol3](project_euler/problem_025/sol3.py) * Problem 026 * [Sol1](project_euler/problem_026/sol1.py) * Problem 027 * [Sol1](project_euler/problem_027/sol1.py) * Problem 028 * [Sol1](project_euler/problem_028/sol1.py) * Problem 029 * [Sol1](project_euler/problem_029/sol1.py) * Problem 030 * [Sol1](project_euler/problem_030/sol1.py) * Problem 031 * [Sol1](project_euler/problem_031/sol1.py) * [Sol2](project_euler/problem_031/sol2.py) * Problem 032 * [Sol32](project_euler/problem_032/sol32.py) * Problem 033 * [Sol1](project_euler/problem_033/sol1.py) * Problem 034 * [Sol1](project_euler/problem_034/sol1.py) * Problem 035 * [Sol1](project_euler/problem_035/sol1.py) * Problem 036 * [Sol1](project_euler/problem_036/sol1.py) * Problem 037 * [Sol1](project_euler/problem_037/sol1.py) * Problem 038 * [Sol1](project_euler/problem_038/sol1.py) * Problem 039 * [Sol1](project_euler/problem_039/sol1.py) * Problem 040 * [Sol1](project_euler/problem_040/sol1.py) * Problem 041 * [Sol1](project_euler/problem_041/sol1.py) * Problem 042 * [Solution42](project_euler/problem_042/solution42.py) * Problem 043 * [Sol1](project_euler/problem_043/sol1.py) * Problem 044 * [Sol1](project_euler/problem_044/sol1.py) * Problem 045 * [Sol1](project_euler/problem_045/sol1.py) * Problem 046 * [Sol1](project_euler/problem_046/sol1.py) * Problem 047 * [Sol1](project_euler/problem_047/sol1.py) * Problem 048 * [Sol1](project_euler/problem_048/sol1.py) * Problem 049 * [Sol1](project_euler/problem_049/sol1.py) * Problem 050 * [Sol1](project_euler/problem_050/sol1.py) * Problem 051 * [Sol1](project_euler/problem_051/sol1.py) * Problem 052 * [Sol1](project_euler/problem_052/sol1.py) * Problem 053 * [Sol1](project_euler/problem_053/sol1.py) * Problem 054 * [Sol1](project_euler/problem_054/sol1.py) * [Test Poker Hand](project_euler/problem_054/test_poker_hand.py) * Problem 055 * [Sol1](project_euler/problem_055/sol1.py) * Problem 056 * [Sol1](project_euler/problem_056/sol1.py) * Problem 057 * [Sol1](project_euler/problem_057/sol1.py) * Problem 058 * [Sol1](project_euler/problem_058/sol1.py) * Problem 059 * [Sol1](project_euler/problem_059/sol1.py) * Problem 062 * [Sol1](project_euler/problem_062/sol1.py) * Problem 063 * [Sol1](project_euler/problem_063/sol1.py) * Problem 064 * [Sol1](project_euler/problem_064/sol1.py) * Problem 065 * [Sol1](project_euler/problem_065/sol1.py) * Problem 067 * [Sol1](project_euler/problem_067/sol1.py) * [Sol2](project_euler/problem_067/sol2.py) * Problem 068 * [Sol1](project_euler/problem_068/sol1.py) * Problem 069 * [Sol1](project_euler/problem_069/sol1.py) * Problem 070 * [Sol1](project_euler/problem_070/sol1.py) * Problem 071 * [Sol1](project_euler/problem_071/sol1.py) * Problem 072 * [Sol1](project_euler/problem_072/sol1.py) * [Sol2](project_euler/problem_072/sol2.py) * Problem 073 * [Sol1](project_euler/problem_073/sol1.py) * Problem 074 * [Sol1](project_euler/problem_074/sol1.py) * [Sol2](project_euler/problem_074/sol2.py) * Problem 075 * [Sol1](project_euler/problem_075/sol1.py) * Problem 076 * [Sol1](project_euler/problem_076/sol1.py) * Problem 077 * [Sol1](project_euler/problem_077/sol1.py) * Problem 078 * [Sol1](project_euler/problem_078/sol1.py) * Problem 079 * [Sol1](project_euler/problem_079/sol1.py) * Problem 080 * [Sol1](project_euler/problem_080/sol1.py) * Problem 081 * [Sol1](project_euler/problem_081/sol1.py) * Problem 082 * [Sol1](project_euler/problem_082/sol1.py) * Problem 085 * [Sol1](project_euler/problem_085/sol1.py) * Problem 086 * [Sol1](project_euler/problem_086/sol1.py) * Problem 087 * [Sol1](project_euler/problem_087/sol1.py) * Problem 089 * [Sol1](project_euler/problem_089/sol1.py) * Problem 091 * [Sol1](project_euler/problem_091/sol1.py) * Problem 092 * [Sol1](project_euler/problem_092/sol1.py) * Problem 094 * [Sol1](project_euler/problem_094/sol1.py) * Problem 097 * [Sol1](project_euler/problem_097/sol1.py) * Problem 099 * [Sol1](project_euler/problem_099/sol1.py) * Problem 100 * [Sol1](project_euler/problem_100/sol1.py) * Problem 101 * [Sol1](project_euler/problem_101/sol1.py) * Problem 102 * [Sol1](project_euler/problem_102/sol1.py) * Problem 104 * [Sol1](project_euler/problem_104/sol1.py) * Problem 107 * [Sol1](project_euler/problem_107/sol1.py) * Problem 109 * [Sol1](project_euler/problem_109/sol1.py) * Problem 112 * [Sol1](project_euler/problem_112/sol1.py) * Problem 113 * [Sol1](project_euler/problem_113/sol1.py) * Problem 114 * [Sol1](project_euler/problem_114/sol1.py) * Problem 115 * [Sol1](project_euler/problem_115/sol1.py) * Problem 116 * [Sol1](project_euler/problem_116/sol1.py) * Problem 117 * [Sol1](project_euler/problem_117/sol1.py) * Problem 119 * [Sol1](project_euler/problem_119/sol1.py) * Problem 120 * [Sol1](project_euler/problem_120/sol1.py) * Problem 121 * [Sol1](project_euler/problem_121/sol1.py) * Problem 123 * [Sol1](project_euler/problem_123/sol1.py) * Problem 125 * [Sol1](project_euler/problem_125/sol1.py) * Problem 129 * [Sol1](project_euler/problem_129/sol1.py) * Problem 131 * [Sol1](project_euler/problem_131/sol1.py) * Problem 135 * [Sol1](project_euler/problem_135/sol1.py) * Problem 144 * [Sol1](project_euler/problem_144/sol1.py) * Problem 145 * [Sol1](project_euler/problem_145/sol1.py) * Problem 173 * [Sol1](project_euler/problem_173/sol1.py) * Problem 174 * [Sol1](project_euler/problem_174/sol1.py) * Problem 180 * [Sol1](project_euler/problem_180/sol1.py) * Problem 187 * [Sol1](project_euler/problem_187/sol1.py) * Problem 188 * [Sol1](project_euler/problem_188/sol1.py) * Problem 191 * [Sol1](project_euler/problem_191/sol1.py) * Problem 203 * [Sol1](project_euler/problem_203/sol1.py) * Problem 205 * [Sol1](project_euler/problem_205/sol1.py) * Problem 206 * [Sol1](project_euler/problem_206/sol1.py) * Problem 207 * [Sol1](project_euler/problem_207/sol1.py) * Problem 234 * [Sol1](project_euler/problem_234/sol1.py) * Problem 301 * [Sol1](project_euler/problem_301/sol1.py) * Problem 493 * [Sol1](project_euler/problem_493/sol1.py) * Problem 551 * [Sol1](project_euler/problem_551/sol1.py) * Problem 587 * [Sol1](project_euler/problem_587/sol1.py) * Problem 686 * [Sol1](project_euler/problem_686/sol1.py) * Problem 800 * [Sol1](project_euler/problem_800/sol1.py) ## Quantum * [Q Fourier Transform](quantum/q_fourier_transform.py) ## Scheduling * [First Come First Served](scheduling/first_come_first_served.py) * [Highest Response Ratio Next](scheduling/highest_response_ratio_next.py) * [Job Sequencing With Deadline](scheduling/job_sequencing_with_deadline.py) * [Multi Level Feedback Queue](scheduling/multi_level_feedback_queue.py) * [Non Preemptive Shortest Job First](scheduling/non_preemptive_shortest_job_first.py) * [Round Robin](scheduling/round_robin.py) * [Shortest Job First](scheduling/shortest_job_first.py) ## Searches * [Binary Search](searches/binary_search.py) * [Binary Tree Traversal](searches/binary_tree_traversal.py) * [Double Linear Search](searches/double_linear_search.py) * [Double Linear Search Recursion](searches/double_linear_search_recursion.py) * [Fibonacci Search](searches/fibonacci_search.py) * [Hill Climbing](searches/hill_climbing.py) * [Interpolation Search](searches/interpolation_search.py) * [Jump Search](searches/jump_search.py) * [Linear Search](searches/linear_search.py) * [Quick Select](searches/quick_select.py) * [Sentinel Linear Search](searches/sentinel_linear_search.py) * [Simple Binary Search](searches/simple_binary_search.py) * [Simulated Annealing](searches/simulated_annealing.py) * [Tabu Search](searches/tabu_search.py) * [Ternary Search](searches/ternary_search.py) ## Sorts * [Bead Sort](sorts/bead_sort.py) * [Binary Insertion Sort](sorts/binary_insertion_sort.py) * [Bitonic Sort](sorts/bitonic_sort.py) * [Bogo Sort](sorts/bogo_sort.py) * [Bubble Sort](sorts/bubble_sort.py) * [Bucket Sort](sorts/bucket_sort.py) * [Circle Sort](sorts/circle_sort.py) * [Cocktail Shaker Sort](sorts/cocktail_shaker_sort.py) * [Comb Sort](sorts/comb_sort.py) * [Counting Sort](sorts/counting_sort.py) * [Cycle Sort](sorts/cycle_sort.py) * [Double Sort](sorts/double_sort.py) * [Dutch National Flag Sort](sorts/dutch_national_flag_sort.py) * [Exchange Sort](sorts/exchange_sort.py) * [External Sort](sorts/external_sort.py) * [Gnome Sort](sorts/gnome_sort.py) * [Heap Sort](sorts/heap_sort.py) * [Insertion Sort](sorts/insertion_sort.py) * [Intro Sort](sorts/intro_sort.py) * [Iterative Merge Sort](sorts/iterative_merge_sort.py) * [Merge Insertion Sort](sorts/merge_insertion_sort.py) * [Merge Sort](sorts/merge_sort.py) * [Msd Radix Sort](sorts/msd_radix_sort.py) * [Natural Sort](sorts/natural_sort.py) * [Odd Even Sort](sorts/odd_even_sort.py) * [Odd Even Transposition Parallel](sorts/odd_even_transposition_parallel.py) * [Odd Even Transposition Single Threaded](sorts/odd_even_transposition_single_threaded.py) * [Pancake Sort](sorts/pancake_sort.py) * [Patience Sort](sorts/patience_sort.py) * [Pigeon Sort](sorts/pigeon_sort.py) * [Pigeonhole Sort](sorts/pigeonhole_sort.py) * [Quick Sort](sorts/quick_sort.py) * [Quick Sort 3 Partition](sorts/quick_sort_3_partition.py) * [Radix Sort](sorts/radix_sort.py) * [Recursive Bubble Sort](sorts/recursive_bubble_sort.py) * [Recursive Insertion Sort](sorts/recursive_insertion_sort.py) * [Recursive Mergesort Array](sorts/recursive_mergesort_array.py) * [Recursive Quick Sort](sorts/recursive_quick_sort.py) * [Selection Sort](sorts/selection_sort.py) * [Shell Sort](sorts/shell_sort.py) * [Shrink Shell Sort](sorts/shrink_shell_sort.py) * [Slowsort](sorts/slowsort.py) * [Stooge Sort](sorts/stooge_sort.py) * [Strand Sort](sorts/strand_sort.py) * [Tim Sort](sorts/tim_sort.py) * [Topological Sort](sorts/topological_sort.py) * [Tree Sort](sorts/tree_sort.py) * [Unknown Sort](sorts/unknown_sort.py) * [Wiggle Sort](sorts/wiggle_sort.py) ## Strings * [Aho Corasick](strings/aho_corasick.py) * [Alternative String Arrange](strings/alternative_string_arrange.py) * [Anagrams](strings/anagrams.py) * [Autocomplete Using Trie](strings/autocomplete_using_trie.py) * [Barcode Validator](strings/barcode_validator.py) * [Boyer Moore Search](strings/boyer_moore_search.py) * [Can String Be Rearranged As Palindrome](strings/can_string_be_rearranged_as_palindrome.py) * [Capitalize](strings/capitalize.py) * [Check Anagrams](strings/check_anagrams.py) * [Credit Card Validator](strings/credit_card_validator.py) * [Detecting English Programmatically](strings/detecting_english_programmatically.py) * [Dna](strings/dna.py) * [Frequency Finder](strings/frequency_finder.py) * [Hamming Distance](strings/hamming_distance.py) * [Indian Phone Validator](strings/indian_phone_validator.py) * [Is Contains Unique Chars](strings/is_contains_unique_chars.py) * [Is Isogram](strings/is_isogram.py) * [Is Pangram](strings/is_pangram.py) * [Is Spain National Id](strings/is_spain_national_id.py) * [Is Srilankan Phone Number](strings/is_srilankan_phone_number.py) * [Is Valid Email Address](strings/is_valid_email_address.py) * [Jaro Winkler](strings/jaro_winkler.py) * [Join](strings/join.py) * [Knuth Morris Pratt](strings/knuth_morris_pratt.py) * [Levenshtein Distance](strings/levenshtein_distance.py) * [Lower](strings/lower.py) * [Manacher](strings/manacher.py) * [Min Cost String Conversion](strings/min_cost_string_conversion.py) * [Naive String Search](strings/naive_string_search.py) * [Ngram](strings/ngram.py) * [Palindrome](strings/palindrome.py) * [Prefix Function](strings/prefix_function.py) * [Rabin Karp](strings/rabin_karp.py) * [Remove Duplicate](strings/remove_duplicate.py) * [Reverse Letters](strings/reverse_letters.py) * [Reverse Long Words](strings/reverse_long_words.py) * [Reverse Words](strings/reverse_words.py) * [Snake Case To Camel Pascal Case](strings/snake_case_to_camel_pascal_case.py) * [Split](strings/split.py) * [String Switch Case](strings/string_switch_case.py) * [Text Justification](strings/text_justification.py) * [Top K Frequent Words](strings/top_k_frequent_words.py) * [Upper](strings/upper.py) * [Wave](strings/wave.py) * [Wildcard Pattern Matching](strings/wildcard_pattern_matching.py) * [Word Occurrence](strings/word_occurrence.py) * [Word Patterns](strings/word_patterns.py) * [Z Function](strings/z_function.py) ## Web Programming * [Co2 Emission](web_programming/co2_emission.py) * [Covid Stats Via Xpath](web_programming/covid_stats_via_xpath.py) * [Crawl Google Results](web_programming/crawl_google_results.py) * [Crawl Google Scholar Citation](web_programming/crawl_google_scholar_citation.py) * [Currency Converter](web_programming/currency_converter.py) * [Current Stock Price](web_programming/current_stock_price.py) * [Current Weather](web_programming/current_weather.py) * [Daily Horoscope](web_programming/daily_horoscope.py) * [Download Images From Google Query](web_programming/download_images_from_google_query.py) * [Emails From Url](web_programming/emails_from_url.py) * [Fetch Anime And Play](web_programming/fetch_anime_and_play.py) * [Fetch Bbc News](web_programming/fetch_bbc_news.py) * [Fetch Github Info](web_programming/fetch_github_info.py) * [Fetch Jobs](web_programming/fetch_jobs.py) * [Fetch Quotes](web_programming/fetch_quotes.py) * [Fetch Well Rx Price](web_programming/fetch_well_rx_price.py) * [Get Amazon Product Data](web_programming/get_amazon_product_data.py) * [Get Imdb Top 250 Movies Csv](web_programming/get_imdb_top_250_movies_csv.py) * [Get Imdbtop](web_programming/get_imdbtop.py) * [Get Top Billionaires](web_programming/get_top_billionaires.py) * [Get Top Hn Posts](web_programming/get_top_hn_posts.py) * [Get User Tweets](web_programming/get_user_tweets.py) * [Giphy](web_programming/giphy.py) * [Instagram Crawler](web_programming/instagram_crawler.py) * [Instagram Pic](web_programming/instagram_pic.py) * [Instagram Video](web_programming/instagram_video.py) * [Nasa Data](web_programming/nasa_data.py) * [Open Google Results](web_programming/open_google_results.py) * [Random Anime Character](web_programming/random_anime_character.py) * [Recaptcha Verification](web_programming/recaptcha_verification.py) * [Reddit](web_programming/reddit.py) * [Search Books By Isbn](web_programming/search_books_by_isbn.py) * [Slack Message](web_programming/slack_message.py) * [Test Fetch Github Info](web_programming/test_fetch_github_info.py) * [World Covid19 Stats](web_programming/world_covid19_stats.py)
1
TheAlgorithms/Python
9,707
Fix mypy errors in circular_linked_list.py and swap_nodes.py
### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-10-04T14:51:39Z"
"2023-10-04T16:05:01Z"
3fd3497f15982a7286326b520b5e7b52767da1f3
dfdd78135df938d948ba3044aca628aca08886e7
Fix mypy errors in circular_linked_list.py and swap_nodes.py. ### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from __future__ import annotations from collections.abc import Iterator from typing import Any class Node: def __init__(self, data: Any): """ Initialize a new Node with the given data. Args: data: The data to be stored in the node. """ self.data: Any = data self.next: Node | None = None # Reference to the next node class CircularLinkedList: def __init__(self) -> None: """ Initialize an empty Circular Linked List. """ self.head = None # Reference to the head (first node) self.tail = None # Reference to the tail (last node) def __iter__(self) -> Iterator[Any]: """ Iterate through all nodes in the Circular Linked List yielding their data. Yields: The data of each node in the linked list. """ node = self.head while self.head: yield node.data node = node.next if node == self.head: break def __len__(self) -> int: """ Get the length (number of nodes) in the Circular Linked List. """ return sum(1 for _ in self) def __repr__(self) -> str: """ Generate a string representation of the Circular Linked List. Returns: A string of the format "1->2->....->N". """ return "->".join(str(item) for item in iter(self)) def insert_tail(self, data: Any) -> None: """ Insert a node with the given data at the end of the Circular Linked List. """ self.insert_nth(len(self), data) def insert_head(self, data: Any) -> None: """ Insert a node with the given data at the beginning of the Circular Linked List. """ self.insert_nth(0, data) def insert_nth(self, index: int, data: Any) -> None: """ Insert the data of the node at the nth pos in the Circular Linked List. Args: index: The index at which the data should be inserted. data: The data to be inserted. Raises: IndexError: If the index is out of range. """ if index < 0 or index > len(self): raise IndexError("list index out of range.") new_node = Node(data) if self.head is None: new_node.next = new_node # First node points to itself self.tail = self.head = new_node elif index == 0: # Insert at the head new_node.next = self.head self.head = self.tail.next = new_node else: temp = self.head for _ in range(index - 1): temp = temp.next new_node.next = temp.next temp.next = new_node if index == len(self) - 1: # Insert at the tail self.tail = new_node def delete_front(self) -> Any: """ Delete and return the data of the node at the front of the Circular Linked List. Raises: IndexError: If the list is empty. """ return self.delete_nth(0) def delete_tail(self) -> Any: """ Delete and return the data of the node at the end of the Circular Linked List. Returns: Any: The data of the deleted node. Raises: IndexError: If the index is out of range. """ return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0) -> Any: """ Delete and return the data of the node at the nth pos in Circular Linked List. Args: index (int): The index of the node to be deleted. Defaults to 0. Returns: Any: The data of the deleted node. Raises: IndexError: If the index is out of range. """ if not 0 <= index < len(self): raise IndexError("list index out of range.") delete_node = self.head if self.head == self.tail: # Just one node self.head = self.tail = None elif index == 0: # Delete head node self.tail.next = self.tail.next.next self.head = self.head.next else: temp = self.head for _ in range(index - 1): temp = temp.next delete_node = temp.next temp.next = temp.next.next if index == len(self) - 1: # Delete at tail self.tail = temp return delete_node.data def is_empty(self) -> bool: """ Check if the Circular Linked List is empty. Returns: bool: True if the list is empty, False otherwise. """ return len(self) == 0 def test_circular_linked_list() -> None: """ Test cases for the CircularLinkedList class. >>> test_circular_linked_list() """ circular_linked_list = CircularLinkedList() assert len(circular_linked_list) == 0 assert circular_linked_list.is_empty() is True assert str(circular_linked_list) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5): assert len(circular_linked_list) == i circular_linked_list.insert_nth(i, i + 1) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) circular_linked_list.insert_tail(6) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 7)) circular_linked_list.insert_head(0) assert str(circular_linked_list) == "->".join(str(i) for i in range(7)) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) assert circular_linked_list.delete_nth(2) == 3 circular_linked_list.insert_nth(2, 3) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations from collections.abc import Iterator from typing import Any class Node: def __init__(self, data: Any): """ Initialize a new Node with the given data. Args: data: The data to be stored in the node. """ self.data: Any = data self.next: Node | None = None # Reference to the next node class CircularLinkedList: def __init__(self) -> None: """ Initialize an empty Circular Linked List. """ self.head: Node | None = None # Reference to the head (first node) self.tail: Node | None = None # Reference to the tail (last node) def __iter__(self) -> Iterator[Any]: """ Iterate through all nodes in the Circular Linked List yielding their data. Yields: The data of each node in the linked list. """ node = self.head while node: yield node.data node = node.next if node == self.head: break def __len__(self) -> int: """ Get the length (number of nodes) in the Circular Linked List. """ return sum(1 for _ in self) def __repr__(self) -> str: """ Generate a string representation of the Circular Linked List. Returns: A string of the format "1->2->....->N". """ return "->".join(str(item) for item in iter(self)) def insert_tail(self, data: Any) -> None: """ Insert a node with the given data at the end of the Circular Linked List. """ self.insert_nth(len(self), data) def insert_head(self, data: Any) -> None: """ Insert a node with the given data at the beginning of the Circular Linked List. """ self.insert_nth(0, data) def insert_nth(self, index: int, data: Any) -> None: """ Insert the data of the node at the nth pos in the Circular Linked List. Args: index: The index at which the data should be inserted. data: The data to be inserted. Raises: IndexError: If the index is out of range. """ if index < 0 or index > len(self): raise IndexError("list index out of range.") new_node: Node = Node(data) if self.head is None: new_node.next = new_node # First node points to itself self.tail = self.head = new_node elif index == 0: # Insert at the head new_node.next = self.head assert self.tail is not None # List is not empty, tail exists self.head = self.tail.next = new_node else: temp: Node | None = self.head for _ in range(index - 1): assert temp is not None temp = temp.next assert temp is not None new_node.next = temp.next temp.next = new_node if index == len(self) - 1: # Insert at the tail self.tail = new_node def delete_front(self) -> Any: """ Delete and return the data of the node at the front of the Circular Linked List. Raises: IndexError: If the list is empty. """ return self.delete_nth(0) def delete_tail(self) -> Any: """ Delete and return the data of the node at the end of the Circular Linked List. Returns: Any: The data of the deleted node. Raises: IndexError: If the index is out of range. """ return self.delete_nth(len(self) - 1) def delete_nth(self, index: int = 0) -> Any: """ Delete and return the data of the node at the nth pos in Circular Linked List. Args: index (int): The index of the node to be deleted. Defaults to 0. Returns: Any: The data of the deleted node. Raises: IndexError: If the index is out of range. """ if not 0 <= index < len(self): raise IndexError("list index out of range.") assert self.head is not None and self.tail is not None delete_node: Node = self.head if self.head == self.tail: # Just one node self.head = self.tail = None elif index == 0: # Delete head node assert self.tail.next is not None self.tail.next = self.tail.next.next self.head = self.head.next else: temp: Node | None = self.head for _ in range(index - 1): assert temp is not None temp = temp.next assert temp is not None and temp.next is not None delete_node = temp.next temp.next = temp.next.next if index == len(self) - 1: # Delete at tail self.tail = temp return delete_node.data def is_empty(self) -> bool: """ Check if the Circular Linked List is empty. Returns: bool: True if the list is empty, False otherwise. """ return len(self) == 0 def test_circular_linked_list() -> None: """ Test cases for the CircularLinkedList class. >>> test_circular_linked_list() """ circular_linked_list = CircularLinkedList() assert len(circular_linked_list) == 0 assert circular_linked_list.is_empty() is True assert str(circular_linked_list) == "" try: circular_linked_list.delete_front() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_tail() raise AssertionError # This should not happen except IndexError: assert True # This should happen try: circular_linked_list.delete_nth(-1) raise AssertionError except IndexError: assert True try: circular_linked_list.delete_nth(0) raise AssertionError except IndexError: assert True assert circular_linked_list.is_empty() is True for i in range(5): assert len(circular_linked_list) == i circular_linked_list.insert_nth(i, i + 1) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) circular_linked_list.insert_tail(6) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 7)) circular_linked_list.insert_head(0) assert str(circular_linked_list) == "->".join(str(i) for i in range(7)) assert circular_linked_list.delete_front() == 0 assert circular_linked_list.delete_tail() == 6 assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) assert circular_linked_list.delete_nth(2) == 3 circular_linked_list.insert_nth(2, 3) assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) assert circular_linked_list.is_empty() is False if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
9,707
Fix mypy errors in circular_linked_list.py and swap_nodes.py
### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-10-04T14:51:39Z"
"2023-10-04T16:05:01Z"
3fd3497f15982a7286326b520b5e7b52767da1f3
dfdd78135df938d948ba3044aca628aca08886e7
Fix mypy errors in circular_linked_list.py and swap_nodes.py. ### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from typing import Any class Node: def __init__(self, data: Any) -> None: """ Initialize a new Node with the given data. Args: data: The data to be stored in the node. """ self.data = data self.next = None # Reference to the next node class LinkedList: def __init__(self) -> None: """ Initialize an empty Linked List. """ self.head = None # Reference to the head (first node) def print_list(self): """ Print the elements of the Linked List in order. """ temp = self.head while temp is not None: print(temp.data, end=" ") temp = temp.next print() def push(self, new_data: Any) -> None: """ Add a new node with the given data to the beginning of the Linked List. Args: new_data (Any): The data to be added to the new node. """ new_node = Node(new_data) new_node.next = self.head self.head = new_node def swap_nodes(self, node_data_1, node_data_2) -> None: """ Swap the positions of two nodes in the Linked List based on their data values. Args: node_data_1: Data value of the first node to be swapped. node_data_2: Data value of the second node to be swapped. Note: If either of the specified data values isn't found then, no swapping occurs. """ 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 # Swap the data values of the two nodes 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) print("Original Linked List:") ll.print_list() ll.swap_nodes(1, 4) print("After swapping the nodes whose data is 1 and 4:") ll.print_list()
from typing import Any class Node: def __init__(self, data: Any) -> None: """ Initialize a new Node with the given data. Args: data: The data to be stored in the node. """ self.data = data self.next: Node | None = None # Reference to the next node class LinkedList: def __init__(self) -> None: """ Initialize an empty Linked List. """ self.head: Node | None = None # Reference to the head (first node) def print_list(self): """ Print the elements of the Linked List in order. """ temp = self.head while temp is not None: print(temp.data, end=" ") temp = temp.next print() def push(self, new_data: Any) -> None: """ Add a new node with the given data to the beginning of the Linked List. Args: new_data (Any): The data to be added to the new node. """ new_node = Node(new_data) new_node.next = self.head self.head = new_node def swap_nodes(self, node_data_1, node_data_2) -> None: """ Swap the positions of two nodes in the Linked List based on their data values. Args: node_data_1: Data value of the first node to be swapped. node_data_2: Data value of the second node to be swapped. Note: If either of the specified data values isn't found then, no swapping occurs. """ 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 # Swap the data values of the two nodes 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) print("Original Linked List:") ll.print_list() ll.swap_nodes(1, 4) print("After swapping the nodes whose data is 1 and 4:") ll.print_list()
1
TheAlgorithms/Python
9,707
Fix mypy errors in circular_linked_list.py and swap_nodes.py
### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-10-04T14:51:39Z"
"2023-10-04T16:05:01Z"
3fd3497f15982a7286326b520b5e7b52767da1f3
dfdd78135df938d948ba3044aca628aca08886e7
Fix mypy errors in circular_linked_list.py and swap_nodes.py. ### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from __future__ import annotations def solve_maze(maze: list[list[int]]) -> bool: """ This method solves the "rat in maze" problem. In this problem we have some n by n matrix, a start point and an end point. We want to go from the start to the end. In this matrix zeroes represent walls and ones paths we can use. Parameters : maze(2D matrix) : maze Returns: Return: True if the maze has a solution or False if it does not. >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [1, 0, 1, 0, 1], ... [0, 0, 1, 0, 0], ... [1, 0, 0, 1, 0]] >>> solve_maze(maze) [1, 0, 0, 0, 0] [1, 1, 1, 1, 0] [0, 0, 0, 1, 0] [0, 0, 0, 1, 1] [0, 0, 0, 0, 1] True >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0]] >>> solve_maze(maze) [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 1, 1, 1, 1] True >>> maze = [[0, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze) [1, 1, 1] [0, 0, 1] [0, 0, 1] True >>> maze = [[0, 1, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze) No solution exists! False >>> maze = [[0, 1], ... [1, 0]] >>> solve_maze(maze) No solution exists! False """ size = len(maze) # We need to create solution object to save path. solutions = [[0 for _ in range(size)] for _ in range(size)] solved = run_maze(maze, 0, 0, solutions) if solved: print("\n".join(str(row) for row in solutions)) else: print("No solution exists!") return solved def run_maze(maze: list[list[int]], i: int, j: int, solutions: list[list[int]]) -> bool: """ This method is recursive starting from (i, j) and going in one of four directions: up, down, left, right. If a path is found to destination it returns True otherwise it returns False. Parameters: maze(2D matrix) : maze i, j : coordinates of matrix solutions(2D matrix) : solutions Returns: Boolean if path is found True, Otherwise False. """ size = len(maze) # Final check point. if i == j == (size - 1): solutions[i][j] = 1 return True lower_flag = (not i < 0) and (not j < 0) # Check lower bounds upper_flag = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. block_flag = (not solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited solutions[i][j] = 1 # check for directions if ( run_maze(maze, i + 1, j, solutions) or run_maze(maze, i, j + 1, solutions) or run_maze(maze, i - 1, j, solutions) or run_maze(maze, i, j - 1, solutions) ): return True solutions[i][j] = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations def solve_maze(maze: list[list[int]]) -> bool: """ This method solves the "rat in maze" problem. In this problem we have some n by n matrix, a start point and an end point. We want to go from the start to the end. In this matrix zeroes represent walls and ones paths we can use. Parameters : maze(2D matrix) : maze Returns: Return: True if the maze has a solution or False if it does not. >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [1, 0, 1, 0, 1], ... [0, 0, 1, 0, 0], ... [1, 0, 0, 1, 0]] >>> solve_maze(maze) [1, 0, 0, 0, 0] [1, 1, 1, 1, 0] [0, 0, 0, 1, 0] [0, 0, 0, 1, 1] [0, 0, 0, 0, 1] True >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0]] >>> solve_maze(maze) [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 1, 1, 1, 1] True >>> maze = [[0, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze) [1, 1, 1] [0, 0, 1] [0, 0, 1] True >>> maze = [[0, 1, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze) No solution exists! False >>> maze = [[0, 1], ... [1, 0]] >>> solve_maze(maze) No solution exists! False """ size = len(maze) # We need to create solution object to save path. solutions = [[0 for _ in range(size)] for _ in range(size)] solved = run_maze(maze, 0, 0, solutions) if solved: print("\n".join(str(row) for row in solutions)) else: print("No solution exists!") return solved def run_maze(maze: list[list[int]], i: int, j: int, solutions: list[list[int]]) -> bool: """ This method is recursive starting from (i, j) and going in one of four directions: up, down, left, right. If a path is found to destination it returns True otherwise it returns False. Parameters: maze(2D matrix) : maze i, j : coordinates of matrix solutions(2D matrix) : solutions Returns: Boolean if path is found True, Otherwise False. """ size = len(maze) # Final check point. if i == j == (size - 1): solutions[i][j] = 1 return True lower_flag = (not i < 0) and (not j < 0) # Check lower bounds upper_flag = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. block_flag = (not solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited solutions[i][j] = 1 # check for directions if ( run_maze(maze, i + 1, j, solutions) or run_maze(maze, i, j + 1, solutions) or run_maze(maze, i - 1, j, solutions) or run_maze(maze, i, j - 1, solutions) ): return True solutions[i][j] = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
9,707
Fix mypy errors in circular_linked_list.py and swap_nodes.py
### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-10-04T14:51:39Z"
"2023-10-04T16:05:01Z"
3fd3497f15982a7286326b520b5e7b52767da1f3
dfdd78135df938d948ba3044aca628aca08886e7
Fix mypy errors in circular_linked_list.py and swap_nodes.py. ### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" CAUTION: You may get a json.decoding error. This works for some of us but fails for others. """ from datetime import UTC, datetime, timedelta import requests from rich import box from rich import console as rich_console from rich import table as rich_table LIMIT = 10 TODAY = datetime.now() API_URL = ( "https://www.forbes.com/forbesapi/person/rtb/0/position/true.json" "?fields=personName,gender,source,countryOfCitizenship,birthDate,finalWorth" f"&limit={LIMIT}" ) def calculate_age(unix_date: float) -> str: """Calculates age from given unix time format. Returns: Age as string >>> from datetime import datetime, UTC >>> years_since_create = datetime.now(tz=UTC).year - 2022 >>> int(calculate_age(-657244800000)) - years_since_create 73 >>> int(calculate_age(46915200000)) - years_since_create 51 """ # Convert date from milliseconds to seconds unix_date /= 1000 if unix_date < 0: # Handle timestamp before epoch epoch = datetime.fromtimestamp(0, tz=UTC) seconds_since_epoch = (datetime.now(tz=UTC) - epoch).seconds birthdate = ( epoch - timedelta(seconds=abs(unix_date) - seconds_since_epoch) ).date() else: birthdate = datetime.fromtimestamp(unix_date, tz=UTC).date() return str( TODAY.year - birthdate.year - ((TODAY.month, TODAY.day) < (birthdate.month, birthdate.day)) ) def get_forbes_real_time_billionaires() -> list[dict[str, str]]: """Get top 10 realtime billionaires using forbes API. Returns: List of top 10 realtime billionaires data. """ response_json = requests.get(API_URL).json() return [ { "Name": person["personName"], "Source": person["source"], "Country": person["countryOfCitizenship"], "Gender": person["gender"], "Worth ($)": f"{person['finalWorth'] / 1000:.1f} Billion", "Age": calculate_age(person["birthDate"]), } for person in response_json["personList"]["personsLists"] ] def display_billionaires(forbes_billionaires: list[dict[str, str]]) -> None: """Display Forbes real time billionaires in a rich table. Args: forbes_billionaires (list): Forbes top 10 real time billionaires """ table = rich_table.Table( title=f"Forbes Top {LIMIT} Real Time Billionaires at {TODAY:%Y-%m-%d %H:%M}", style="green", highlight=True, box=box.SQUARE, ) for key in forbes_billionaires[0]: table.add_column(key) for billionaire in forbes_billionaires: table.add_row(*billionaire.values()) rich_console.Console().print(table) if __name__ == "__main__": display_billionaires(get_forbes_real_time_billionaires())
""" CAUTION: You may get a json.decoding error. This works for some of us but fails for others. """ from datetime import UTC, datetime, timedelta import requests from rich import box from rich import console as rich_console from rich import table as rich_table LIMIT = 10 TODAY = datetime.now() API_URL = ( "https://www.forbes.com/forbesapi/person/rtb/0/position/true.json" "?fields=personName,gender,source,countryOfCitizenship,birthDate,finalWorth" f"&limit={LIMIT}" ) def calculate_age(unix_date: float) -> str: """Calculates age from given unix time format. Returns: Age as string >>> from datetime import datetime, UTC >>> years_since_create = datetime.now(tz=UTC).year - 2022 >>> int(calculate_age(-657244800000)) - years_since_create 73 >>> int(calculate_age(46915200000)) - years_since_create 51 """ # Convert date from milliseconds to seconds unix_date /= 1000 if unix_date < 0: # Handle timestamp before epoch epoch = datetime.fromtimestamp(0, tz=UTC) seconds_since_epoch = (datetime.now(tz=UTC) - epoch).seconds birthdate = ( epoch - timedelta(seconds=abs(unix_date) - seconds_since_epoch) ).date() else: birthdate = datetime.fromtimestamp(unix_date, tz=UTC).date() return str( TODAY.year - birthdate.year - ((TODAY.month, TODAY.day) < (birthdate.month, birthdate.day)) ) def get_forbes_real_time_billionaires() -> list[dict[str, str]]: """Get top 10 realtime billionaires using forbes API. Returns: List of top 10 realtime billionaires data. """ response_json = requests.get(API_URL).json() return [ { "Name": person["personName"], "Source": person["source"], "Country": person["countryOfCitizenship"], "Gender": person["gender"], "Worth ($)": f"{person['finalWorth'] / 1000:.1f} Billion", "Age": calculate_age(person["birthDate"]), } for person in response_json["personList"]["personsLists"] ] def display_billionaires(forbes_billionaires: list[dict[str, str]]) -> None: """Display Forbes real time billionaires in a rich table. Args: forbes_billionaires (list): Forbes top 10 real time billionaires """ table = rich_table.Table( title=f"Forbes Top {LIMIT} Real Time Billionaires at {TODAY:%Y-%m-%d %H:%M}", style="green", highlight=True, box=box.SQUARE, ) for key in forbes_billionaires[0]: table.add_column(key) for billionaire in forbes_billionaires: table.add_row(*billionaire.values()) rich_console.Console().print(table) if __name__ == "__main__": display_billionaires(get_forbes_real_time_billionaires())
-1
TheAlgorithms/Python
9,707
Fix mypy errors in circular_linked_list.py and swap_nodes.py
### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-10-04T14:51:39Z"
"2023-10-04T16:05:01Z"
3fd3497f15982a7286326b520b5e7b52767da1f3
dfdd78135df938d948ba3044aca628aca08886e7
Fix mypy errors in circular_linked_list.py and swap_nodes.py. ### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
import requests from bs4 import BeautifulSoup, NavigableString, Tag from fake_useragent import UserAgent BASE_URL = "https://ww1.gogoanime2.org" def search_scraper(anime_name: str) -> list: """[summary] Take an url and return list of anime after scraping the site. >>> type(search_scraper("demon_slayer")) <class 'list'> Args: anime_name (str): [Name of anime] Raises: e: [Raises exception on failure] Returns: [list]: [List of animes] """ # concat the name to form the search url. search_url = f"{BASE_URL}/search/{anime_name}" response = requests.get( search_url, headers={"UserAgent": UserAgent().chrome} ) # request the url. # Is the response ok? response.raise_for_status() # parse with soup. soup = BeautifulSoup(response.text, "html.parser") # get list of anime anime_ul = soup.find("ul", {"class": "items"}) if anime_ul is None or isinstance(anime_ul, NavigableString): msg = f"Could not find and anime with name {anime_name}" raise ValueError(msg) anime_li = anime_ul.children # for each anime, insert to list. the name and url. anime_list = [] for anime in anime_li: if isinstance(anime, Tag): anime_url = anime.find("a") if anime_url is None or isinstance(anime_url, NavigableString): continue anime_title = anime.find("a") if anime_title is None or isinstance(anime_title, NavigableString): continue anime_list.append({"title": anime_title["title"], "url": anime_url["href"]}) return anime_list def search_anime_episode_list(episode_endpoint: str) -> list: """[summary] Take an url and return list of episodes after scraping the site for an url. >>> type(search_anime_episode_list("/anime/kimetsu-no-yaiba")) <class 'list'> Args: episode_endpoint (str): [Endpoint of episode] Raises: e: [description] Returns: [list]: [List of episodes] """ request_url = f"{BASE_URL}{episode_endpoint}" response = requests.get(url=request_url, headers={"UserAgent": UserAgent().chrome}) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") # With this id. get the episode list. episode_page_ul = soup.find("ul", {"id": "episode_related"}) if episode_page_ul is None or isinstance(episode_page_ul, NavigableString): msg = f"Could not find any anime eposiodes with name {anime_name}" raise ValueError(msg) episode_page_li = episode_page_ul.children episode_list = [] for episode in episode_page_li: if isinstance(episode, Tag): url = episode.find("a") if url is None or isinstance(url, NavigableString): continue title = episode.find("div", {"class": "name"}) if title is None or isinstance(title, NavigableString): continue episode_list.append( {"title": title.text.replace(" ", ""), "url": url["href"]} ) return episode_list def get_anime_episode(episode_endpoint: str) -> list: """[summary] Get click url and download url from episode url >>> type(get_anime_episode("/watch/kimetsu-no-yaiba/1")) <class 'list'> Args: episode_endpoint (str): [Endpoint of episode] Raises: e: [description] Returns: [list]: [List of download and watch url] """ episode_page_url = f"{BASE_URL}{episode_endpoint}" response = requests.get( url=episode_page_url, headers={"User-Agent": UserAgent().chrome} ) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") url = soup.find("iframe", {"id": "playerframe"}) if url is None or isinstance(url, NavigableString): msg = f"Could not find url and download url from {episode_endpoint}" raise RuntimeError(msg) episode_url = url["src"] if not isinstance(episode_url, str): msg = f"Could not find url and download url from {episode_endpoint}" raise RuntimeError(msg) download_url = episode_url.replace("/embed/", "/playlist/") + ".m3u8" return [f"{BASE_URL}{episode_url}", f"{BASE_URL}{download_url}"] if __name__ == "__main__": anime_name = input("Enter anime name: ").strip() anime_list = search_scraper(anime_name) print("\n") if len(anime_list) == 0: print("No anime found with this name") else: print(f"Found {len(anime_list)} results: ") for i, anime in enumerate(anime_list): anime_title = anime["title"] print(f"{i+1}. {anime_title}") anime_choice = int(input("\nPlease choose from the following list: ").strip()) chosen_anime = anime_list[anime_choice - 1] print(f"You chose {chosen_anime['title']}. Searching for episodes...") episode_list = search_anime_episode_list(chosen_anime["url"]) if len(episode_list) == 0: print("No episode found for this anime") else: print(f"Found {len(episode_list)} results: ") for i, episode in enumerate(episode_list): print(f"{i+1}. {episode['title']}") episode_choice = int(input("\nChoose an episode by serial no: ").strip()) chosen_episode = episode_list[episode_choice - 1] print(f"You chose {chosen_episode['title']}. Searching...") episode_url, download_url = get_anime_episode(chosen_episode["url"]) print(f"\nTo watch, ctrl+click on {episode_url}.") print(f"To download, ctrl+click on {download_url}.")
import requests from bs4 import BeautifulSoup, NavigableString, Tag from fake_useragent import UserAgent BASE_URL = "https://ww1.gogoanime2.org" def search_scraper(anime_name: str) -> list: """[summary] Take an url and return list of anime after scraping the site. >>> type(search_scraper("demon_slayer")) <class 'list'> Args: anime_name (str): [Name of anime] Raises: e: [Raises exception on failure] Returns: [list]: [List of animes] """ # concat the name to form the search url. search_url = f"{BASE_URL}/search/{anime_name}" response = requests.get( search_url, headers={"UserAgent": UserAgent().chrome} ) # request the url. # Is the response ok? response.raise_for_status() # parse with soup. soup = BeautifulSoup(response.text, "html.parser") # get list of anime anime_ul = soup.find("ul", {"class": "items"}) if anime_ul is None or isinstance(anime_ul, NavigableString): msg = f"Could not find and anime with name {anime_name}" raise ValueError(msg) anime_li = anime_ul.children # for each anime, insert to list. the name and url. anime_list = [] for anime in anime_li: if isinstance(anime, Tag): anime_url = anime.find("a") if anime_url is None or isinstance(anime_url, NavigableString): continue anime_title = anime.find("a") if anime_title is None or isinstance(anime_title, NavigableString): continue anime_list.append({"title": anime_title["title"], "url": anime_url["href"]}) return anime_list def search_anime_episode_list(episode_endpoint: str) -> list: """[summary] Take an url and return list of episodes after scraping the site for an url. >>> type(search_anime_episode_list("/anime/kimetsu-no-yaiba")) <class 'list'> Args: episode_endpoint (str): [Endpoint of episode] Raises: e: [description] Returns: [list]: [List of episodes] """ request_url = f"{BASE_URL}{episode_endpoint}" response = requests.get(url=request_url, headers={"UserAgent": UserAgent().chrome}) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") # With this id. get the episode list. episode_page_ul = soup.find("ul", {"id": "episode_related"}) if episode_page_ul is None or isinstance(episode_page_ul, NavigableString): msg = f"Could not find any anime eposiodes with name {anime_name}" raise ValueError(msg) episode_page_li = episode_page_ul.children episode_list = [] for episode in episode_page_li: if isinstance(episode, Tag): url = episode.find("a") if url is None or isinstance(url, NavigableString): continue title = episode.find("div", {"class": "name"}) if title is None or isinstance(title, NavigableString): continue episode_list.append( {"title": title.text.replace(" ", ""), "url": url["href"]} ) return episode_list def get_anime_episode(episode_endpoint: str) -> list: """[summary] Get click url and download url from episode url >>> type(get_anime_episode("/watch/kimetsu-no-yaiba/1")) <class 'list'> Args: episode_endpoint (str): [Endpoint of episode] Raises: e: [description] Returns: [list]: [List of download and watch url] """ episode_page_url = f"{BASE_URL}{episode_endpoint}" response = requests.get( url=episode_page_url, headers={"User-Agent": UserAgent().chrome} ) response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") url = soup.find("iframe", {"id": "playerframe"}) if url is None or isinstance(url, NavigableString): msg = f"Could not find url and download url from {episode_endpoint}" raise RuntimeError(msg) episode_url = url["src"] if not isinstance(episode_url, str): msg = f"Could not find url and download url from {episode_endpoint}" raise RuntimeError(msg) download_url = episode_url.replace("/embed/", "/playlist/") + ".m3u8" return [f"{BASE_URL}{episode_url}", f"{BASE_URL}{download_url}"] if __name__ == "__main__": anime_name = input("Enter anime name: ").strip() anime_list = search_scraper(anime_name) print("\n") if len(anime_list) == 0: print("No anime found with this name") else: print(f"Found {len(anime_list)} results: ") for i, anime in enumerate(anime_list): anime_title = anime["title"] print(f"{i+1}. {anime_title}") anime_choice = int(input("\nPlease choose from the following list: ").strip()) chosen_anime = anime_list[anime_choice - 1] print(f"You chose {chosen_anime['title']}. Searching for episodes...") episode_list = search_anime_episode_list(chosen_anime["url"]) if len(episode_list) == 0: print("No episode found for this anime") else: print(f"Found {len(episode_list)} results: ") for i, episode in enumerate(episode_list): print(f"{i+1}. {episode['title']}") episode_choice = int(input("\nChoose an episode by serial no: ").strip()) chosen_episode = episode_list[episode_choice - 1] print(f"You chose {chosen_episode['title']}. Searching...") episode_url, download_url = get_anime_episode(chosen_episode["url"]) print(f"\nTo watch, ctrl+click on {episode_url}.") print(f"To download, ctrl+click on {download_url}.")
-1
TheAlgorithms/Python
9,707
Fix mypy errors in circular_linked_list.py and swap_nodes.py
### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-10-04T14:51:39Z"
"2023-10-04T16:05:01Z"
3fd3497f15982a7286326b520b5e7b52767da1f3
dfdd78135df938d948ba3044aca628aca08886e7
Fix mypy errors in circular_linked_list.py and swap_nodes.py. ### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
9,707
Fix mypy errors in circular_linked_list.py and swap_nodes.py
### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-10-04T14:51:39Z"
"2023-10-04T16:05:01Z"
3fd3497f15982a7286326b520b5e7b52767da1f3
dfdd78135df938d948ba3044aca628aca08886e7
Fix mypy errors in circular_linked_list.py and swap_nodes.py. ### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
9,707
Fix mypy errors in circular_linked_list.py and swap_nodes.py
### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-10-04T14:51:39Z"
"2023-10-04T16:05:01Z"
3fd3497f15982a7286326b520b5e7b52767da1f3
dfdd78135df938d948ba3044aca628aca08886e7
Fix mypy errors in circular_linked_list.py and swap_nodes.py. ### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
def stooge_sort(arr: list[int]) -> list[int]: """ Examples: >>> stooge_sort([18.1, 0, -7.1, -1, 2, 2]) [-7.1, -1, 0, 2, 2, 18.1] >>> stooge_sort([]) [] """ stooge(arr, 0, len(arr) - 1) return arr def stooge(arr: list[int], i: int, h: int) -> None: if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: arr[i], arr[h] = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: t = (int)((h - i + 1) / 3) # Recursively sort first 2/3 elements stooge(arr, i, (h - t)) # Recursively sort last 2/3 elements stooge(arr, i + t, (h)) # Recursively sort first 2/3 elements stooge(arr, i, (h - t)) if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(stooge_sort(unsorted))
def stooge_sort(arr: list[int]) -> list[int]: """ Examples: >>> stooge_sort([18.1, 0, -7.1, -1, 2, 2]) [-7.1, -1, 0, 2, 2, 18.1] >>> stooge_sort([]) [] """ stooge(arr, 0, len(arr) - 1) return arr def stooge(arr: list[int], i: int, h: int) -> None: if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: arr[i], arr[h] = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: t = (int)((h - i + 1) / 3) # Recursively sort first 2/3 elements stooge(arr, i, (h - t)) # Recursively sort last 2/3 elements stooge(arr, i + t, (h)) # Recursively sort first 2/3 elements stooge(arr, i, (h - t)) if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(stooge_sort(unsorted))
-1
TheAlgorithms/Python
9,707
Fix mypy errors in circular_linked_list.py and swap_nodes.py
### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-10-04T14:51:39Z"
"2023-10-04T16:05:01Z"
3fd3497f15982a7286326b520b5e7b52767da1f3
dfdd78135df938d948ba3044aca628aca08886e7
Fix mypy errors in circular_linked_list.py and swap_nodes.py. ### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
import argparse import datetime def zeller(date_input: str) -> str: """ Zellers Congruence Algorithm Find the day of the week for nearly any Gregorian or Julian calendar date >>> zeller('01-31-2010') 'Your date 01-31-2010, is a Sunday!' Validate out of range month >>> zeller('13-31-2010') Traceback (most recent call last): ... ValueError: Month must be between 1 - 12 >>> zeller('.2-31-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.2' Validate out of range date: >>> zeller('01-33-2010') Traceback (most recent call last): ... ValueError: Date must be between 1 - 31 >>> zeller('01-.4-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.4' Validate second separator: >>> zeller('01-31*2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate first separator: >>> zeller('01^31-2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate out of range year: >>> zeller('01-31-8999') Traceback (most recent call last): ... ValueError: Year out of range. There has to be some sort of limit...right? Test null input: >>> zeller() Traceback (most recent call last): ... TypeError: zeller() missing 1 required positional argument: 'date_input' Test length of date_input: >>> zeller('') Traceback (most recent call last): ... ValueError: Must be 10 characters long >>> zeller('01-31-19082939') Traceback (most recent call last): ... ValueError: Must be 10 characters long""" # Days of the week for response days = { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday", } convert_datetime_days = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(date_input) < 11: raise ValueError("Must be 10 characters long") # Get month m: int = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError("Month must be between 1 - 12") sep_1: str = date_input[2] # Validate if sep_1 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get day d: int = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError("Date must be between 1 - 31") # Get second separator sep_2: str = date_input[5] # Validate if sep_2 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get year y: int = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( "Year out of range. There has to be some sort of limit...right?" ) # Get datetime obj for validation dt_ck = datetime.date(int(y), int(m), int(d)) # Start math if m <= 2: y = y - 1 m = m + 12 # maths var c: int = int(str(y)[:2]) k: int = int(str(y)[2:]) t: int = int(2.6 * m - 5.39) u: int = int(c / 4) v: int = int(k / 4) x: int = int(d + k) z: int = int(t + u + v + x) w: int = int(z - (2 * c)) f: int = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("The date was evaluated incorrectly. Contact developer.") # Response response: str = f"Your date {date_input}, is a {days[str(f)]}!" return response if __name__ == "__main__": import doctest doctest.testmod() parser = argparse.ArgumentParser( description=( "Find out what day of the week nearly any date is or was. Enter " "date as a string in the mm-dd-yyyy or mm/dd/yyyy format" ) ) parser.add_argument( "date_input", type=str, help="Date as a string (mm-dd-yyyy or mm/dd/yyyy)" ) args = parser.parse_args() zeller(args.date_input)
import argparse import datetime def zeller(date_input: str) -> str: """ Zellers Congruence Algorithm Find the day of the week for nearly any Gregorian or Julian calendar date >>> zeller('01-31-2010') 'Your date 01-31-2010, is a Sunday!' Validate out of range month >>> zeller('13-31-2010') Traceback (most recent call last): ... ValueError: Month must be between 1 - 12 >>> zeller('.2-31-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.2' Validate out of range date: >>> zeller('01-33-2010') Traceback (most recent call last): ... ValueError: Date must be between 1 - 31 >>> zeller('01-.4-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.4' Validate second separator: >>> zeller('01-31*2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate first separator: >>> zeller('01^31-2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate out of range year: >>> zeller('01-31-8999') Traceback (most recent call last): ... ValueError: Year out of range. There has to be some sort of limit...right? Test null input: >>> zeller() Traceback (most recent call last): ... TypeError: zeller() missing 1 required positional argument: 'date_input' Test length of date_input: >>> zeller('') Traceback (most recent call last): ... ValueError: Must be 10 characters long >>> zeller('01-31-19082939') Traceback (most recent call last): ... ValueError: Must be 10 characters long""" # Days of the week for response days = { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday", } convert_datetime_days = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(date_input) < 11: raise ValueError("Must be 10 characters long") # Get month m: int = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError("Month must be between 1 - 12") sep_1: str = date_input[2] # Validate if sep_1 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get day d: int = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError("Date must be between 1 - 31") # Get second separator sep_2: str = date_input[5] # Validate if sep_2 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get year y: int = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( "Year out of range. There has to be some sort of limit...right?" ) # Get datetime obj for validation dt_ck = datetime.date(int(y), int(m), int(d)) # Start math if m <= 2: y = y - 1 m = m + 12 # maths var c: int = int(str(y)[:2]) k: int = int(str(y)[2:]) t: int = int(2.6 * m - 5.39) u: int = int(c / 4) v: int = int(k / 4) x: int = int(d + k) z: int = int(t + u + v + x) w: int = int(z - (2 * c)) f: int = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("The date was evaluated incorrectly. Contact developer.") # Response response: str = f"Your date {date_input}, is a {days[str(f)]}!" return response if __name__ == "__main__": import doctest doctest.testmod() parser = argparse.ArgumentParser( description=( "Find out what day of the week nearly any date is or was. Enter " "date as a string in the mm-dd-yyyy or mm/dd/yyyy format" ) ) parser.add_argument( "date_input", type=str, help="Date as a string (mm-dd-yyyy or mm/dd/yyyy)" ) args = parser.parse_args() zeller(args.date_input)
-1
TheAlgorithms/Python
9,707
Fix mypy errors in circular_linked_list.py and swap_nodes.py
### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-10-04T14:51:39Z"
"2023-10-04T16:05:01Z"
3fd3497f15982a7286326b520b5e7b52767da1f3
dfdd78135df938d948ba3044aca628aca08886e7
Fix mypy errors in circular_linked_list.py and swap_nodes.py. ### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# Author: João Gustavo A. Amorim & Gabriel Kunz # Author email: joaogustavoamorim@gmail.com and gabriel-kunz@uergs.edu.br # Coding date: apr 2019 # Black: True """ * This code implement the Hamming code: https://en.wikipedia.org/wiki/Hamming_code - In telecommunication, Hamming codes are a family of linear error-correcting codes. Hamming codes can detect up to two-bit errors or correct one-bit errors without detection of uncorrected errors. By contrast, the simple parity code cannot correct errors, and can detect only an odd number of bits in error. Hamming codes are perfect codes, that is, they achieve the highest possible rate for codes with their block length and minimum distance of three. * the implemented code consists of: * a function responsible for encoding the message (emitterConverter) * return the encoded message * a function responsible for decoding the message (receptorConverter) * return the decoded message and a ack of data integrity * how to use: to be used you must declare how many parity bits (sizePari) you want to include in the message. it is desired (for test purposes) to select a bit to be set as an error. This serves to check whether the code is working correctly. Lastly, the variable of the message/word that must be desired to be encoded (text). * how this work: declaration of variables (sizePari, be, text) converts the message/word (text) to binary using the text_to_bits function encodes the message using the rules of hamming encoding decodes the message using the rules of hamming encoding print the original message, the encoded message and the decoded message forces an error in the coded text variable decodes the message that was forced the error print the original message, the encoded message, the bit changed message and the decoded message """ # Imports import numpy as np # Functions of binary conversion-------------------------------------- def text_to_bits(text, encoding="utf-8", errors="surrogatepass"): """ >>> text_to_bits("msg") '011011010111001101100111' """ bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) def text_from_bits(bits, encoding="utf-8", errors="surrogatepass"): """ >>> text_from_bits('011011010111001101100111') 'msg' """ n = int(bits, 2) return n.to_bytes((n.bit_length() + 7) // 8, "big").decode(encoding, errors) or "\0" # Functions of hamming code------------------------------------------- def emitter_converter(size_par, data): """ :param size_par: how many parity bits the message must have :param data: information bits :return: message to be transmitted by unreliable medium - bits of information merged with parity bits >>> emitter_converter(4, "101010111111") ['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1'] """ if size_par + len(data) <= 2**size_par - (len(data) - 1): raise ValueError("size of parity don't match with size of data") data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data) + 1)] # sorted information data for the size of the output data data_ord = [] # data position template + parity data_out_gab = [] # parity bit counter qtd_bp = 0 # counter position of data bits cont_data = 0 for x in range(1, size_par + len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par: if (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a given parity cont_bo = 0 # counter to control the loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1" and x == "1": cont_bo += 1 cont_loop += 1 parity.append(cont_bo % 2) qtd_bp += 1 # Mount the message cont_bp = 0 # parity bit counter for x in range(size_par + len(data)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) return data_out def receptor_converter(size_par, data): """ >>> receptor_converter(4, "1111010010111111") (['1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1'], True) """ # data position template + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 # list of parity received parity_received = [] data_output = [] for x in range(1, len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_output.append(data[cont_data]) else: parity_received.append(data[cont_data]) cont_data += 1 # -----------calculates the parity with the data data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data_output) + 1)] # sorted information data for the size of the output data data_ord = [] # Data position feedback + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 for x in range(1, size_par + len(data_output) + 1): # Performs a template position of bits - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data_output[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a certain parity cont_bo = 0 # Counter to control loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1" and x == "1": cont_bo += 1 cont_loop += 1 parity.append(str(cont_bo % 2)) qtd_bp += 1 # Mount the message cont_bp = 0 # Parity bit counter for x in range(size_par + len(data_output)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) ack = parity_received == parity return data_output, ack # --------------------------------------------------------------------- """ # Example how to use # number of parity bits sizePari = 4 # location of the bit that will be forced an error be = 2 # Message/word to be encoded and decoded with hamming # text = input("Enter the word to be read: ") text = "Message01" # Convert the message to binary binaryText = text_to_bits(text) # Prints the binary of the string print("Text input in binary is '" + binaryText + "'") # total transmitted bits totalBits = len(binaryText) + sizePari print("Size of data is " + str(totalBits)) print("\n --Message exchange--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) print("\n --Force error--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) # forces error dataOut[-be] = "1" * (dataOut[-be] == "0") + "0" * (dataOut[-be] == "1") print("Data after transmission -> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) """
# Author: João Gustavo A. Amorim & Gabriel Kunz # Author email: joaogustavoamorim@gmail.com and gabriel-kunz@uergs.edu.br # Coding date: apr 2019 # Black: True """ * This code implement the Hamming code: https://en.wikipedia.org/wiki/Hamming_code - In telecommunication, Hamming codes are a family of linear error-correcting codes. Hamming codes can detect up to two-bit errors or correct one-bit errors without detection of uncorrected errors. By contrast, the simple parity code cannot correct errors, and can detect only an odd number of bits in error. Hamming codes are perfect codes, that is, they achieve the highest possible rate for codes with their block length and minimum distance of three. * the implemented code consists of: * a function responsible for encoding the message (emitterConverter) * return the encoded message * a function responsible for decoding the message (receptorConverter) * return the decoded message and a ack of data integrity * how to use: to be used you must declare how many parity bits (sizePari) you want to include in the message. it is desired (for test purposes) to select a bit to be set as an error. This serves to check whether the code is working correctly. Lastly, the variable of the message/word that must be desired to be encoded (text). * how this work: declaration of variables (sizePari, be, text) converts the message/word (text) to binary using the text_to_bits function encodes the message using the rules of hamming encoding decodes the message using the rules of hamming encoding print the original message, the encoded message and the decoded message forces an error in the coded text variable decodes the message that was forced the error print the original message, the encoded message, the bit changed message and the decoded message """ # Imports import numpy as np # Functions of binary conversion-------------------------------------- def text_to_bits(text, encoding="utf-8", errors="surrogatepass"): """ >>> text_to_bits("msg") '011011010111001101100111' """ bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:] return bits.zfill(8 * ((len(bits) + 7) // 8)) def text_from_bits(bits, encoding="utf-8", errors="surrogatepass"): """ >>> text_from_bits('011011010111001101100111') 'msg' """ n = int(bits, 2) return n.to_bytes((n.bit_length() + 7) // 8, "big").decode(encoding, errors) or "\0" # Functions of hamming code------------------------------------------- def emitter_converter(size_par, data): """ :param size_par: how many parity bits the message must have :param data: information bits :return: message to be transmitted by unreliable medium - bits of information merged with parity bits >>> emitter_converter(4, "101010111111") ['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1'] """ if size_par + len(data) <= 2**size_par - (len(data) - 1): raise ValueError("size of parity don't match with size of data") data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data) + 1)] # sorted information data for the size of the output data data_ord = [] # data position template + parity data_out_gab = [] # parity bit counter qtd_bp = 0 # counter position of data bits cont_data = 0 for x in range(1, size_par + len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par: if (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a given parity cont_bo = 0 # counter to control the loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1" and x == "1": cont_bo += 1 cont_loop += 1 parity.append(cont_bo % 2) qtd_bp += 1 # Mount the message cont_bp = 0 # parity bit counter for x in range(size_par + len(data)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) return data_out def receptor_converter(size_par, data): """ >>> receptor_converter(4, "1111010010111111") (['1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1'], True) """ # data position template + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 # list of parity received parity_received = [] data_output = [] for x in range(1, len(data) + 1): # Performs a template of bit positions - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_output.append(data[cont_data]) else: parity_received.append(data[cont_data]) cont_data += 1 # -----------calculates the parity with the data data_out = [] parity = [] bin_pos = [bin(x)[2:] for x in range(1, size_par + len(data_output) + 1)] # sorted information data for the size of the output data data_ord = [] # Data position feedback + parity data_out_gab = [] # Parity bit counter qtd_bp = 0 # Counter p data bit reading cont_data = 0 for x in range(1, size_par + len(data_output) + 1): # Performs a template position of bits - who should be given, # and who should be parity if qtd_bp < size_par and (np.log(x) / np.log(2)).is_integer(): data_out_gab.append("P") qtd_bp = qtd_bp + 1 else: data_out_gab.append("D") # Sorts the data to the new output size if data_out_gab[-1] == "D": data_ord.append(data_output[cont_data]) cont_data += 1 else: data_ord.append(None) # Calculates parity qtd_bp = 0 # parity bit counter for bp in range(1, size_par + 1): # Bit counter one for a certain parity cont_bo = 0 # Counter to control loop reading cont_loop = 0 for x in data_ord: if x is not None: try: aux = (bin_pos[cont_loop])[-1 * (bp)] except IndexError: aux = "0" if aux == "1" and x == "1": cont_bo += 1 cont_loop += 1 parity.append(str(cont_bo % 2)) qtd_bp += 1 # Mount the message cont_bp = 0 # Parity bit counter for x in range(size_par + len(data_output)): if data_ord[x] is None: data_out.append(str(parity[cont_bp])) cont_bp += 1 else: data_out.append(data_ord[x]) ack = parity_received == parity return data_output, ack # --------------------------------------------------------------------- """ # Example how to use # number of parity bits sizePari = 4 # location of the bit that will be forced an error be = 2 # Message/word to be encoded and decoded with hamming # text = input("Enter the word to be read: ") text = "Message01" # Convert the message to binary binaryText = text_to_bits(text) # Prints the binary of the string print("Text input in binary is '" + binaryText + "'") # total transmitted bits totalBits = len(binaryText) + sizePari print("Size of data is " + str(totalBits)) print("\n --Message exchange--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) print("\n --Force error--") print("Data to send ------------> " + binaryText) dataOut = emitterConverter(sizePari, binaryText) print("Data converted ----------> " + "".join(dataOut)) # forces error dataOut[-be] = "1" * (dataOut[-be] == "0") + "0" * (dataOut[-be] == "1") print("Data after transmission -> " + "".join(dataOut)) dataReceiv, ack = receptorConverter(sizePari, dataOut) print( "Data receive ------------> " + "".join(dataReceiv) + "\t\t -- Data integrity: " + str(ack) ) """
-1
TheAlgorithms/Python
9,707
Fix mypy errors in circular_linked_list.py and swap_nodes.py
### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-10-04T14:51:39Z"
"2023-10-04T16:05:01Z"
3fd3497f15982a7286326b520b5e7b52767da1f3
dfdd78135df938d948ba3044aca628aca08886e7
Fix mypy errors in circular_linked_list.py and swap_nodes.py. ### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
class Graph: """ Data structure to store graphs (based on adjacency lists) """ def __init__(self): self.num_vertices = 0 self.num_edges = 0 self.adjacency = {} def add_vertex(self, vertex): """ Adds a vertex to the graph """ if vertex not in self.adjacency: self.adjacency[vertex] = {} self.num_vertices += 1 def add_edge(self, head, tail, weight): """ Adds an edge to the graph """ self.add_vertex(head) self.add_vertex(tail) if head == tail: return self.adjacency[head][tail] = weight self.adjacency[tail][head] = weight def distinct_weight(self): """ For Boruvks's algorithm the weights should be distinct Converts the weights to be distinct """ edges = self.get_edges() for edge in edges: head, tail, weight = edge edges.remove((tail, head, weight)) for i in range(len(edges)): edges[i] = list(edges[i]) edges.sort(key=lambda e: e[2]) for i in range(len(edges) - 1): if edges[i][2] >= edges[i + 1][2]: edges[i + 1][2] = edges[i][2] + 1 for edge in edges: head, tail, weight = edge self.adjacency[head][tail] = weight self.adjacency[tail][head] = weight def __str__(self): """ Returns string representation of the graph """ string = "" for tail in self.adjacency: for head in self.adjacency[tail]: weight = self.adjacency[head][tail] string += f"{head} -> {tail} == {weight}\n" return string.rstrip("\n") def get_edges(self): """ Returna all edges in the graph """ output = [] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail])) return output def get_vertices(self): """ Returns all vertices in the graph """ return self.adjacency.keys() @staticmethod def build(vertices=None, edges=None): """ Builds a graph from the given set of vertices and edges """ g = Graph() if vertices is None: vertices = [] if edges is None: edge = [] for vertex in vertices: g.add_vertex(vertex) for edge in edges: g.add_edge(*edge) return g class UnionFind: """ Disjoint set Union and Find for Boruvka's algorithm """ def __init__(self): self.parent = {} self.rank = {} def __len__(self): return len(self.parent) def make_set(self, item): if item in self.parent: return self.find(item) self.parent[item] = item self.rank[item] = 0 return item def find(self, item): if item not in self.parent: return self.make_set(item) if item != self.parent[item]: self.parent[item] = self.find(self.parent[item]) return self.parent[item] def union(self, item1, item2): root1 = self.find(item1) root2 = self.find(item2) if root1 == root2: return root1 if self.rank[root1] > self.rank[root2]: self.parent[root2] = root1 return root1 if self.rank[root1] < self.rank[root2]: self.parent[root1] = root2 return root2 if self.rank[root1] == self.rank[root2]: self.rank[root1] += 1 self.parent[root2] = root1 return root1 return None @staticmethod def boruvka_mst(graph): """ Implementation of Boruvka's algorithm >>> g = Graph() >>> g = Graph.build([0, 1, 2, 3], [[0, 1, 1], [0, 2, 1],[2, 3, 1]]) >>> g.distinct_weight() >>> bg = Graph.boruvka_mst(g) >>> print(bg) 1 -> 0 == 1 2 -> 0 == 2 0 -> 1 == 1 0 -> 2 == 2 3 -> 2 == 3 2 -> 3 == 3 """ num_components = graph.num_vertices union_find = Graph.UnionFind() mst_edges = [] while num_components > 1: cheap_edge = {} for vertex in graph.get_vertices(): cheap_edge[vertex] = -1 edges = graph.get_edges() for edge in edges: head, tail, weight = edge edges.remove((tail, head, weight)) for edge in edges: head, tail, weight = edge set1 = union_find.find(head) set2 = union_find.find(tail) if set1 != set2: if cheap_edge[set1] == -1 or cheap_edge[set1][2] > weight: cheap_edge[set1] = [head, tail, weight] if cheap_edge[set2] == -1 or cheap_edge[set2][2] > weight: cheap_edge[set2] = [head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: head, tail, weight = cheap_edge[vertex] if union_find.find(head) != union_find.find(tail): union_find.union(head, tail) mst_edges.append(cheap_edge[vertex]) num_components = num_components - 1 mst = Graph.build(edges=mst_edges) return mst
class Graph: """ Data structure to store graphs (based on adjacency lists) """ def __init__(self): self.num_vertices = 0 self.num_edges = 0 self.adjacency = {} def add_vertex(self, vertex): """ Adds a vertex to the graph """ if vertex not in self.adjacency: self.adjacency[vertex] = {} self.num_vertices += 1 def add_edge(self, head, tail, weight): """ Adds an edge to the graph """ self.add_vertex(head) self.add_vertex(tail) if head == tail: return self.adjacency[head][tail] = weight self.adjacency[tail][head] = weight def distinct_weight(self): """ For Boruvks's algorithm the weights should be distinct Converts the weights to be distinct """ edges = self.get_edges() for edge in edges: head, tail, weight = edge edges.remove((tail, head, weight)) for i in range(len(edges)): edges[i] = list(edges[i]) edges.sort(key=lambda e: e[2]) for i in range(len(edges) - 1): if edges[i][2] >= edges[i + 1][2]: edges[i + 1][2] = edges[i][2] + 1 for edge in edges: head, tail, weight = edge self.adjacency[head][tail] = weight self.adjacency[tail][head] = weight def __str__(self): """ Returns string representation of the graph """ string = "" for tail in self.adjacency: for head in self.adjacency[tail]: weight = self.adjacency[head][tail] string += f"{head} -> {tail} == {weight}\n" return string.rstrip("\n") def get_edges(self): """ Returna all edges in the graph """ output = [] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail])) return output def get_vertices(self): """ Returns all vertices in the graph """ return self.adjacency.keys() @staticmethod def build(vertices=None, edges=None): """ Builds a graph from the given set of vertices and edges """ g = Graph() if vertices is None: vertices = [] if edges is None: edge = [] for vertex in vertices: g.add_vertex(vertex) for edge in edges: g.add_edge(*edge) return g class UnionFind: """ Disjoint set Union and Find for Boruvka's algorithm """ def __init__(self): self.parent = {} self.rank = {} def __len__(self): return len(self.parent) def make_set(self, item): if item in self.parent: return self.find(item) self.parent[item] = item self.rank[item] = 0 return item def find(self, item): if item not in self.parent: return self.make_set(item) if item != self.parent[item]: self.parent[item] = self.find(self.parent[item]) return self.parent[item] def union(self, item1, item2): root1 = self.find(item1) root2 = self.find(item2) if root1 == root2: return root1 if self.rank[root1] > self.rank[root2]: self.parent[root2] = root1 return root1 if self.rank[root1] < self.rank[root2]: self.parent[root1] = root2 return root2 if self.rank[root1] == self.rank[root2]: self.rank[root1] += 1 self.parent[root2] = root1 return root1 return None @staticmethod def boruvka_mst(graph): """ Implementation of Boruvka's algorithm >>> g = Graph() >>> g = Graph.build([0, 1, 2, 3], [[0, 1, 1], [0, 2, 1],[2, 3, 1]]) >>> g.distinct_weight() >>> bg = Graph.boruvka_mst(g) >>> print(bg) 1 -> 0 == 1 2 -> 0 == 2 0 -> 1 == 1 0 -> 2 == 2 3 -> 2 == 3 2 -> 3 == 3 """ num_components = graph.num_vertices union_find = Graph.UnionFind() mst_edges = [] while num_components > 1: cheap_edge = {} for vertex in graph.get_vertices(): cheap_edge[vertex] = -1 edges = graph.get_edges() for edge in edges: head, tail, weight = edge edges.remove((tail, head, weight)) for edge in edges: head, tail, weight = edge set1 = union_find.find(head) set2 = union_find.find(tail) if set1 != set2: if cheap_edge[set1] == -1 or cheap_edge[set1][2] > weight: cheap_edge[set1] = [head, tail, weight] if cheap_edge[set2] == -1 or cheap_edge[set2][2] > weight: cheap_edge[set2] = [head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: head, tail, weight = cheap_edge[vertex] if union_find.find(head) != union_find.find(tail): union_find.union(head, tail) mst_edges.append(cheap_edge[vertex]) num_components = num_components - 1 mst = Graph.build(edges=mst_edges) return mst
-1
TheAlgorithms/Python
9,707
Fix mypy errors in circular_linked_list.py and swap_nodes.py
### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-10-04T14:51:39Z"
"2023-10-04T16:05:01Z"
3fd3497f15982a7286326b520b5e7b52767da1f3
dfdd78135df938d948ba3044aca628aca08886e7
Fix mypy errors in circular_linked_list.py and swap_nodes.py. ### Describe your change: Fixes #9710 Fix mypy errors in `data_structures/linked_list/circular_linked_list.py` and `data_structures/linked_list/swap_nodes.py` that were let through in #9668. These errors are causing every new PR to fail the pre-commit check. My fixes primarily consisted of `assert` statements and type hints in order to convince mypy of (implicitly understood) type guarantees. * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Calculate price plus tax of a good or service given its price and a tax rate. """ def price_plus_tax(price: float, tax_rate: float) -> float: """ >>> price_plus_tax(100, 0.25) 125.0 >>> price_plus_tax(125.50, 0.05) 131.775 """ return price * (1 + tax_rate) if __name__ == "__main__": print(f"{price_plus_tax(100, 0.25) = }") print(f"{price_plus_tax(125.50, 0.05) = }")
""" Calculate price plus tax of a good or service given its price and a tax rate. """ def price_plus_tax(price: float, tax_rate: float) -> float: """ >>> price_plus_tax(100, 0.25) 125.0 >>> price_plus_tax(125.50, 0.05) 131.775 """ return price * (1 + tax_rate) if __name__ == "__main__": print(f"{price_plus_tax(100, 0.25) = }") print(f"{price_plus_tax(125.50, 0.05) = }")
-1