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 | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| name: "build"
on:
pull_request:
schedule:
- cron: "0 0 * * *" # Run everyday
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: "3.9"
- uses: actions/cache@v2
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip setuptools six wheel
python -m pip install mypy pytest-cov -r requirements.txt
- run: mypy . # See `mypy.ini` for configuration settings.
- name: Run tests
run: pytest --doctest-modules --ignore=project_euler/ --ignore=scripts/validate_solutions.py --cov-report=term-missing:skip-covered --cov=. .
- if: ${{ success() }}
run: scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md
| name: "build"
on:
pull_request:
schedule:
- cron: "0 0 * * *" # Run everyday
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: "3.9"
- uses: actions/cache@v2
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip setuptools six wheel
python -m pip install mypy pytest-cov -r requirements.txt
- run: mypy --ignore-missing-imports --install-types --non-interactive .
- name: Run tests
run: pytest --doctest-modules --ignore=project_euler/ --ignore=scripts/validate_solutions.py --cov-report=term-missing:skip-covered --cov=. .
- if: ${{ success() }}
run: scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md
| 1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| name: pre-commit
on: [push, pull_request]
jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/cache@v2
with:
path: |
~/.cache/pre-commit
~/.cache/pip
key: ${{ runner.os }}-pre-commit-${{ hashFiles('.pre-commit-config.yaml') }}
- uses: actions/setup-python@v2
- uses: psf/[email protected]
- name: Install pre-commit
run: |
python -m pip install --upgrade pip
python -m pip install --upgrade pre-commit
- run: pre-commit run --verbose --all-files --show-diff-on-failure
| name: pre-commit
on: [push, pull_request]
jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/cache@v2
with:
path: |
~/.cache/pre-commit
~/.cache/pip
key: ${{ runner.os }}-pre-commit-${{ hashFiles('.pre-commit-config.yaml') }}
- uses: actions/setup-python@v2
with:
python-version: 3.9
- uses: psf/[email protected]
- name: Install pre-commit
run: |
python -m pip install --upgrade pip
python -m pip install --upgrade pre-commit
- run: pre-commit run --verbose --all-files --show-diff-on-failure
| 1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.4.0
hooks:
- id: check-executables-have-shebangs
- id: check-yaml
- id: end-of-file-fixer
types: [python]
- id: trailing-whitespace
exclude: |
(?x)^(
data_structures/heap/binomial_heap.py
)$
- id: requirements-txt-fixer
- repo: https://github.com/psf/black
rev: 21.4b0
hooks:
- id: black
- repo: https://github.com/PyCQA/isort
rev: 5.8.0
hooks:
- id: isort
args:
- --profile=black
- repo: https://github.com/asottile/pyupgrade
rev: v2.29.0
hooks:
- id: pyupgrade
args:
- --py39-plus
- repo: https://gitlab.com/pycqa/flake8
rev: 3.9.1
hooks:
- id: flake8
args:
- --ignore=E203,W503
- --max-complexity=25
- --max-line-length=88
# FIXME: fix mypy errors and then uncomment this
# - repo: https://github.com/pre-commit/mirrors-mypy
# rev: v0.782
# hooks:
# - id: mypy
# args:
# - --ignore-missing-imports
- repo: https://github.com/codespell-project/codespell
rev: v2.0.0
hooks:
- id: codespell
args:
- --ignore-words-list=ans,crate,fo,followings,hist,iff,mater,secant,som,tim
- --skip="./.*,./strings/dictionary.txt,./strings/words.txt,./project_euler/problem_022/p022_names.txt"
- --quiet-level=2
exclude: |
(?x)^(
strings/dictionary.txt |
strings/words.txt |
project_euler/problem_022/p022_names.txt
)$
- repo: local
hooks:
- id: validate-filenames
name: Validate filenames
entry: ./scripts/validate_filenames.py
language: script
pass_filenames: false
| repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.4.0
hooks:
- id: check-executables-have-shebangs
- id: check-yaml
- id: end-of-file-fixer
types: [python]
- id: trailing-whitespace
exclude: |
(?x)^(
data_structures/heap/binomial_heap.py
)$
- id: requirements-txt-fixer
- repo: https://github.com/psf/black
rev: 21.4b0
hooks:
- id: black
- repo: https://github.com/PyCQA/isort
rev: 5.8.0
hooks:
- id: isort
args:
- --profile=black
- repo: https://github.com/asottile/pyupgrade
rev: v2.29.0
hooks:
- id: pyupgrade
args:
- --py39-plus
- repo: https://gitlab.com/pycqa/flake8
rev: 3.9.1
hooks:
- id: flake8
args:
- --ignore=E203,W503
- --max-complexity=25
- --max-line-length=88
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.910
hooks:
- id: mypy
args:
- --ignore-missing-imports
- --install-types # See mirrors-mypy README.md
- --non-interactive
- repo: https://github.com/codespell-project/codespell
rev: v2.0.0
hooks:
- id: codespell
args:
- --ignore-words-list=ans,crate,fo,followings,hist,iff,mater,secant,som,tim
- --skip="./.*,./strings/dictionary.txt,./strings/words.txt,./project_euler/problem_022/p022_names.txt"
exclude: |
(?x)^(
strings/dictionary.txt |
strings/words.txt |
project_euler/problem_022/p022_names.txt
)$
- repo: local
hooks:
- id: validate-filenames
name: Validate filenames
entry: ./scripts/validate_filenames.py
language: script
pass_filenames: false
| 1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import sys
from collections import deque
class LRUCache:
"""Page Replacement Algorithm, Least Recently Used (LRU) Caching."""
dq_store = object() # Cache store of keys
key_reference_map = object() # References of the keys in cache
_MAX_CAPACITY: int = 10 # Maximum capacity of cache
def __init__(self, n: int):
"""Creates an empty store and map for the keys.
The LRUCache is set the size n.
"""
self.dq_store = deque()
self.key_reference_map = 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):
"""
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_map:
if len(self.dq_store) == LRUCache._MAX_CAPACITY:
last_element = self.dq_store.pop()
self.key_reference_map.remove(last_element)
else:
index_remove = 0
for idx, key in enumerate(self.dq_store):
if key == x:
index_remove = idx
break
self.dq_store.remove(index_remove)
self.dq_store.appendleft(x)
self.key_reference_map.add(x)
def display(self):
"""
Prints all the elements in the store.
"""
for k in self.dq_store:
print(k)
if __name__ == "__main__":
lru_cache = LRUCache(4)
lru_cache.refer(1)
lru_cache.refer(2)
lru_cache.refer(3)
lru_cache.refer(1)
lru_cache.refer(4)
lru_cache.refer(5)
lru_cache.display()
| 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 | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| beautifulsoup4
fake_useragent
keras<2.7.0
lxml
matplotlib
numpy
opencv-python
pandas
pillow
qiskit
requests
# scikit-fuzzy # Causing broken builds
sklearn
statsmodels
sympy
tensorflow
texttable
tweepy
types-requests
xgboost
| beautifulsoup4
fake_useragent
keras<2.7.0
lxml
matplotlib
numpy
opencv-python
pandas
pillow
qiskit
requests
# scikit-fuzzy # Causing broken builds
sklearn
statsmodels
sympy
tensorflow
texttable
tweepy
xgboost
| 1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| 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 | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
This is pure Python implementation of Tabu search algorithm for a Travelling Salesman
Problem, that the distances between the cities are symmetric (the distance between city
'a' and city 'b' is the same between city 'b' and city 'a').
The TSP can be represented into a graph. The cities are represented by nodes and the
distance between them is represented by the weight of the ark between the nodes.
The .txt file with the graph has the form:
node1 node2 distance_between_node1_and_node2
node1 node3 distance_between_node1_and_node3
...
Be careful node1, node2 and the distance between them, must exist only once. This means
in the .txt file should not exist:
node1 node2 distance_between_node1_and_node2
node2 node1 distance_between_node2_and_node1
For pytests run following command:
pytest
For manual testing run:
python tabu_search.py -f your_file_name.txt -number_of_iterations_of_tabu_search \
-s size_of_tabu_search
e.g. python tabu_search.py -f tabudata2.txt -i 4 -s 3
"""
import argparse
import copy
def generate_neighbours(path):
"""
Pure implementation of generating a dictionary of neighbors and the cost with each
neighbor, given a path file that includes a graph.
:param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt)
:return dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
Example of dict_of_neighbours:
>>) dict_of_neighbours[a]
[[b,20],[c,18],[d,22],[e,26]]
This indicates the neighbors of node (city) 'a', which has neighbor the node 'b'
with distance 20, the node 'c' with distance 18, the node 'd' with distance 22 and
the node 'e' with distance 26.
"""
dict_of_neighbours = {}
with open(path) as f:
for line in f:
if line.split()[0] not in dict_of_neighbours:
_list = list()
_list.append([line.split()[1], line.split()[2]])
dict_of_neighbours[line.split()[0]] = _list
else:
dict_of_neighbours[line.split()[0]].append(
[line.split()[1], line.split()[2]]
)
if line.split()[1] not in dict_of_neighbours:
_list = list()
_list.append([line.split()[0], line.split()[2]])
dict_of_neighbours[line.split()[1]] = _list
else:
dict_of_neighbours[line.split()[1]].append(
[line.split()[0], line.split()[2]]
)
return dict_of_neighbours
def generate_first_solution(path, dict_of_neighbours):
"""
Pure implementation of generating the first solution for the Tabu search to start,
with the redundant resolution strategy. That means that we start from the starting
node (e.g. node 'a'), then we go to the city nearest (lowest distance) to this node
(let's assume is node 'c'), then we go to the nearest city of the node 'c', etc.
till we have visited all cities and return to the starting node.
:param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt)
:param dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
:return first_solution: The solution for the first iteration of Tabu search using
the redundant resolution strategy in a list.
:return distance_of_first_solution: The total distance that Travelling Salesman
will travel, if he follows the path in first_solution.
"""
with open(path) as f:
start_node = f.read(1)
end_node = start_node
first_solution = []
visiting = start_node
distance_of_first_solution = 0
while visiting not in first_solution:
minim = 10000
for k in dict_of_neighbours[visiting]:
if int(k[1]) < int(minim) and k[0] not in first_solution:
minim = k[1]
best_node = k[0]
first_solution.append(visiting)
distance_of_first_solution = distance_of_first_solution + int(minim)
visiting = best_node
first_solution.append(end_node)
position = 0
for k in dict_of_neighbours[first_solution[-2]]:
if k[0] == start_node:
break
position += 1
distance_of_first_solution = (
distance_of_first_solution
+ int(dict_of_neighbours[first_solution[-2]][position][1])
- 10000
)
return first_solution, distance_of_first_solution
def find_neighborhood(solution, dict_of_neighbours):
"""
Pure implementation of generating the neighborhood (sorted by total distance of
each solution from lowest to highest) of a solution with 1-1 exchange method, that
means we exchange each node in a solution with each other node and generating a
number of solution named neighborhood.
:param solution: The solution in which we want to find the neighborhood.
:param dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
:return neighborhood_of_solution: A list that includes the solutions and the total
distance of each solution (in form of list) that are produced with 1-1 exchange
from the solution that the method took as an input
Example:
>>> find_neighborhood(['a', 'c', 'b', 'd', 'e', 'a'],
... {'a': [['b', '20'], ['c', '18'], ['d', '22'], ['e', '26']],
... 'c': [['a', '18'], ['b', '10'], ['d', '23'], ['e', '24']],
... 'b': [['a', '20'], ['c', '10'], ['d', '11'], ['e', '12']],
... 'e': [['a', '26'], ['b', '12'], ['c', '24'], ['d', '40']],
... 'd': [['a', '22'], ['b', '11'], ['c', '23'], ['e', '40']]}
... ) # doctest: +NORMALIZE_WHITESPACE
[['a', 'e', 'b', 'd', 'c', 'a', 90],
['a', 'c', 'd', 'b', 'e', 'a', 90],
['a', 'd', 'b', 'c', 'e', 'a', 93],
['a', 'c', 'b', 'e', 'd', 'a', 102],
['a', 'c', 'e', 'd', 'b', 'a', 113],
['a', 'b', 'c', 'd', 'e', 'a', 119]]
"""
neighborhood_of_solution = []
for n in solution[1:-1]:
idx1 = solution.index(n)
for kn in solution[1:-1]:
idx2 = solution.index(kn)
if n == kn:
continue
_tmp = copy.deepcopy(solution)
_tmp[idx1] = kn
_tmp[idx2] = n
distance = 0
for k in _tmp[:-1]:
next_node = _tmp[_tmp.index(k) + 1]
for i in dict_of_neighbours[k]:
if i[0] == next_node:
distance = distance + int(i[1])
_tmp.append(distance)
if _tmp not in neighborhood_of_solution:
neighborhood_of_solution.append(_tmp)
indexOfLastItemInTheList = len(neighborhood_of_solution[0]) - 1
neighborhood_of_solution.sort(key=lambda x: x[indexOfLastItemInTheList])
return neighborhood_of_solution
def tabu_search(
first_solution, distance_of_first_solution, dict_of_neighbours, iters, size
):
"""
Pure implementation of Tabu search algorithm for a Travelling Salesman Problem in
Python.
:param first_solution: The solution for the first iteration of Tabu search using
the redundant resolution strategy in a list.
:param distance_of_first_solution: The total distance that Travelling Salesman will
travel, if he follows the path in first_solution.
:param dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
:param iters: The number of iterations that Tabu search will execute.
:param size: The size of Tabu List.
:return best_solution_ever: The solution with the lowest distance that occurred
during the execution of Tabu search.
:return best_cost: The total distance that Travelling Salesman will travel, if he
follows the path in best_solution ever.
"""
count = 1
solution = first_solution
tabu_list = list()
best_cost = distance_of_first_solution
best_solution_ever = solution
while count <= iters:
neighborhood = find_neighborhood(solution, dict_of_neighbours)
index_of_best_solution = 0
best_solution = neighborhood[index_of_best_solution]
best_cost_index = len(best_solution) - 1
found = False
while not found:
i = 0
while i < len(best_solution):
if best_solution[i] != solution[i]:
first_exchange_node = best_solution[i]
second_exchange_node = solution[i]
break
i = i + 1
if [first_exchange_node, second_exchange_node] not in tabu_list and [
second_exchange_node,
first_exchange_node,
] not in tabu_list:
tabu_list.append([first_exchange_node, second_exchange_node])
found = True
solution = best_solution[:-1]
cost = neighborhood[index_of_best_solution][best_cost_index]
if cost < best_cost:
best_cost = cost
best_solution_ever = solution
else:
index_of_best_solution = index_of_best_solution + 1
best_solution = neighborhood[index_of_best_solution]
if len(tabu_list) >= size:
tabu_list.pop(0)
count = count + 1
return best_solution_ever, best_cost
def main(args=None):
dict_of_neighbours = generate_neighbours(args.File)
first_solution, distance_of_first_solution = generate_first_solution(
args.File, dict_of_neighbours
)
best_sol, best_cost = tabu_search(
first_solution,
distance_of_first_solution,
dict_of_neighbours,
args.Iterations,
args.Size,
)
print(f"Best solution: {best_sol}, with total distance: {best_cost}.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Tabu Search")
parser.add_argument(
"-f",
"--File",
type=str,
help="Path to the file containing the data",
required=True,
)
parser.add_argument(
"-i",
"--Iterations",
type=int,
help="How many iterations the algorithm should perform",
required=True,
)
parser.add_argument(
"-s", "--Size", type=int, help="Size of the tabu list", required=True
)
# Pass the arguments to main method
main(parser.parse_args())
| """
This is pure Python implementation of Tabu search algorithm for a Travelling Salesman
Problem, that the distances between the cities are symmetric (the distance between city
'a' and city 'b' is the same between city 'b' and city 'a').
The TSP can be represented into a graph. The cities are represented by nodes and the
distance between them is represented by the weight of the ark between the nodes.
The .txt file with the graph has the form:
node1 node2 distance_between_node1_and_node2
node1 node3 distance_between_node1_and_node3
...
Be careful node1, node2 and the distance between them, must exist only once. This means
in the .txt file should not exist:
node1 node2 distance_between_node1_and_node2
node2 node1 distance_between_node2_and_node1
For pytests run following command:
pytest
For manual testing run:
python tabu_search.py -f your_file_name.txt -number_of_iterations_of_tabu_search \
-s size_of_tabu_search
e.g. python tabu_search.py -f tabudata2.txt -i 4 -s 3
"""
import argparse
import copy
def generate_neighbours(path):
"""
Pure implementation of generating a dictionary of neighbors and the cost with each
neighbor, given a path file that includes a graph.
:param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt)
:return dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
Example of dict_of_neighbours:
>>) dict_of_neighbours[a]
[[b,20],[c,18],[d,22],[e,26]]
This indicates the neighbors of node (city) 'a', which has neighbor the node 'b'
with distance 20, the node 'c' with distance 18, the node 'd' with distance 22 and
the node 'e' with distance 26.
"""
dict_of_neighbours = {}
with open(path) as f:
for line in f:
if line.split()[0] not in dict_of_neighbours:
_list = list()
_list.append([line.split()[1], line.split()[2]])
dict_of_neighbours[line.split()[0]] = _list
else:
dict_of_neighbours[line.split()[0]].append(
[line.split()[1], line.split()[2]]
)
if line.split()[1] not in dict_of_neighbours:
_list = list()
_list.append([line.split()[0], line.split()[2]])
dict_of_neighbours[line.split()[1]] = _list
else:
dict_of_neighbours[line.split()[1]].append(
[line.split()[0], line.split()[2]]
)
return dict_of_neighbours
def generate_first_solution(path, dict_of_neighbours):
"""
Pure implementation of generating the first solution for the Tabu search to start,
with the redundant resolution strategy. That means that we start from the starting
node (e.g. node 'a'), then we go to the city nearest (lowest distance) to this node
(let's assume is node 'c'), then we go to the nearest city of the node 'c', etc.
till we have visited all cities and return to the starting node.
:param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt)
:param dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
:return first_solution: The solution for the first iteration of Tabu search using
the redundant resolution strategy in a list.
:return distance_of_first_solution: The total distance that Travelling Salesman
will travel, if he follows the path in first_solution.
"""
with open(path) as f:
start_node = f.read(1)
end_node = start_node
first_solution = []
visiting = start_node
distance_of_first_solution = 0
while visiting not in first_solution:
minim = 10000
for k in dict_of_neighbours[visiting]:
if int(k[1]) < int(minim) and k[0] not in first_solution:
minim = k[1]
best_node = k[0]
first_solution.append(visiting)
distance_of_first_solution = distance_of_first_solution + int(minim)
visiting = best_node
first_solution.append(end_node)
position = 0
for k in dict_of_neighbours[first_solution[-2]]:
if k[0] == start_node:
break
position += 1
distance_of_first_solution = (
distance_of_first_solution
+ int(dict_of_neighbours[first_solution[-2]][position][1])
- 10000
)
return first_solution, distance_of_first_solution
def find_neighborhood(solution, dict_of_neighbours):
"""
Pure implementation of generating the neighborhood (sorted by total distance of
each solution from lowest to highest) of a solution with 1-1 exchange method, that
means we exchange each node in a solution with each other node and generating a
number of solution named neighborhood.
:param solution: The solution in which we want to find the neighborhood.
:param dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
:return neighborhood_of_solution: A list that includes the solutions and the total
distance of each solution (in form of list) that are produced with 1-1 exchange
from the solution that the method took as an input
Example:
>>> find_neighborhood(['a', 'c', 'b', 'd', 'e', 'a'],
... {'a': [['b', '20'], ['c', '18'], ['d', '22'], ['e', '26']],
... 'c': [['a', '18'], ['b', '10'], ['d', '23'], ['e', '24']],
... 'b': [['a', '20'], ['c', '10'], ['d', '11'], ['e', '12']],
... 'e': [['a', '26'], ['b', '12'], ['c', '24'], ['d', '40']],
... 'd': [['a', '22'], ['b', '11'], ['c', '23'], ['e', '40']]}
... ) # doctest: +NORMALIZE_WHITESPACE
[['a', 'e', 'b', 'd', 'c', 'a', 90],
['a', 'c', 'd', 'b', 'e', 'a', 90],
['a', 'd', 'b', 'c', 'e', 'a', 93],
['a', 'c', 'b', 'e', 'd', 'a', 102],
['a', 'c', 'e', 'd', 'b', 'a', 113],
['a', 'b', 'c', 'd', 'e', 'a', 119]]
"""
neighborhood_of_solution = []
for n in solution[1:-1]:
idx1 = solution.index(n)
for kn in solution[1:-1]:
idx2 = solution.index(kn)
if n == kn:
continue
_tmp = copy.deepcopy(solution)
_tmp[idx1] = kn
_tmp[idx2] = n
distance = 0
for k in _tmp[:-1]:
next_node = _tmp[_tmp.index(k) + 1]
for i in dict_of_neighbours[k]:
if i[0] == next_node:
distance = distance + int(i[1])
_tmp.append(distance)
if _tmp not in neighborhood_of_solution:
neighborhood_of_solution.append(_tmp)
indexOfLastItemInTheList = len(neighborhood_of_solution[0]) - 1
neighborhood_of_solution.sort(key=lambda x: x[indexOfLastItemInTheList])
return neighborhood_of_solution
def tabu_search(
first_solution, distance_of_first_solution, dict_of_neighbours, iters, size
):
"""
Pure implementation of Tabu search algorithm for a Travelling Salesman Problem in
Python.
:param first_solution: The solution for the first iteration of Tabu search using
the redundant resolution strategy in a list.
:param distance_of_first_solution: The total distance that Travelling Salesman will
travel, if he follows the path in first_solution.
:param dict_of_neighbours: Dictionary with key each node and value a list of lists
with the neighbors of the node and the cost (distance) for each neighbor.
:param iters: The number of iterations that Tabu search will execute.
:param size: The size of Tabu List.
:return best_solution_ever: The solution with the lowest distance that occurred
during the execution of Tabu search.
:return best_cost: The total distance that Travelling Salesman will travel, if he
follows the path in best_solution ever.
"""
count = 1
solution = first_solution
tabu_list = list()
best_cost = distance_of_first_solution
best_solution_ever = solution
while count <= iters:
neighborhood = find_neighborhood(solution, dict_of_neighbours)
index_of_best_solution = 0
best_solution = neighborhood[index_of_best_solution]
best_cost_index = len(best_solution) - 1
found = False
while not found:
i = 0
while i < len(best_solution):
if best_solution[i] != solution[i]:
first_exchange_node = best_solution[i]
second_exchange_node = solution[i]
break
i = i + 1
if [first_exchange_node, second_exchange_node] not in tabu_list and [
second_exchange_node,
first_exchange_node,
] not in tabu_list:
tabu_list.append([first_exchange_node, second_exchange_node])
found = True
solution = best_solution[:-1]
cost = neighborhood[index_of_best_solution][best_cost_index]
if cost < best_cost:
best_cost = cost
best_solution_ever = solution
else:
index_of_best_solution = index_of_best_solution + 1
best_solution = neighborhood[index_of_best_solution]
if len(tabu_list) >= size:
tabu_list.pop(0)
count = count + 1
return best_solution_ever, best_cost
def main(args=None):
dict_of_neighbours = generate_neighbours(args.File)
first_solution, distance_of_first_solution = generate_first_solution(
args.File, dict_of_neighbours
)
best_sol, best_cost = tabu_search(
first_solution,
distance_of_first_solution,
dict_of_neighbours,
args.Iterations,
args.Size,
)
print(f"Best solution: {best_sol}, with total distance: {best_cost}.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Tabu Search")
parser.add_argument(
"-f",
"--File",
type=str,
help="Path to the file containing the data",
required=True,
)
parser.add_argument(
"-i",
"--Iterations",
type=int,
help="How many iterations the algorithm should perform",
required=True,
)
parser.add_argument(
"-s", "--Size", type=int, help="Size of the tabu list", required=True
)
# Pass the arguments to main method
main(parser.parse_args())
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Linked Lists consists of Nodes.
Nodes contain data and also may link to other nodes:
- Head Node: First node, the address of the
head node gives us access of the complete list
- Last node: points to null
"""
from typing import Any, Optional
class Node:
def __init__(self, item: Any, next: Any) -> None:
self.item = item
self.next = next
class LinkedList:
def __init__(self) -> None:
self.head: Optional[Node] = None
self.size = 0
def add(self, item: Any) -> None:
self.head = Node(item, self.head)
self.size += 1
def remove(self) -> Any:
# Switched 'self.is_empty()' to 'self.head is None'
# because mypy was considering the possibility that 'self.head'
# can be None in below else part and giving error
if self.head is None:
return None
else:
item = self.head.item
self.head = self.head.next
self.size -= 1
return item
def is_empty(self) -> bool:
return self.head is None
def __str__(self) -> str:
"""
>>> linked_list = LinkedList()
>>> linked_list.add(23)
>>> linked_list.add(14)
>>> linked_list.add(9)
>>> print(linked_list)
9 --> 14 --> 23
"""
if not self.is_empty:
return ""
else:
iterate = self.head
item_str = ""
item_list: list[str] = []
while iterate:
item_list.append(str(iterate.item))
iterate = iterate.next
item_str = " --> ".join(item_list)
return item_str
def __len__(self) -> int:
"""
>>> linked_list = LinkedList()
>>> len(linked_list)
0
>>> linked_list.add("a")
>>> len(linked_list)
1
>>> linked_list.add("b")
>>> len(linked_list)
2
>>> _ = linked_list.remove()
>>> len(linked_list)
1
>>> _ = linked_list.remove()
>>> len(linked_list)
0
"""
return self.size
| """
Linked Lists consists of Nodes.
Nodes contain data and also may link to other nodes:
- Head Node: First node, the address of the
head node gives us access of the complete list
- Last node: points to null
"""
from typing import Any, Optional
class Node:
def __init__(self, item: Any, next: Any) -> None:
self.item = item
self.next = next
class LinkedList:
def __init__(self) -> None:
self.head: Optional[Node] = None
self.size = 0
def add(self, item: Any) -> None:
self.head = Node(item, self.head)
self.size += 1
def remove(self) -> Any:
# Switched 'self.is_empty()' to 'self.head is None'
# because mypy was considering the possibility that 'self.head'
# can be None in below else part and giving error
if self.head is None:
return None
else:
item = self.head.item
self.head = self.head.next
self.size -= 1
return item
def is_empty(self) -> bool:
return self.head is None
def __str__(self) -> str:
"""
>>> linked_list = LinkedList()
>>> linked_list.add(23)
>>> linked_list.add(14)
>>> linked_list.add(9)
>>> print(linked_list)
9 --> 14 --> 23
"""
if not self.is_empty:
return ""
else:
iterate = self.head
item_str = ""
item_list: list[str] = []
while iterate:
item_list.append(str(iterate.item))
iterate = iterate.next
item_str = " --> ".join(item_list)
return item_str
def __len__(self) -> int:
"""
>>> linked_list = LinkedList()
>>> len(linked_list)
0
>>> linked_list.add("a")
>>> len(linked_list)
1
>>> linked_list.add("b")
>>> len(linked_list)
2
>>> _ = linked_list.remove()
>>> len(linked_list)
1
>>> _ = linked_list.remove()
>>> len(linked_list)
0
"""
return self.size
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Prim's (also known as Jarník's) algorithm is a greedy algorithm that finds a minimum
spanning tree for a weighted undirected graph. This means it finds a subset of the
edges that forms a tree that includes every vertex, where the total weight of all the
edges in the tree is minimized. The algorithm operates by building this tree one vertex
at a time, from an arbitrary starting vertex, at each step adding the cheapest possible
connection from the tree to another vertex.
"""
from __future__ import annotations
from sys import maxsize
from typing import Generic, TypeVar
T = TypeVar("T")
def get_parent_position(position: int) -> int:
"""
heap helper function get the position of the parent of the current node
>>> get_parent_position(1)
0
>>> get_parent_position(2)
0
"""
return (position - 1) // 2
def get_child_left_position(position: int) -> int:
"""
heap helper function get the position of the left child of the current node
>>> get_child_left_position(0)
1
"""
return (2 * position) + 1
def get_child_right_position(position: int) -> int:
"""
heap helper function get the position of the right child of the current node
>>> get_child_right_position(0)
2
"""
return (2 * position) + 2
class MinPriorityQueue(Generic[T]):
"""
Minimum Priority Queue Class
Functions:
is_empty: function to check if the priority queue is empty
push: function to add an element with given priority to the queue
extract_min: function to remove and return the element with lowest weight (highest
priority)
update_key: function to update the weight of the given key
_bubble_up: helper function to place a node at the proper position (upward
movement)
_bubble_down: helper function to place a node at the proper position (downward
movement)
_swap_nodes: helper function to swap the nodes at the given positions
>>> queue = MinPriorityQueue()
>>> queue.push(1, 1000)
>>> queue.push(2, 100)
>>> queue.push(3, 4000)
>>> queue.push(4, 3000)
>>> print(queue.extract_min())
2
>>> queue.update_key(4, 50)
>>> print(queue.extract_min())
4
>>> print(queue.extract_min())
1
>>> print(queue.extract_min())
3
"""
def __init__(self) -> None:
self.heap: list[tuple[T, int]] = []
self.position_map: dict[T, int] = {}
self.elements: int = 0
def __len__(self) -> int:
return self.elements
def __repr__(self) -> str:
return str(self.heap)
def is_empty(self) -> bool:
# Check if the priority queue is empty
return self.elements == 0
def push(self, elem: T, weight: int) -> None:
# Add an element with given priority to the queue
self.heap.append((elem, weight))
self.position_map[elem] = self.elements
self.elements += 1
self._bubble_up(elem)
def extract_min(self) -> T:
# Remove and return the element with lowest weight (highest priority)
if self.elements > 1:
self._swap_nodes(0, self.elements - 1)
elem, _ = self.heap.pop()
del self.position_map[elem]
self.elements -= 1
if self.elements > 0:
bubble_down_elem, _ = self.heap[0]
self._bubble_down(bubble_down_elem)
return elem
def update_key(self, elem: T, weight: int) -> None:
# Update the weight of the given key
position = self.position_map[elem]
self.heap[position] = (elem, weight)
if position > 0:
parent_position = get_parent_position(position)
_, parent_weight = self.heap[parent_position]
if parent_weight > weight:
self._bubble_up(elem)
else:
self._bubble_down(elem)
else:
self._bubble_down(elem)
def _bubble_up(self, elem: T) -> None:
# Place a node at the proper position (upward movement) [to be used internally
# only]
curr_pos = self.position_map[elem]
if curr_pos == 0:
return
parent_position = get_parent_position(curr_pos)
_, weight = self.heap[curr_pos]
_, parent_weight = self.heap[parent_position]
if parent_weight > weight:
self._swap_nodes(parent_position, curr_pos)
return self._bubble_up(elem)
return
def _bubble_down(self, elem: T) -> None:
# Place a node at the proper position (downward movement) [to be used
# internally only]
curr_pos = self.position_map[elem]
_, weight = self.heap[curr_pos]
child_left_position = get_child_left_position(curr_pos)
child_right_position = get_child_right_position(curr_pos)
if child_left_position < self.elements and child_right_position < self.elements:
_, child_left_weight = self.heap[child_left_position]
_, child_right_weight = self.heap[child_right_position]
if child_right_weight < child_left_weight:
if child_right_weight < weight:
self._swap_nodes(child_right_position, curr_pos)
return self._bubble_down(elem)
if child_left_position < self.elements:
_, child_left_weight = self.heap[child_left_position]
if child_left_weight < weight:
self._swap_nodes(child_left_position, curr_pos)
return self._bubble_down(elem)
else:
return
if child_right_position < self.elements:
_, child_right_weight = self.heap[child_right_position]
if child_right_weight < weight:
self._swap_nodes(child_right_position, curr_pos)
return self._bubble_down(elem)
else:
return
def _swap_nodes(self, node1_pos: int, node2_pos: int) -> None:
# Swap the nodes at the given positions
node1_elem = self.heap[node1_pos][0]
node2_elem = self.heap[node2_pos][0]
self.heap[node1_pos], self.heap[node2_pos] = (
self.heap[node2_pos],
self.heap[node1_pos],
)
self.position_map[node1_elem] = node2_pos
self.position_map[node2_elem] = node1_pos
class GraphUndirectedWeighted(Generic[T]):
"""
Graph Undirected Weighted Class
Functions:
add_node: function to add a node in the graph
add_edge: function to add an edge between 2 nodes in the graph
"""
def __init__(self) -> None:
self.connections: dict[T, dict[T, int]] = {}
self.nodes: int = 0
def __repr__(self) -> str:
return str(self.connections)
def __len__(self) -> int:
return self.nodes
def add_node(self, node: T) -> None:
# Add a node in the graph if it is not in the graph
if node not in self.connections:
self.connections[node] = {}
self.nodes += 1
def add_edge(self, node1: T, node2: T, weight: int) -> None:
# Add an edge between 2 nodes in the graph
self.add_node(node1)
self.add_node(node2)
self.connections[node1][node2] = weight
self.connections[node2][node1] = weight
def prims_algo(
graph: GraphUndirectedWeighted[T],
) -> tuple[dict[T, int], dict[T, T | None]]:
"""
>>> graph = GraphUndirectedWeighted()
>>> graph.add_edge("a", "b", 3)
>>> graph.add_edge("b", "c", 10)
>>> graph.add_edge("c", "d", 5)
>>> graph.add_edge("a", "c", 15)
>>> graph.add_edge("b", "d", 100)
>>> dist, parent = prims_algo(graph)
>>> abs(dist["a"] - dist["b"])
3
>>> abs(dist["d"] - dist["b"])
15
>>> abs(dist["a"] - dist["c"])
13
"""
# prim's algorithm for minimum spanning tree
dist: dict[T, int] = {node: maxsize for node in graph.connections}
parent: dict[T, T | None] = {node: None for node in graph.connections}
priority_queue: MinPriorityQueue[T] = MinPriorityQueue()
for node, weight in dist.items():
priority_queue.push(node, weight)
if priority_queue.is_empty():
return dist, parent
# initialization
node = priority_queue.extract_min()
dist[node] = 0
for neighbour in graph.connections[node]:
if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
dist[neighbour] = dist[node] + graph.connections[node][neighbour]
priority_queue.update_key(neighbour, dist[neighbour])
parent[neighbour] = node
# running prim's algorithm
while not priority_queue.is_empty():
node = priority_queue.extract_min()
for neighbour in graph.connections[node]:
if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
dist[neighbour] = dist[node] + graph.connections[node][neighbour]
priority_queue.update_key(neighbour, dist[neighbour])
parent[neighbour] = node
return dist, parent
| """
Prim's (also known as Jarník's) algorithm is a greedy algorithm that finds a minimum
spanning tree for a weighted undirected graph. This means it finds a subset of the
edges that forms a tree that includes every vertex, where the total weight of all the
edges in the tree is minimized. The algorithm operates by building this tree one vertex
at a time, from an arbitrary starting vertex, at each step adding the cheapest possible
connection from the tree to another vertex.
"""
from __future__ import annotations
from sys import maxsize
from typing import Generic, TypeVar
T = TypeVar("T")
def get_parent_position(position: int) -> int:
"""
heap helper function get the position of the parent of the current node
>>> get_parent_position(1)
0
>>> get_parent_position(2)
0
"""
return (position - 1) // 2
def get_child_left_position(position: int) -> int:
"""
heap helper function get the position of the left child of the current node
>>> get_child_left_position(0)
1
"""
return (2 * position) + 1
def get_child_right_position(position: int) -> int:
"""
heap helper function get the position of the right child of the current node
>>> get_child_right_position(0)
2
"""
return (2 * position) + 2
class MinPriorityQueue(Generic[T]):
"""
Minimum Priority Queue Class
Functions:
is_empty: function to check if the priority queue is empty
push: function to add an element with given priority to the queue
extract_min: function to remove and return the element with lowest weight (highest
priority)
update_key: function to update the weight of the given key
_bubble_up: helper function to place a node at the proper position (upward
movement)
_bubble_down: helper function to place a node at the proper position (downward
movement)
_swap_nodes: helper function to swap the nodes at the given positions
>>> queue = MinPriorityQueue()
>>> queue.push(1, 1000)
>>> queue.push(2, 100)
>>> queue.push(3, 4000)
>>> queue.push(4, 3000)
>>> print(queue.extract_min())
2
>>> queue.update_key(4, 50)
>>> print(queue.extract_min())
4
>>> print(queue.extract_min())
1
>>> print(queue.extract_min())
3
"""
def __init__(self) -> None:
self.heap: list[tuple[T, int]] = []
self.position_map: dict[T, int] = {}
self.elements: int = 0
def __len__(self) -> int:
return self.elements
def __repr__(self) -> str:
return str(self.heap)
def is_empty(self) -> bool:
# Check if the priority queue is empty
return self.elements == 0
def push(self, elem: T, weight: int) -> None:
# Add an element with given priority to the queue
self.heap.append((elem, weight))
self.position_map[elem] = self.elements
self.elements += 1
self._bubble_up(elem)
def extract_min(self) -> T:
# Remove and return the element with lowest weight (highest priority)
if self.elements > 1:
self._swap_nodes(0, self.elements - 1)
elem, _ = self.heap.pop()
del self.position_map[elem]
self.elements -= 1
if self.elements > 0:
bubble_down_elem, _ = self.heap[0]
self._bubble_down(bubble_down_elem)
return elem
def update_key(self, elem: T, weight: int) -> None:
# Update the weight of the given key
position = self.position_map[elem]
self.heap[position] = (elem, weight)
if position > 0:
parent_position = get_parent_position(position)
_, parent_weight = self.heap[parent_position]
if parent_weight > weight:
self._bubble_up(elem)
else:
self._bubble_down(elem)
else:
self._bubble_down(elem)
def _bubble_up(self, elem: T) -> None:
# Place a node at the proper position (upward movement) [to be used internally
# only]
curr_pos = self.position_map[elem]
if curr_pos == 0:
return
parent_position = get_parent_position(curr_pos)
_, weight = self.heap[curr_pos]
_, parent_weight = self.heap[parent_position]
if parent_weight > weight:
self._swap_nodes(parent_position, curr_pos)
return self._bubble_up(elem)
return
def _bubble_down(self, elem: T) -> None:
# Place a node at the proper position (downward movement) [to be used
# internally only]
curr_pos = self.position_map[elem]
_, weight = self.heap[curr_pos]
child_left_position = get_child_left_position(curr_pos)
child_right_position = get_child_right_position(curr_pos)
if child_left_position < self.elements and child_right_position < self.elements:
_, child_left_weight = self.heap[child_left_position]
_, child_right_weight = self.heap[child_right_position]
if child_right_weight < child_left_weight:
if child_right_weight < weight:
self._swap_nodes(child_right_position, curr_pos)
return self._bubble_down(elem)
if child_left_position < self.elements:
_, child_left_weight = self.heap[child_left_position]
if child_left_weight < weight:
self._swap_nodes(child_left_position, curr_pos)
return self._bubble_down(elem)
else:
return
if child_right_position < self.elements:
_, child_right_weight = self.heap[child_right_position]
if child_right_weight < weight:
self._swap_nodes(child_right_position, curr_pos)
return self._bubble_down(elem)
else:
return
def _swap_nodes(self, node1_pos: int, node2_pos: int) -> None:
# Swap the nodes at the given positions
node1_elem = self.heap[node1_pos][0]
node2_elem = self.heap[node2_pos][0]
self.heap[node1_pos], self.heap[node2_pos] = (
self.heap[node2_pos],
self.heap[node1_pos],
)
self.position_map[node1_elem] = node2_pos
self.position_map[node2_elem] = node1_pos
class GraphUndirectedWeighted(Generic[T]):
"""
Graph Undirected Weighted Class
Functions:
add_node: function to add a node in the graph
add_edge: function to add an edge between 2 nodes in the graph
"""
def __init__(self) -> None:
self.connections: dict[T, dict[T, int]] = {}
self.nodes: int = 0
def __repr__(self) -> str:
return str(self.connections)
def __len__(self) -> int:
return self.nodes
def add_node(self, node: T) -> None:
# Add a node in the graph if it is not in the graph
if node not in self.connections:
self.connections[node] = {}
self.nodes += 1
def add_edge(self, node1: T, node2: T, weight: int) -> None:
# Add an edge between 2 nodes in the graph
self.add_node(node1)
self.add_node(node2)
self.connections[node1][node2] = weight
self.connections[node2][node1] = weight
def prims_algo(
graph: GraphUndirectedWeighted[T],
) -> tuple[dict[T, int], dict[T, T | None]]:
"""
>>> graph = GraphUndirectedWeighted()
>>> graph.add_edge("a", "b", 3)
>>> graph.add_edge("b", "c", 10)
>>> graph.add_edge("c", "d", 5)
>>> graph.add_edge("a", "c", 15)
>>> graph.add_edge("b", "d", 100)
>>> dist, parent = prims_algo(graph)
>>> abs(dist["a"] - dist["b"])
3
>>> abs(dist["d"] - dist["b"])
15
>>> abs(dist["a"] - dist["c"])
13
"""
# prim's algorithm for minimum spanning tree
dist: dict[T, int] = {node: maxsize for node in graph.connections}
parent: dict[T, T | None] = {node: None for node in graph.connections}
priority_queue: MinPriorityQueue[T] = MinPriorityQueue()
for node, weight in dist.items():
priority_queue.push(node, weight)
if priority_queue.is_empty():
return dist, parent
# initialization
node = priority_queue.extract_min()
dist[node] = 0
for neighbour in graph.connections[node]:
if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
dist[neighbour] = dist[node] + graph.connections[node][neighbour]
priority_queue.update_key(neighbour, dist[neighbour])
parent[neighbour] = node
# running prim's algorithm
while not priority_queue.is_empty():
node = priority_queue.extract_min()
for neighbour in graph.connections[node]:
if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
dist[neighbour] = dist[node] + graph.connections[node][neighbour]
priority_queue.update_key(neighbour, dist[neighbour])
parent[neighbour] = node
return dist, parent
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Author : Syed Faizan ( 3rd Year IIIT Pune )
Github : faizan2700
Purpose : You have one function f(x) which takes float integer and returns
float you have to integrate the function in limits a to b.
The approximation proposed by Thomas Simpsons in 1743 is one way to calculate
integration.
( read article : https://cp-algorithms.com/num_methods/simpson-integration.html )
simpson_integration() takes function,lower_limit=a,upper_limit=b,precision and
returns the integration of function in given limit.
"""
# constants
# the more the number of steps the more accurate
N_STEPS = 1000
def f(x: float) -> float:
return x * x
"""
Summary of Simpson Approximation :
By simpsons integration :
1. integration of fxdx with limit a to b is =
f(x0) + 4 * f(x1) + 2 * f(x2) + 4 * f(x3) + 2 * f(x4)..... + f(xn)
where x0 = a
xi = a + i * h
xn = b
"""
def simpson_integration(function, a: float, b: float, precision: int = 4) -> float:
"""
Args:
function : the function which's integration is desired
a : the lower limit of integration
b : upper limit of integraion
precision : precision of the result,error required default is 4
Returns:
result : the value of the approximated integration of function in range a to b
Raises:
AssertionError: function is not callable
AssertionError: a is not float or integer
AssertionError: function should return float or integer
AssertionError: b is not float or integer
AssertionError: precision is not positive integer
>>> simpson_integration(lambda x : x*x,1,2,3)
2.333
>>> simpson_integration(lambda x : x*x,'wrong_input',2,3)
Traceback (most recent call last):
...
AssertionError: a should be float or integer your input : wrong_input
>>> simpson_integration(lambda x : x*x,1,'wrong_input',3)
Traceback (most recent call last):
...
AssertionError: b should be float or integer your input : wrong_input
>>> simpson_integration(lambda x : x*x,1,2,'wrong_input')
Traceback (most recent call last):
...
AssertionError: precision should be positive integer your input : wrong_input
>>> simpson_integration('wrong_input',2,3,4)
Traceback (most recent call last):
...
AssertionError: the function(object) passed should be callable your input : ...
>>> simpson_integration(lambda x : x*x,3.45,3.2,1)
-2.8
>>> simpson_integration(lambda x : x*x,3.45,3.2,0)
Traceback (most recent call last):
...
AssertionError: precision should be positive integer your input : 0
>>> simpson_integration(lambda x : x*x,3.45,3.2,-1)
Traceback (most recent call last):
...
AssertionError: precision should be positive integer your input : -1
"""
assert callable(
function
), f"the function(object) passed should be callable your input : {function}"
assert isinstance(a, float) or isinstance(
a, int
), f"a should be float or integer your input : {a}"
assert isinstance(function(a), float) or isinstance(function(a), int), (
"the function should return integer or float return type of your function, "
f"{type(a)}"
)
assert isinstance(b, float) or isinstance(
b, int
), f"b should be float or integer your input : {b}"
assert (
isinstance(precision, int) and precision > 0
), f"precision should be positive integer your input : {precision}"
# just applying the formula of simpson for approximate integraion written in
# mentioned article in first comment of this file and above this function
h = (b - a) / N_STEPS
result = function(a) + function(b)
for i in range(1, N_STEPS):
a1 = a + h * i
result += function(a1) * (4 if i % 2 else 2)
result *= h / 3
return round(result, precision)
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Author : Syed Faizan ( 3rd Year IIIT Pune )
Github : faizan2700
Purpose : You have one function f(x) which takes float integer and returns
float you have to integrate the function in limits a to b.
The approximation proposed by Thomas Simpsons in 1743 is one way to calculate
integration.
( read article : https://cp-algorithms.com/num_methods/simpson-integration.html )
simpson_integration() takes function,lower_limit=a,upper_limit=b,precision and
returns the integration of function in given limit.
"""
# constants
# the more the number of steps the more accurate
N_STEPS = 1000
def f(x: float) -> float:
return x * x
"""
Summary of Simpson Approximation :
By simpsons integration :
1. integration of fxdx with limit a to b is =
f(x0) + 4 * f(x1) + 2 * f(x2) + 4 * f(x3) + 2 * f(x4)..... + f(xn)
where x0 = a
xi = a + i * h
xn = b
"""
def simpson_integration(function, a: float, b: float, precision: int = 4) -> float:
"""
Args:
function : the function which's integration is desired
a : the lower limit of integration
b : upper limit of integraion
precision : precision of the result,error required default is 4
Returns:
result : the value of the approximated integration of function in range a to b
Raises:
AssertionError: function is not callable
AssertionError: a is not float or integer
AssertionError: function should return float or integer
AssertionError: b is not float or integer
AssertionError: precision is not positive integer
>>> simpson_integration(lambda x : x*x,1,2,3)
2.333
>>> simpson_integration(lambda x : x*x,'wrong_input',2,3)
Traceback (most recent call last):
...
AssertionError: a should be float or integer your input : wrong_input
>>> simpson_integration(lambda x : x*x,1,'wrong_input',3)
Traceback (most recent call last):
...
AssertionError: b should be float or integer your input : wrong_input
>>> simpson_integration(lambda x : x*x,1,2,'wrong_input')
Traceback (most recent call last):
...
AssertionError: precision should be positive integer your input : wrong_input
>>> simpson_integration('wrong_input',2,3,4)
Traceback (most recent call last):
...
AssertionError: the function(object) passed should be callable your input : ...
>>> simpson_integration(lambda x : x*x,3.45,3.2,1)
-2.8
>>> simpson_integration(lambda x : x*x,3.45,3.2,0)
Traceback (most recent call last):
...
AssertionError: precision should be positive integer your input : 0
>>> simpson_integration(lambda x : x*x,3.45,3.2,-1)
Traceback (most recent call last):
...
AssertionError: precision should be positive integer your input : -1
"""
assert callable(
function
), f"the function(object) passed should be callable your input : {function}"
assert isinstance(a, float) or isinstance(
a, int
), f"a should be float or integer your input : {a}"
assert isinstance(function(a), float) or isinstance(function(a), int), (
"the function should return integer or float return type of your function, "
f"{type(a)}"
)
assert isinstance(b, float) or isinstance(
b, int
), f"b should be float or integer your input : {b}"
assert (
isinstance(precision, int) and precision > 0
), f"precision should be positive integer your input : {precision}"
# just applying the formula of simpson for approximate integraion written in
# mentioned article in first comment of this file and above this function
h = (b - a) / N_STEPS
result = function(a) + function(b)
for i in range(1, N_STEPS):
a1 = a + h * i
result += function(a1) * (4 if i % 2 else 2)
result *= h / 3
return round(result, precision)
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #
| #
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
https://en.wikipedia.org/wiki/Component_(graph_theory)
Finding connected components in graph
"""
test_graph_1 = {0: [1, 2], 1: [0, 3], 2: [0], 3: [1], 4: [5, 6], 5: [4, 6], 6: [4, 5]}
test_graph_2 = {0: [1, 2, 3], 1: [0, 3], 2: [0], 3: [0, 1], 4: [], 5: []}
def dfs(graph: dict, vert: int, visited: list) -> list:
"""
Use depth first search to find all vertices
being in the same component as initial vertex
>>> dfs(test_graph_1, 0, 5 * [False])
[0, 1, 3, 2]
>>> dfs(test_graph_2, 0, 6 * [False])
[0, 1, 3, 2]
"""
visited[vert] = True
connected_verts = []
for neighbour in graph[vert]:
if not visited[neighbour]:
connected_verts += dfs(graph, neighbour, visited)
return [vert] + connected_verts
def connected_components(graph: dict) -> list:
"""
This function takes graph as a parameter
and then returns the list of connected components
>>> connected_components(test_graph_1)
[[0, 1, 3, 2], [4, 5, 6]]
>>> connected_components(test_graph_2)
[[0, 1, 3, 2], [4], [5]]
"""
graph_size = len(graph)
visited = graph_size * [False]
components_list = []
for i in range(graph_size):
if not visited[i]:
i_connected = dfs(graph, i, visited)
components_list.append(i_connected)
return components_list
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
https://en.wikipedia.org/wiki/Component_(graph_theory)
Finding connected components in graph
"""
test_graph_1 = {0: [1, 2], 1: [0, 3], 2: [0], 3: [1], 4: [5, 6], 5: [4, 6], 6: [4, 5]}
test_graph_2 = {0: [1, 2, 3], 1: [0, 3], 2: [0], 3: [0, 1], 4: [], 5: []}
def dfs(graph: dict, vert: int, visited: list) -> list:
"""
Use depth first search to find all vertices
being in the same component as initial vertex
>>> dfs(test_graph_1, 0, 5 * [False])
[0, 1, 3, 2]
>>> dfs(test_graph_2, 0, 6 * [False])
[0, 1, 3, 2]
"""
visited[vert] = True
connected_verts = []
for neighbour in graph[vert]:
if not visited[neighbour]:
connected_verts += dfs(graph, neighbour, visited)
return [vert] + connected_verts
def connected_components(graph: dict) -> list:
"""
This function takes graph as a parameter
and then returns the list of connected components
>>> connected_components(test_graph_1)
[[0, 1, 3, 2], [4, 5, 6]]
>>> connected_components(test_graph_2)
[[0, 1, 3, 2], [4], [5]]
"""
graph_size = len(graph)
visited = graph_size * [False]
components_list = []
for i in range(graph_size):
if not visited[i]:
i_connected = dfs(graph, i, visited)
components_list.append(i_connected)
return components_list
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
author: Christian Bender
date: 21.12.2017
class: XORCipher
This class implements the XOR-cipher algorithm and provides
some useful methods for encrypting and decrypting strings and
files.
Overview about methods
- encrypt : list of char
- decrypt : list of char
- encrypt_string : str
- decrypt_string : str
- encrypt_file : boolean
- decrypt_file : boolean
"""
from __future__ import annotations
class XORCipher:
def __init__(self, key: int = 0):
"""
simple constructor that receives a key or uses
default key = 0
"""
# private field
self.__key = key
def encrypt(self, content: str, key: int) -> list[str]:
"""
input: 'content' of type string and 'key' of type int
output: encrypted string 'content' as a list of chars
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert isinstance(key, int) and isinstance(content, str)
key = key or self.__key or 1
# make sure key is an appropriate size
key %= 255
return [chr(ord(ch) ^ key) for ch in content]
def decrypt(self, content: str, key: int) -> list[str]:
"""
input: 'content' of type list and 'key' of type int
output: decrypted string 'content' as a list of chars
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert isinstance(key, int) and isinstance(content, list)
key = key or self.__key or 1
# make sure key is an appropriate size
key %= 255
return [chr(ord(ch) ^ key) for ch in content]
def encrypt_string(self, content: str, key: int = 0) -> str:
"""
input: 'content' of type string and 'key' of type int
output: encrypted string 'content'
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert isinstance(key, int) and isinstance(content, str)
key = key or self.__key or 1
# make sure key can be any size
while key > 255:
key -= 255
# This will be returned
ans = ""
for ch in content:
ans += chr(ord(ch) ^ key)
return ans
def decrypt_string(self, content: str, key: int = 0) -> str:
"""
input: 'content' of type string and 'key' of type int
output: decrypted string 'content'
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert isinstance(key, int) and isinstance(content, str)
key = key or self.__key or 1
# make sure key can be any size
while key > 255:
key -= 255
# This will be returned
ans = ""
for ch in content:
ans += chr(ord(ch) ^ key)
return ans
def encrypt_file(self, file: str, key: int = 0) -> bool:
"""
input: filename (str) and a key (int)
output: returns true if encrypt process was
successful otherwise false
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert isinstance(file, str) and isinstance(key, int)
try:
with open(file) as fin:
with open("encrypt.out", "w+") as fout:
# actual encrypt-process
for line in fin:
fout.write(self.encrypt_string(line, key))
except OSError:
return False
return True
def decrypt_file(self, file: str, key: int) -> bool:
"""
input: filename (str) and a key (int)
output: returns true if decrypt process was
successful otherwise false
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert isinstance(file, str) and isinstance(key, int)
try:
with open(file) as fin:
with open("decrypt.out", "w+") as fout:
# actual encrypt-process
for line in fin:
fout.write(self.decrypt_string(line, key))
except OSError:
return False
return True
# Tests
# crypt = XORCipher()
# key = 67
# # test encrypt
# print(crypt.encrypt("hallo welt",key))
# # test decrypt
# print(crypt.decrypt(crypt.encrypt("hallo welt",key), key))
# # test encrypt_string
# print(crypt.encrypt_string("hallo welt",key))
# # test decrypt_string
# print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key))
# if (crypt.encrypt_file("test.txt",key)):
# print("encrypt successful")
# else:
# print("encrypt unsuccessful")
# if (crypt.decrypt_file("encrypt.out",key)):
# print("decrypt successful")
# else:
# print("decrypt unsuccessful")
| """
author: Christian Bender
date: 21.12.2017
class: XORCipher
This class implements the XOR-cipher algorithm and provides
some useful methods for encrypting and decrypting strings and
files.
Overview about methods
- encrypt : list of char
- decrypt : list of char
- encrypt_string : str
- decrypt_string : str
- encrypt_file : boolean
- decrypt_file : boolean
"""
from __future__ import annotations
class XORCipher:
def __init__(self, key: int = 0):
"""
simple constructor that receives a key or uses
default key = 0
"""
# private field
self.__key = key
def encrypt(self, content: str, key: int) -> list[str]:
"""
input: 'content' of type string and 'key' of type int
output: encrypted string 'content' as a list of chars
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert isinstance(key, int) and isinstance(content, str)
key = key or self.__key or 1
# make sure key is an appropriate size
key %= 255
return [chr(ord(ch) ^ key) for ch in content]
def decrypt(self, content: str, key: int) -> list[str]:
"""
input: 'content' of type list and 'key' of type int
output: decrypted string 'content' as a list of chars
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert isinstance(key, int) and isinstance(content, list)
key = key or self.__key or 1
# make sure key is an appropriate size
key %= 255
return [chr(ord(ch) ^ key) for ch in content]
def encrypt_string(self, content: str, key: int = 0) -> str:
"""
input: 'content' of type string and 'key' of type int
output: encrypted string 'content'
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert isinstance(key, int) and isinstance(content, str)
key = key or self.__key or 1
# make sure key can be any size
while key > 255:
key -= 255
# This will be returned
ans = ""
for ch in content:
ans += chr(ord(ch) ^ key)
return ans
def decrypt_string(self, content: str, key: int = 0) -> str:
"""
input: 'content' of type string and 'key' of type int
output: decrypted string 'content'
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert isinstance(key, int) and isinstance(content, str)
key = key or self.__key or 1
# make sure key can be any size
while key > 255:
key -= 255
# This will be returned
ans = ""
for ch in content:
ans += chr(ord(ch) ^ key)
return ans
def encrypt_file(self, file: str, key: int = 0) -> bool:
"""
input: filename (str) and a key (int)
output: returns true if encrypt process was
successful otherwise false
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert isinstance(file, str) and isinstance(key, int)
try:
with open(file) as fin:
with open("encrypt.out", "w+") as fout:
# actual encrypt-process
for line in fin:
fout.write(self.encrypt_string(line, key))
except OSError:
return False
return True
def decrypt_file(self, file: str, key: int) -> bool:
"""
input: filename (str) and a key (int)
output: returns true if decrypt process was
successful otherwise false
if key not passed the method uses the key by the constructor.
otherwise key = 1
"""
# precondition
assert isinstance(file, str) and isinstance(key, int)
try:
with open(file) as fin:
with open("decrypt.out", "w+") as fout:
# actual encrypt-process
for line in fin:
fout.write(self.decrypt_string(line, key))
except OSError:
return False
return True
# Tests
# crypt = XORCipher()
# key = 67
# # test encrypt
# print(crypt.encrypt("hallo welt",key))
# # test decrypt
# print(crypt.decrypt(crypt.encrypt("hallo welt",key), key))
# # test encrypt_string
# print(crypt.encrypt_string("hallo welt",key))
# # test decrypt_string
# print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key))
# if (crypt.encrypt_file("test.txt",key)):
# print("encrypt successful")
# else:
# print("encrypt unsuccessful")
# if (crypt.decrypt_file("encrypt.out",key)):
# print("decrypt successful")
# else:
# print("decrypt unsuccessful")
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/env python3
import os
try:
from .build_directory_md import good_file_paths
except ImportError:
from build_directory_md import good_file_paths # type: ignore
filepaths = list(good_file_paths())
assert filepaths, "good_file_paths() failed!"
upper_files = [file for file in filepaths if file != file.lower()]
if upper_files:
print(f"{len(upper_files)} files contain uppercase characters:")
print("\n".join(upper_files) + "\n")
space_files = [file for file in filepaths if " " in file]
if space_files:
print(f"{len(space_files)} files contain space characters:")
print("\n".join(space_files) + "\n")
hyphen_files = [file for file in filepaths if "-" in file]
if hyphen_files:
print(f"{len(hyphen_files)} files contain hyphen characters:")
print("\n".join(hyphen_files) + "\n")
nodir_files = [file for file in filepaths if os.sep not in file]
if nodir_files:
print(f"{len(nodir_files)} files are not in a directory:")
print("\n".join(nodir_files) + "\n")
bad_files = len(upper_files + space_files + hyphen_files + nodir_files)
if bad_files:
import sys
sys.exit(bad_files)
| #!/usr/bin/env python3
import os
try:
from .build_directory_md import good_file_paths
except ImportError:
from build_directory_md import good_file_paths # type: ignore
filepaths = list(good_file_paths())
assert filepaths, "good_file_paths() failed!"
upper_files = [file for file in filepaths if file != file.lower()]
if upper_files:
print(f"{len(upper_files)} files contain uppercase characters:")
print("\n".join(upper_files) + "\n")
space_files = [file for file in filepaths if " " in file]
if space_files:
print(f"{len(space_files)} files contain space characters:")
print("\n".join(space_files) + "\n")
hyphen_files = [file for file in filepaths if "-" in file]
if hyphen_files:
print(f"{len(hyphen_files)} files contain hyphen characters:")
print("\n".join(hyphen_files) + "\n")
nodir_files = [file for file in filepaths if os.sep not in file]
if nodir_files:
print(f"{len(nodir_files)} files are not in a directory:")
print("\n".join(nodir_files) + "\n")
bad_files = len(upper_files + space_files + hyphen_files + nodir_files)
if bad_files:
import sys
sys.exit(bad_files)
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Checks if a system of forces is in static equilibrium.
"""
from __future__ import annotations
from numpy import array, cos, cross, ndarray, radians, sin
def polar_force(
magnitude: float, angle: float, radian_mode: bool = False
) -> list[float]:
"""
Resolves force along rectangular components.
(force, angle) => (force_x, force_y)
>>> polar_force(10, 45)
[7.0710678118654755, 7.071067811865475]
>>> polar_force(10, 3.14, radian_mode=True)
[-9.999987317275394, 0.01592652916486828]
"""
if radian_mode:
return [magnitude * cos(angle), magnitude * sin(angle)]
return [magnitude * cos(radians(angle)), magnitude * sin(radians(angle))]
def in_static_equilibrium(
forces: ndarray, location: ndarray, eps: float = 10 ** -1
) -> bool:
"""
Check if a system is in equilibrium.
It takes two numpy.array objects.
forces ==> [
[force1_x, force1_y],
[force2_x, force2_y],
....]
location ==> [
[x1, y1],
[x2, y2],
....]
>>> force = array([[1, 1], [-1, 2]])
>>> location = array([[1, 0], [10, 0]])
>>> in_static_equilibrium(force, location)
False
"""
# summation of moments is zero
moments: ndarray = cross(location, forces)
sum_moments: float = sum(moments)
return abs(sum_moments) < eps
if __name__ == "__main__":
# Test to check if it works
forces = array(
[polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90)]
)
location = array([[0, 0], [0, 0], [0, 0]])
assert in_static_equilibrium(forces, location)
# Problem 1 in image_data/2D_problems.jpg
forces = array(
[
polar_force(30 * 9.81, 15),
polar_force(215, 180 - 45),
polar_force(264, 90 - 30),
]
)
location = array([[0, 0], [0, 0], [0, 0]])
assert in_static_equilibrium(forces, location)
# Problem in image_data/2D_problems_1.jpg
forces = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]])
location = array([[0, 0], [6, 0], [10, 0], [12, 0]])
assert in_static_equilibrium(forces, location)
import doctest
doctest.testmod()
| """
Checks if a system of forces is in static equilibrium.
"""
from __future__ import annotations
from numpy import array, cos, cross, ndarray, radians, sin
def polar_force(
magnitude: float, angle: float, radian_mode: bool = False
) -> list[float]:
"""
Resolves force along rectangular components.
(force, angle) => (force_x, force_y)
>>> polar_force(10, 45)
[7.0710678118654755, 7.071067811865475]
>>> polar_force(10, 3.14, radian_mode=True)
[-9.999987317275394, 0.01592652916486828]
"""
if radian_mode:
return [magnitude * cos(angle), magnitude * sin(angle)]
return [magnitude * cos(radians(angle)), magnitude * sin(radians(angle))]
def in_static_equilibrium(
forces: ndarray, location: ndarray, eps: float = 10 ** -1
) -> bool:
"""
Check if a system is in equilibrium.
It takes two numpy.array objects.
forces ==> [
[force1_x, force1_y],
[force2_x, force2_y],
....]
location ==> [
[x1, y1],
[x2, y2],
....]
>>> force = array([[1, 1], [-1, 2]])
>>> location = array([[1, 0], [10, 0]])
>>> in_static_equilibrium(force, location)
False
"""
# summation of moments is zero
moments: ndarray = cross(location, forces)
sum_moments: float = sum(moments)
return abs(sum_moments) < eps
if __name__ == "__main__":
# Test to check if it works
forces = array(
[polar_force(718.4, 180 - 30), polar_force(879.54, 45), polar_force(100, -90)]
)
location = array([[0, 0], [0, 0], [0, 0]])
assert in_static_equilibrium(forces, location)
# Problem 1 in image_data/2D_problems.jpg
forces = array(
[
polar_force(30 * 9.81, 15),
polar_force(215, 180 - 45),
polar_force(264, 90 - 30),
]
)
location = array([[0, 0], [0, 0], [0, 0]])
assert in_static_equilibrium(forces, location)
# Problem in image_data/2D_problems_1.jpg
forces = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]])
location = array([[0, 0], [6, 0], [10, 0], [12, 0]])
assert in_static_equilibrium(forces, location)
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import json
import requests
from .fetch_github_info import AUTHENTICATED_USER_ENDPOINT, fetch_github_info
def test_fetch_github_info(monkeypatch):
class FakeResponse:
def __init__(self, content) -> None:
assert isinstance(content, (bytes, str))
self.content = content
def json(self):
return json.loads(self.content)
def mock_response(*args, **kwargs):
assert args[0] == AUTHENTICATED_USER_ENDPOINT
assert "Authorization" in kwargs["headers"]
assert kwargs["headers"]["Authorization"].startswith("token ")
assert "Accept" in kwargs["headers"]
return FakeResponse(b'{"login":"test","id":1}')
monkeypatch.setattr(requests, "get", mock_response)
result = fetch_github_info("token")
assert result["login"] == "test"
assert result["id"] == 1
| import json
import requests
from .fetch_github_info import AUTHENTICATED_USER_ENDPOINT, fetch_github_info
def test_fetch_github_info(monkeypatch):
class FakeResponse:
def __init__(self, content) -> None:
assert isinstance(content, (bytes, str))
self.content = content
def json(self):
return json.loads(self.content)
def mock_response(*args, **kwargs):
assert args[0] == AUTHENTICATED_USER_ENDPOINT
assert "Authorization" in kwargs["headers"]
assert kwargs["headers"]["Authorization"].startswith("token ")
assert "Accept" in kwargs["headers"]
return FakeResponse(b'{"login":"test","id":1}')
monkeypatch.setattr(requests, "get", mock_response)
result = fetch_github_info("token")
assert result["login"] == "test"
assert result["id"] == 1
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Created by susmith98
from collections import Counter
from timeit import timeit
# Problem Description:
# Check if characters of the given string can be rearranged to form a palindrome.
# Counter is faster for long strings and non-Counter is faster for short strings.
def can_string_be_rearranged_as_palindrome_counter(
input_str: str = "",
) -> bool:
"""
A Palindrome is a String that reads the same forward as it does backwards.
Examples of Palindromes mom, dad, malayalam
>>> can_string_be_rearranged_as_palindrome_counter("Momo")
True
>>> can_string_be_rearranged_as_palindrome_counter("Mother")
False
>>> can_string_be_rearranged_as_palindrome_counter("Father")
False
>>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama")
True
"""
return sum(c % 2 for c in Counter(input_str.replace(" ", "").lower()).values()) < 2
def can_string_be_rearranged_as_palindrome(input_str: str = "") -> bool:
"""
A Palindrome is a String that reads the same forward as it does backwards.
Examples of Palindromes mom, dad, malayalam
>>> can_string_be_rearranged_as_palindrome("Momo")
True
>>> can_string_be_rearranged_as_palindrome("Mother")
False
>>> can_string_be_rearranged_as_palindrome("Father")
False
>>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama")
True
"""
if len(input_str) == 0:
return True
lower_case_input_str = input_str.replace(" ", "").lower()
# character_freq_dict: Stores the frequency of every character in the input string
character_freq_dict: dict[str, int] = {}
for character in lower_case_input_str:
character_freq_dict[character] = character_freq_dict.get(character, 0) + 1
"""
Above line of code is equivalent to:
1) Getting the frequency of current character till previous index
>>> character_freq = character_freq_dict.get(character, 0)
2) Incrementing the frequency of current character by 1
>>> character_freq = character_freq + 1
3) Updating the frequency of current character
>>> character_freq_dict[character] = character_freq
"""
"""
OBSERVATIONS:
Even length palindrome
-> Every character appears even no.of times.
Odd length palindrome
-> Every character appears even no.of times except for one character.
LOGIC:
Step 1: We'll count number of characters that appear odd number of times i.e oddChar
Step 2:If we find more than 1 character that appears odd number of times,
It is not possible to rearrange as a palindrome
"""
oddChar = 0
for character_count in character_freq_dict.values():
if character_count % 2:
oddChar += 1
if oddChar > 1:
return False
return True
def benchmark(input_str: str = "") -> None:
"""
Benchmark code for comparing above 2 functions
"""
print("\nFor string = ", input_str, ":")
print(
"> can_string_be_rearranged_as_palindrome_counter()",
"\tans =",
can_string_be_rearranged_as_palindrome_counter(input_str),
"\ttime =",
timeit(
"z.can_string_be_rearranged_as_palindrome_counter(z.check_str)",
setup="import __main__ as z",
),
"seconds",
)
print(
"> can_string_be_rearranged_as_palindrome()",
"\tans =",
can_string_be_rearranged_as_palindrome(input_str),
"\ttime =",
timeit(
"z.can_string_be_rearranged_as_palindrome(z.check_str)",
setup="import __main__ as z",
),
"seconds",
)
if __name__ == "__main__":
check_str = input(
"Enter string to determine if it can be rearranged as a palindrome or not: "
).strip()
benchmark(check_str)
status = can_string_be_rearranged_as_palindrome_counter(check_str)
print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
| # Created by susmith98
from collections import Counter
from timeit import timeit
# Problem Description:
# Check if characters of the given string can be rearranged to form a palindrome.
# Counter is faster for long strings and non-Counter is faster for short strings.
def can_string_be_rearranged_as_palindrome_counter(
input_str: str = "",
) -> bool:
"""
A Palindrome is a String that reads the same forward as it does backwards.
Examples of Palindromes mom, dad, malayalam
>>> can_string_be_rearranged_as_palindrome_counter("Momo")
True
>>> can_string_be_rearranged_as_palindrome_counter("Mother")
False
>>> can_string_be_rearranged_as_palindrome_counter("Father")
False
>>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama")
True
"""
return sum(c % 2 for c in Counter(input_str.replace(" ", "").lower()).values()) < 2
def can_string_be_rearranged_as_palindrome(input_str: str = "") -> bool:
"""
A Palindrome is a String that reads the same forward as it does backwards.
Examples of Palindromes mom, dad, malayalam
>>> can_string_be_rearranged_as_palindrome("Momo")
True
>>> can_string_be_rearranged_as_palindrome("Mother")
False
>>> can_string_be_rearranged_as_palindrome("Father")
False
>>> can_string_be_rearranged_as_palindrome_counter("A man a plan a canal Panama")
True
"""
if len(input_str) == 0:
return True
lower_case_input_str = input_str.replace(" ", "").lower()
# character_freq_dict: Stores the frequency of every character in the input string
character_freq_dict: dict[str, int] = {}
for character in lower_case_input_str:
character_freq_dict[character] = character_freq_dict.get(character, 0) + 1
"""
Above line of code is equivalent to:
1) Getting the frequency of current character till previous index
>>> character_freq = character_freq_dict.get(character, 0)
2) Incrementing the frequency of current character by 1
>>> character_freq = character_freq + 1
3) Updating the frequency of current character
>>> character_freq_dict[character] = character_freq
"""
"""
OBSERVATIONS:
Even length palindrome
-> Every character appears even no.of times.
Odd length palindrome
-> Every character appears even no.of times except for one character.
LOGIC:
Step 1: We'll count number of characters that appear odd number of times i.e oddChar
Step 2:If we find more than 1 character that appears odd number of times,
It is not possible to rearrange as a palindrome
"""
oddChar = 0
for character_count in character_freq_dict.values():
if character_count % 2:
oddChar += 1
if oddChar > 1:
return False
return True
def benchmark(input_str: str = "") -> None:
"""
Benchmark code for comparing above 2 functions
"""
print("\nFor string = ", input_str, ":")
print(
"> can_string_be_rearranged_as_palindrome_counter()",
"\tans =",
can_string_be_rearranged_as_palindrome_counter(input_str),
"\ttime =",
timeit(
"z.can_string_be_rearranged_as_palindrome_counter(z.check_str)",
setup="import __main__ as z",
),
"seconds",
)
print(
"> can_string_be_rearranged_as_palindrome()",
"\tans =",
can_string_be_rearranged_as_palindrome(input_str),
"\ttime =",
timeit(
"z.can_string_be_rearranged_as_palindrome(z.check_str)",
setup="import __main__ as z",
),
"seconds",
)
if __name__ == "__main__":
check_str = input(
"Enter string to determine if it can be rearranged as a palindrome or not: "
).strip()
benchmark(check_str)
status = can_string_be_rearranged_as_palindrome_counter(check_str)
print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # To get an insight into Greedy Algorithm through the Knapsack problem
"""
A shopkeeper has bags of wheat that each have different weights and different profits.
eg.
profit 5 8 7 1 12 3 4
weight 2 7 1 6 4 2 5
max_weight 100
Constraints:
max_weight > 0
profit[i] >= 0
weight[i] >= 0
Calculate the maximum profit that the shopkeeper can make given maxmum weight that can
be carried.
"""
def calc_profit(profit: list, weight: list, max_weight: int) -> int:
"""
Function description is as follows-
:param profit: Take a list of profits
:param weight: Take a list of weight if bags corresponding to the profits
:param max_weight: Maximum weight that could be carried
:return: Maximum expected gain
>>> calc_profit([1, 2, 3], [3, 4, 5], 15)
6
>>> calc_profit([10, 9 , 8], [3 ,4 , 5], 25)
27
"""
if len(profit) != len(weight):
raise ValueError("The length of profit and weight must be same.")
if max_weight <= 0:
raise ValueError("max_weight must greater than zero.")
if any(p < 0 for p in profit):
raise ValueError("Profit can not be negative.")
if any(w < 0 for w in weight):
raise ValueError("Weight can not be negative.")
# List created to store profit gained for the 1kg in case of each weight
# respectively. Calculate and append profit/weight for each element.
profit_by_weight = [p / w for p, w in zip(profit, weight)]
# Creating a copy of the list and sorting profit/weight in ascending order
sorted_profit_by_weight = sorted(profit_by_weight)
# declaring useful variables
length = len(sorted_profit_by_weight)
limit = 0
gain = 0
i = 0
# loop till the total weight do not reach max limit e.g. 15 kg and till i<length
while limit <= max_weight and i < length:
# flag value for encountered greatest element in sorted_profit_by_weight
biggest_profit_by_weight = sorted_profit_by_weight[length - i - 1]
"""
Calculate the index of the biggest_profit_by_weight in profit_by_weight list.
This will give the index of the first encountered element which is same as of
biggest_profit_by_weight. There may be one or more values same as that of
biggest_profit_by_weight but index always encounter the very first element
only. To curb this alter the values in profit_by_weight once they are used
here it is done to -1 because neither profit nor weight can be in negative.
"""
index = profit_by_weight.index(biggest_profit_by_weight)
profit_by_weight[index] = -1
# check if the weight encountered is less than the total weight
# encountered before.
if max_weight - limit >= weight[index]:
limit += weight[index]
# Adding profit gained for the given weight 1 ===
# weight[index]/weight[index]
gain += 1 * profit[index]
else:
# Since the weight encountered is greater than limit, therefore take the
# required number of remaining kgs and calculate profit for it.
# weight remaining / weight[index]
gain += (max_weight - limit) / weight[index] * profit[index]
break
i += 1
return gain
if __name__ == "__main__":
print(
"Input profits, weights, and then max_weight (all positive ints) separated by "
"spaces."
)
profit = [int(x) for x in input("Input profits separated by spaces: ").split()]
weight = [int(x) for x in input("Input weights separated by spaces: ").split()]
max_weight = int(input("Max weight allowed: "))
# Function Call
calc_profit(profit, weight, max_weight)
| # To get an insight into Greedy Algorithm through the Knapsack problem
"""
A shopkeeper has bags of wheat that each have different weights and different profits.
eg.
profit 5 8 7 1 12 3 4
weight 2 7 1 6 4 2 5
max_weight 100
Constraints:
max_weight > 0
profit[i] >= 0
weight[i] >= 0
Calculate the maximum profit that the shopkeeper can make given maxmum weight that can
be carried.
"""
def calc_profit(profit: list, weight: list, max_weight: int) -> int:
"""
Function description is as follows-
:param profit: Take a list of profits
:param weight: Take a list of weight if bags corresponding to the profits
:param max_weight: Maximum weight that could be carried
:return: Maximum expected gain
>>> calc_profit([1, 2, 3], [3, 4, 5], 15)
6
>>> calc_profit([10, 9 , 8], [3 ,4 , 5], 25)
27
"""
if len(profit) != len(weight):
raise ValueError("The length of profit and weight must be same.")
if max_weight <= 0:
raise ValueError("max_weight must greater than zero.")
if any(p < 0 for p in profit):
raise ValueError("Profit can not be negative.")
if any(w < 0 for w in weight):
raise ValueError("Weight can not be negative.")
# List created to store profit gained for the 1kg in case of each weight
# respectively. Calculate and append profit/weight for each element.
profit_by_weight = [p / w for p, w in zip(profit, weight)]
# Creating a copy of the list and sorting profit/weight in ascending order
sorted_profit_by_weight = sorted(profit_by_weight)
# declaring useful variables
length = len(sorted_profit_by_weight)
limit = 0
gain = 0
i = 0
# loop till the total weight do not reach max limit e.g. 15 kg and till i<length
while limit <= max_weight and i < length:
# flag value for encountered greatest element in sorted_profit_by_weight
biggest_profit_by_weight = sorted_profit_by_weight[length - i - 1]
"""
Calculate the index of the biggest_profit_by_weight in profit_by_weight list.
This will give the index of the first encountered element which is same as of
biggest_profit_by_weight. There may be one or more values same as that of
biggest_profit_by_weight but index always encounter the very first element
only. To curb this alter the values in profit_by_weight once they are used
here it is done to -1 because neither profit nor weight can be in negative.
"""
index = profit_by_weight.index(biggest_profit_by_weight)
profit_by_weight[index] = -1
# check if the weight encountered is less than the total weight
# encountered before.
if max_weight - limit >= weight[index]:
limit += weight[index]
# Adding profit gained for the given weight 1 ===
# weight[index]/weight[index]
gain += 1 * profit[index]
else:
# Since the weight encountered is greater than limit, therefore take the
# required number of remaining kgs and calculate profit for it.
# weight remaining / weight[index]
gain += (max_weight - limit) / weight[index] * profit[index]
break
i += 1
return gain
if __name__ == "__main__":
print(
"Input profits, weights, and then max_weight (all positive ints) separated by "
"spaces."
)
profit = [int(x) for x in input("Input profits separated by spaces: ").split()]
weight = [int(x) for x in input("Input weights separated by spaces: ").split()]
max_weight = int(input("Max weight allowed: "))
# Function Call
calc_profit(profit, weight, max_weight)
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Given an array of integer elements and an integer 'k', we are required to find the
maximum sum of 'k' consecutive elements in the array.
Instead of using a nested for loop, in a Brute force approach we will use a technique
called 'Window sliding technique' where the nested loops can be converted to a single
loop to reduce time complexity.
"""
from __future__ import annotations
def max_sum_in_array(array: list[int], k: int) -> int:
"""
Returns the maximum sum of k consecutive elements
>>> arr = [1, 4, 2, 10, 2, 3, 1, 0, 20]
>>> k = 4
>>> max_sum_in_array(arr, k)
24
>>> k = 10
>>> max_sum_in_array(arr,k)
Traceback (most recent call last):
...
ValueError: Invalid Input
>>> arr = [1, 4, 2, 10, 2, 13, 1, 0, 2]
>>> k = 4
>>> max_sum_in_array(arr, k)
27
"""
if len(array) < k or k < 0:
raise ValueError("Invalid Input")
max_sum = current_sum = sum(array[:k])
for i in range(len(array) - k):
current_sum = current_sum - array[i] + array[i + k]
max_sum = max(max_sum, current_sum)
return max_sum
if __name__ == "__main__":
from doctest import testmod
from random import randint
testmod()
array = [randint(-1000, 1000) for i in range(100)]
k = randint(0, 110)
print(f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}")
| """
Given an array of integer elements and an integer 'k', we are required to find the
maximum sum of 'k' consecutive elements in the array.
Instead of using a nested for loop, in a Brute force approach we will use a technique
called 'Window sliding technique' where the nested loops can be converted to a single
loop to reduce time complexity.
"""
from __future__ import annotations
def max_sum_in_array(array: list[int], k: int) -> int:
"""
Returns the maximum sum of k consecutive elements
>>> arr = [1, 4, 2, 10, 2, 3, 1, 0, 20]
>>> k = 4
>>> max_sum_in_array(arr, k)
24
>>> k = 10
>>> max_sum_in_array(arr,k)
Traceback (most recent call last):
...
ValueError: Invalid Input
>>> arr = [1, 4, 2, 10, 2, 13, 1, 0, 2]
>>> k = 4
>>> max_sum_in_array(arr, k)
27
"""
if len(array) < k or k < 0:
raise ValueError("Invalid Input")
max_sum = current_sum = sum(array[:k])
for i in range(len(array) - k):
current_sum = current_sum - array[i] + array[i + k]
max_sum = max(max_sum, current_sum)
return max_sum
if __name__ == "__main__":
from doctest import testmod
from random import randint
testmod()
array = [randint(-1000, 1000) for i in range(100)]
k = randint(0, 110)
print(f"The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}")
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from math import asin, atan, cos, radians, sin, sqrt, tan
def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""
Calculate great circle distance between two points in a sphere,
given longitudes and latitudes https://en.wikipedia.org/wiki/Haversine_formula
We know that the globe is "sort of" spherical, so a path between two points
isn't exactly a straight line. We need to account for the Earth's curvature
when calculating distance from point A to B. This effect is negligible for
small distances but adds up as distance increases. The Haversine method treats
the earth as a sphere which allows us to "project" the two points A and B
onto the surface of that sphere and approximate the spherical distance between
them. Since the Earth is not a perfect sphere, other methods which model the
Earth's ellipsoidal nature are more accurate but a quick and modifiable
computation like Haversine can be handy for shorter range distances.
Args:
lat1, lon1: latitude and longitude of coordinate 1
lat2, lon2: latitude and longitude of coordinate 2
Returns:
geographical distance between two points in metres
>>> from collections import namedtuple
>>> point_2d = namedtuple("point_2d", "lat lon")
>>> SAN_FRANCISCO = point_2d(37.774856, -122.424227)
>>> YOSEMITE = point_2d(37.864742, -119.537521)
>>> f"{haversine_distance(*SAN_FRANCISCO, *YOSEMITE):0,.0f} meters"
'254,352 meters'
"""
# CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System
# Distance in metres(m)
AXIS_A = 6378137.0
AXIS_B = 6356752.314245
RADIUS = 6378137
# Equation parameters
# Equation https://en.wikipedia.org/wiki/Haversine_formula#Formulation
flattening = (AXIS_A - AXIS_B) / AXIS_A
phi_1 = atan((1 - flattening) * tan(radians(lat1)))
phi_2 = atan((1 - flattening) * tan(radians(lat2)))
lambda_1 = radians(lon1)
lambda_2 = radians(lon2)
# Equation
sin_sq_phi = sin((phi_2 - phi_1) / 2)
sin_sq_lambda = sin((lambda_2 - lambda_1) / 2)
# Square both values
sin_sq_phi *= sin_sq_phi
sin_sq_lambda *= sin_sq_lambda
h_value = sqrt(sin_sq_phi + (cos(phi_1) * cos(phi_2) * sin_sq_lambda))
return 2 * RADIUS * asin(h_value)
if __name__ == "__main__":
import doctest
doctest.testmod()
| from math import asin, atan, cos, radians, sin, sqrt, tan
def haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
"""
Calculate great circle distance between two points in a sphere,
given longitudes and latitudes https://en.wikipedia.org/wiki/Haversine_formula
We know that the globe is "sort of" spherical, so a path between two points
isn't exactly a straight line. We need to account for the Earth's curvature
when calculating distance from point A to B. This effect is negligible for
small distances but adds up as distance increases. The Haversine method treats
the earth as a sphere which allows us to "project" the two points A and B
onto the surface of that sphere and approximate the spherical distance between
them. Since the Earth is not a perfect sphere, other methods which model the
Earth's ellipsoidal nature are more accurate but a quick and modifiable
computation like Haversine can be handy for shorter range distances.
Args:
lat1, lon1: latitude and longitude of coordinate 1
lat2, lon2: latitude and longitude of coordinate 2
Returns:
geographical distance between two points in metres
>>> from collections import namedtuple
>>> point_2d = namedtuple("point_2d", "lat lon")
>>> SAN_FRANCISCO = point_2d(37.774856, -122.424227)
>>> YOSEMITE = point_2d(37.864742, -119.537521)
>>> f"{haversine_distance(*SAN_FRANCISCO, *YOSEMITE):0,.0f} meters"
'254,352 meters'
"""
# CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System
# Distance in metres(m)
AXIS_A = 6378137.0
AXIS_B = 6356752.314245
RADIUS = 6378137
# Equation parameters
# Equation https://en.wikipedia.org/wiki/Haversine_formula#Formulation
flattening = (AXIS_A - AXIS_B) / AXIS_A
phi_1 = atan((1 - flattening) * tan(radians(lat1)))
phi_2 = atan((1 - flattening) * tan(radians(lat2)))
lambda_1 = radians(lon1)
lambda_2 = radians(lon2)
# Equation
sin_sq_phi = sin((phi_2 - phi_1) / 2)
sin_sq_lambda = sin((lambda_2 - lambda_1) / 2)
# Square both values
sin_sq_phi *= sin_sq_phi
sin_sq_lambda *= sin_sq_lambda
h_value = sqrt(sin_sq_phi + (cos(phi_1) * cos(phi_2) * sin_sq_lambda))
return 2 * RADIUS * asin(h_value)
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
This is a pure Python implementation of the merge-insertion sort algorithm
Source: https://en.wikipedia.org/wiki/Graham_scan
For doctests run following command:
python3 -m doctest -v graham_scan.py
"""
from __future__ import annotations
from collections import deque
from enum import Enum
from math import atan2, degrees
from sys import maxsize
def graham_scan(points: list[tuple[int, int]]) -> list[tuple[int, int]]:
"""Pure implementation of graham scan algorithm in Python
:param points: The unique points on coordinates.
:return: The points on convex hell.
Examples:
>>> graham_scan([(9, 6), (3, 1), (0, 0), (5, 5), (5, 2), (7, 0), (3, 3), (1, 4)])
[(0, 0), (7, 0), (9, 6), (5, 5), (1, 4)]
>>> graham_scan([(0, 0), (1, 0), (1, 1), (0, 1)])
[(0, 0), (1, 0), (1, 1), (0, 1)]
>>> graham_scan([(0, 0), (1, 1), (2, 2), (3, 3), (-1, 2)])
[(0, 0), (1, 1), (2, 2), (3, 3), (-1, 2)]
>>> graham_scan([(-100, 20), (99, 3), (1, 10000001), (5133186, -25), (-66, -4)])
[(5133186, -25), (1, 10000001), (-100, 20), (-66, -4)]
"""
if len(points) <= 2:
# There is no convex hull
raise ValueError("graham_scan: argument must contain more than 3 points.")
if len(points) == 3:
return points
# find the lowest and the most left point
minidx = 0
miny, minx = maxsize, maxsize
for i, point in enumerate(points):
x = point[0]
y = point[1]
if y < miny:
miny = y
minx = x
minidx = i
if y == miny:
if x < minx:
minx = x
minidx = i
# remove the lowest and the most left point from points for preparing for sort
points.pop(minidx)
def angle_comparer(point: tuple[int, int], minx: int, miny: int) -> float:
"""Return the angle toward to point from (minx, miny)
:param point: The target point
minx: The starting point's x
miny: The starting point's y
:return: the angle
Examples:
>>> angle_comparer((1,1), 0, 0)
45.0
>>> angle_comparer((100,1), 10, 10)
-5.710593137499642
>>> angle_comparer((5,5), 2, 3)
33.690067525979785
"""
# sort the points accorgind to the angle from the lowest and the most left point
x = point[0]
y = point[1]
angle = degrees(atan2(y - miny, x - minx))
return angle
sorted_points = sorted(points, key=lambda point: angle_comparer(point, minx, miny))
# This insert actually costs complexity,
# and you should instead add (minx, miny) into stack later.
# I'm using insert just for easy understanding.
sorted_points.insert(0, (minx, miny))
# traversal from the lowest and the most left point in anti-clockwise direction
# if direction gets right, the previous point is not the convex hull.
class Direction(Enum):
left = 1
straight = 2
right = 3
def check_direction(
starting: tuple[int, int], via: tuple[int, int], target: tuple[int, int]
) -> Direction:
"""Return the direction toward to the line from via to target from starting
:param starting: The starting point
via: The via point
target: The target point
:return: the Direction
Examples:
>>> check_direction((1,1), (2,2), (3,3))
Direction.straight
>>> check_direction((60,1), (-50,199), (30,2))
Direction.left
>>> check_direction((0,0), (5,5), (10,0))
Direction.right
"""
x0, y0 = starting
x1, y1 = via
x2, y2 = target
via_angle = degrees(atan2(y1 - y0, x1 - x0))
if via_angle < 0:
via_angle += 360
target_angle = degrees(atan2(y2 - y0, x2 - x0))
if target_angle < 0:
target_angle += 360
# t-
# \ \
# \ v
# \|
# s
# via_angle is always lower than target_angle, if direction is left.
# If they are same, it means they are on a same line of convex hull.
if target_angle > via_angle:
return Direction.left
elif target_angle == via_angle:
return Direction.straight
else:
return Direction.right
stack: deque[tuple[int, int]] = deque()
stack.append(sorted_points[0])
stack.append(sorted_points[1])
stack.append(sorted_points[2])
# In any ways, the first 3 points line are towards left.
# Because we sort them the angle from minx, miny.
current_direction = Direction.left
for i in range(3, len(sorted_points)):
while True:
starting = stack[-2]
via = stack[-1]
target = sorted_points[i]
next_direction = check_direction(starting, via, target)
if next_direction == Direction.left:
current_direction = Direction.left
break
if next_direction == Direction.straight:
if current_direction == Direction.left:
# We keep current_direction as left.
# Because if the straight line keeps as straight,
# we want to know if this straight line is towards left.
break
elif current_direction == Direction.right:
# If the straight line is towards right,
# every previous points on those straigh line is not convex hull.
stack.pop()
if next_direction == Direction.right:
stack.pop()
stack.append(sorted_points[i])
return list(stack)
| """
This is a pure Python implementation of the merge-insertion sort algorithm
Source: https://en.wikipedia.org/wiki/Graham_scan
For doctests run following command:
python3 -m doctest -v graham_scan.py
"""
from __future__ import annotations
from collections import deque
from enum import Enum
from math import atan2, degrees
from sys import maxsize
def graham_scan(points: list[tuple[int, int]]) -> list[tuple[int, int]]:
"""Pure implementation of graham scan algorithm in Python
:param points: The unique points on coordinates.
:return: The points on convex hell.
Examples:
>>> graham_scan([(9, 6), (3, 1), (0, 0), (5, 5), (5, 2), (7, 0), (3, 3), (1, 4)])
[(0, 0), (7, 0), (9, 6), (5, 5), (1, 4)]
>>> graham_scan([(0, 0), (1, 0), (1, 1), (0, 1)])
[(0, 0), (1, 0), (1, 1), (0, 1)]
>>> graham_scan([(0, 0), (1, 1), (2, 2), (3, 3), (-1, 2)])
[(0, 0), (1, 1), (2, 2), (3, 3), (-1, 2)]
>>> graham_scan([(-100, 20), (99, 3), (1, 10000001), (5133186, -25), (-66, -4)])
[(5133186, -25), (1, 10000001), (-100, 20), (-66, -4)]
"""
if len(points) <= 2:
# There is no convex hull
raise ValueError("graham_scan: argument must contain more than 3 points.")
if len(points) == 3:
return points
# find the lowest and the most left point
minidx = 0
miny, minx = maxsize, maxsize
for i, point in enumerate(points):
x = point[0]
y = point[1]
if y < miny:
miny = y
minx = x
minidx = i
if y == miny:
if x < minx:
minx = x
minidx = i
# remove the lowest and the most left point from points for preparing for sort
points.pop(minidx)
def angle_comparer(point: tuple[int, int], minx: int, miny: int) -> float:
"""Return the angle toward to point from (minx, miny)
:param point: The target point
minx: The starting point's x
miny: The starting point's y
:return: the angle
Examples:
>>> angle_comparer((1,1), 0, 0)
45.0
>>> angle_comparer((100,1), 10, 10)
-5.710593137499642
>>> angle_comparer((5,5), 2, 3)
33.690067525979785
"""
# sort the points accorgind to the angle from the lowest and the most left point
x = point[0]
y = point[1]
angle = degrees(atan2(y - miny, x - minx))
return angle
sorted_points = sorted(points, key=lambda point: angle_comparer(point, minx, miny))
# This insert actually costs complexity,
# and you should instead add (minx, miny) into stack later.
# I'm using insert just for easy understanding.
sorted_points.insert(0, (minx, miny))
# traversal from the lowest and the most left point in anti-clockwise direction
# if direction gets right, the previous point is not the convex hull.
class Direction(Enum):
left = 1
straight = 2
right = 3
def check_direction(
starting: tuple[int, int], via: tuple[int, int], target: tuple[int, int]
) -> Direction:
"""Return the direction toward to the line from via to target from starting
:param starting: The starting point
via: The via point
target: The target point
:return: the Direction
Examples:
>>> check_direction((1,1), (2,2), (3,3))
Direction.straight
>>> check_direction((60,1), (-50,199), (30,2))
Direction.left
>>> check_direction((0,0), (5,5), (10,0))
Direction.right
"""
x0, y0 = starting
x1, y1 = via
x2, y2 = target
via_angle = degrees(atan2(y1 - y0, x1 - x0))
if via_angle < 0:
via_angle += 360
target_angle = degrees(atan2(y2 - y0, x2 - x0))
if target_angle < 0:
target_angle += 360
# t-
# \ \
# \ v
# \|
# s
# via_angle is always lower than target_angle, if direction is left.
# If they are same, it means they are on a same line of convex hull.
if target_angle > via_angle:
return Direction.left
elif target_angle == via_angle:
return Direction.straight
else:
return Direction.right
stack: deque[tuple[int, int]] = deque()
stack.append(sorted_points[0])
stack.append(sorted_points[1])
stack.append(sorted_points[2])
# In any ways, the first 3 points line are towards left.
# Because we sort them the angle from minx, miny.
current_direction = Direction.left
for i in range(3, len(sorted_points)):
while True:
starting = stack[-2]
via = stack[-1]
target = sorted_points[i]
next_direction = check_direction(starting, via, target)
if next_direction == Direction.left:
current_direction = Direction.left
break
if next_direction == Direction.straight:
if current_direction == Direction.left:
# We keep current_direction as left.
# Because if the straight line keeps as straight,
# we want to know if this straight line is towards left.
break
elif current_direction == Direction.right:
# If the straight line is towards right,
# every previous points on those straigh line is not convex hull.
stack.pop()
if next_direction == Direction.right:
stack.pop()
stack.append(sorted_points[i])
return list(stack)
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Implementation of gaussian filter algorithm
"""
from itertools import product
from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey
from numpy import dot, exp, mgrid, pi, ravel, square, uint8, zeros
def gen_gaussian_kernel(k_size, sigma):
center = k_size // 2
x, y = mgrid[0 - center : k_size - center, 0 - center : k_size - center]
g = 1 / (2 * pi * sigma) * exp(-(square(x) + square(y)) / (2 * square(sigma)))
return g
def gaussian_filter(image, k_size, sigma):
height, width = image.shape[0], image.shape[1]
# dst image height and width
dst_height = height - k_size + 1
dst_width = width - k_size + 1
# im2col, turn the k_size*k_size pixels into a row and np.vstack all rows
image_array = zeros((dst_height * dst_width, k_size * k_size))
row = 0
for i, j in product(range(dst_height), range(dst_width)):
window = ravel(image[i : i + k_size, j : j + k_size])
image_array[row, :] = window
row += 1
# turn the kernel into shape(k*k, 1)
gaussian_kernel = gen_gaussian_kernel(k_size, sigma)
filter_array = ravel(gaussian_kernel)
# reshape and get the dst image
dst = dot(image_array, filter_array).reshape(dst_height, dst_width).astype(uint8)
return dst
if __name__ == "__main__":
# read original image
img = imread(r"../image_data/lena.jpg")
# turn image in gray scale value
gray = cvtColor(img, COLOR_BGR2GRAY)
# get values with two different mask size
gaussian3x3 = gaussian_filter(gray, 3, sigma=1)
gaussian5x5 = gaussian_filter(gray, 5, sigma=0.8)
# show result images
imshow("gaussian filter with 3x3 mask", gaussian3x3)
imshow("gaussian filter with 5x5 mask", gaussian5x5)
waitKey()
| """
Implementation of gaussian filter algorithm
"""
from itertools import product
from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey
from numpy import dot, exp, mgrid, pi, ravel, square, uint8, zeros
def gen_gaussian_kernel(k_size, sigma):
center = k_size // 2
x, y = mgrid[0 - center : k_size - center, 0 - center : k_size - center]
g = 1 / (2 * pi * sigma) * exp(-(square(x) + square(y)) / (2 * square(sigma)))
return g
def gaussian_filter(image, k_size, sigma):
height, width = image.shape[0], image.shape[1]
# dst image height and width
dst_height = height - k_size + 1
dst_width = width - k_size + 1
# im2col, turn the k_size*k_size pixels into a row and np.vstack all rows
image_array = zeros((dst_height * dst_width, k_size * k_size))
row = 0
for i, j in product(range(dst_height), range(dst_width)):
window = ravel(image[i : i + k_size, j : j + k_size])
image_array[row, :] = window
row += 1
# turn the kernel into shape(k*k, 1)
gaussian_kernel = gen_gaussian_kernel(k_size, sigma)
filter_array = ravel(gaussian_kernel)
# reshape and get the dst image
dst = dot(image_array, filter_array).reshape(dst_height, dst_width).astype(uint8)
return dst
if __name__ == "__main__":
# read original image
img = imread(r"../image_data/lena.jpg")
# turn image in gray scale value
gray = cvtColor(img, COLOR_BGR2GRAY)
# get values with two different mask size
gaussian3x3 = gaussian_filter(gray, 3, sigma=1)
gaussian5x5 = gaussian_filter(gray, 5, sigma=0.8)
# show result images
imshow("gaussian filter with 3x3 mask", gaussian3x3)
imshow("gaussian filter with 5x5 mask", gaussian5x5)
waitKey()
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| def quick_sort(data: list) -> list:
"""
>>> for data in ([2, 1, 0], [2.2, 1.1, 0], "quick_sort"):
... quick_sort(data) == sorted(data)
True
True
True
"""
if len(data) <= 1:
return data
else:
return (
quick_sort([e for e in data[1:] if e <= data[0]])
+ [data[0]]
+ quick_sort([e for e in data[1:] if e > data[0]])
)
if __name__ == "__main__":
import doctest
doctest.testmod()
| def quick_sort(data: list) -> list:
"""
>>> for data in ([2, 1, 0], [2.2, 1.1, 0], "quick_sort"):
... quick_sort(data) == sorted(data)
True
True
True
"""
if len(data) <= 1:
return data
else:
return (
quick_sort([e for e in data[1:] if e <= data[0]])
+ [data[0]]
+ quick_sort([e for e in data[1:] if e > data[0]])
)
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #############################
# Author: Aravind Kashyap
# File: lis.py
# comments: This programme outputs the Longest Strictly Increasing Subsequence in
# O(NLogN) Where N is the Number of elements in the list
#############################
from __future__ import annotations
def CeilIndex(v, l, r, key): # noqa: E741
while r - l > 1:
m = (l + r) // 2
if v[m] >= key:
r = m
else:
l = m # noqa: E741
return r
def LongestIncreasingSubsequenceLength(v: list[int]) -> int:
"""
>>> LongestIncreasingSubsequenceLength([2, 5, 3, 7, 11, 8, 10, 13, 6])
6
>>> LongestIncreasingSubsequenceLength([])
0
>>> LongestIncreasingSubsequenceLength([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3,
... 11, 7, 15])
6
>>> LongestIncreasingSubsequenceLength([5, 4, 3, 2, 1])
1
"""
if len(v) == 0:
return 0
tail = [0] * len(v)
length = 1
tail[0] = v[0]
for i in range(1, len(v)):
if v[i] < tail[0]:
tail[0] = v[i]
elif v[i] > tail[length - 1]:
tail[length] = v[i]
length += 1
else:
tail[CeilIndex(tail, -1, length - 1, v[i])] = v[i]
return length
if __name__ == "__main__":
import doctest
doctest.testmod()
| #############################
# Author: Aravind Kashyap
# File: lis.py
# comments: This programme outputs the Longest Strictly Increasing Subsequence in
# O(NLogN) Where N is the Number of elements in the list
#############################
from __future__ import annotations
def CeilIndex(v, l, r, key): # noqa: E741
while r - l > 1:
m = (l + r) // 2
if v[m] >= key:
r = m
else:
l = m # noqa: E741
return r
def LongestIncreasingSubsequenceLength(v: list[int]) -> int:
"""
>>> LongestIncreasingSubsequenceLength([2, 5, 3, 7, 11, 8, 10, 13, 6])
6
>>> LongestIncreasingSubsequenceLength([])
0
>>> LongestIncreasingSubsequenceLength([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3,
... 11, 7, 15])
6
>>> LongestIncreasingSubsequenceLength([5, 4, 3, 2, 1])
1
"""
if len(v) == 0:
return 0
tail = [0] * len(v)
length = 1
tail[0] = v[0]
for i in range(1, len(v)):
if v[i] < tail[0]:
tail[0] = v[i]
elif v[i] > tail[length - 1]:
tail[length] = v[i]
length += 1
else:
tail[CeilIndex(tail, -1, length - 1, v[i])] = v[i]
return length
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """Queue represented by a Python list"""
class Queue:
def __init__(self):
self.entries = []
self.length = 0
self.front = 0
def __str__(self):
printed = "<" + str(self.entries)[1:-1] + ">"
return printed
"""Enqueues {@code item}
@param item
item to enqueue"""
def put(self, item):
self.entries.append(item)
self.length = self.length + 1
"""Dequeues {@code item}
@requirement: |self.length| > 0
@return dequeued
item that was dequeued"""
def get(self):
self.length = self.length - 1
dequeued = self.entries[self.front]
# self.front-=1
# self.entries = self.entries[self.front:]
self.entries = self.entries[1:]
return dequeued
"""Rotates the queue {@code rotation} times
@param rotation
number of times to rotate queue"""
def rotate(self, rotation):
for i in range(rotation):
self.put(self.get())
"""Enqueues {@code item}
@return item at front of self.entries"""
def get_front(self):
return self.entries[0]
"""Returns the length of this.entries"""
def size(self):
return self.length
| """Queue represented by a Python list"""
class Queue:
def __init__(self):
self.entries = []
self.length = 0
self.front = 0
def __str__(self):
printed = "<" + str(self.entries)[1:-1] + ">"
return printed
"""Enqueues {@code item}
@param item
item to enqueue"""
def put(self, item):
self.entries.append(item)
self.length = self.length + 1
"""Dequeues {@code item}
@requirement: |self.length| > 0
@return dequeued
item that was dequeued"""
def get(self):
self.length = self.length - 1
dequeued = self.entries[self.front]
# self.front-=1
# self.entries = self.entries[self.front:]
self.entries = self.entries[1:]
return dequeued
"""Rotates the queue {@code rotation} times
@param rotation
number of times to rotate queue"""
def rotate(self, rotation):
for i in range(rotation):
self.put(self.get())
"""Enqueues {@code item}
@return item at front of self.entries"""
def get_front(self):
return self.entries[0]
"""Returns the length of this.entries"""
def size(self):
return self.length
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| def dencrypt(s: str, n: int = 13) -> str:
"""
https://en.wikipedia.org/wiki/ROT13
>>> msg = "My secret bank account number is 173-52946 so don't tell anyone!!"
>>> s = dencrypt(msg)
>>> s
"Zl frperg onax nppbhag ahzore vf 173-52946 fb qba'g gryy nalbar!!"
>>> dencrypt(s) == msg
True
"""
out = ""
for c in s:
if "A" <= c <= "Z":
out += chr(ord("A") + (ord(c) - ord("A") + n) % 26)
elif "a" <= c <= "z":
out += chr(ord("a") + (ord(c) - ord("a") + n) % 26)
else:
out += c
return out
def main() -> None:
s0 = input("Enter message: ")
s1 = dencrypt(s0, 13)
print("Encryption:", s1)
s2 = dencrypt(s1, 13)
print("Decryption: ", s2)
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| def dencrypt(s: str, n: int = 13) -> str:
"""
https://en.wikipedia.org/wiki/ROT13
>>> msg = "My secret bank account number is 173-52946 so don't tell anyone!!"
>>> s = dencrypt(msg)
>>> s
"Zl frperg onax nppbhag ahzore vf 173-52946 fb qba'g gryy nalbar!!"
>>> dencrypt(s) == msg
True
"""
out = ""
for c in s:
if "A" <= c <= "Z":
out += chr(ord("A") + (ord(c) - ord("A") + n) % 26)
elif "a" <= c <= "z":
out += chr(ord("a") + (ord(c) - ord("a") + n) % 26)
else:
out += c
return out
def main() -> None:
s0 = input("Enter message: ")
s1 = dencrypt(s0, 13)
print("Encryption:", s1)
s2 = dencrypt(s1, 13)
print("Decryption: ", s2)
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
LCS Problem Statement: Given two sequences, find the length of longest subsequence
present in both of them. A subsequence is a sequence that appears in the same relative
order, but not necessarily continuous.
Example:"abc", "abg" are subsequences of "abcdefgh".
"""
def longest_common_subsequence(x: str, y: str):
"""
Finds the longest common subsequence between two strings. Also returns the
The subsequence found
Parameters
----------
x: str, one of the strings
y: str, the other string
Returns
-------
L[m][n]: int, the length of the longest subsequence. Also equal to len(seq)
Seq: str, the subsequence found
>>> longest_common_subsequence("programming", "gaming")
(6, 'gaming')
>>> longest_common_subsequence("physics", "smartphone")
(2, 'ph')
>>> longest_common_subsequence("computer", "food")
(1, 'o')
"""
# find the length of strings
assert x is not None
assert y is not None
m = len(x)
n = len(y)
# declaring the array for storing the dp values
L = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
match = 1
else:
match = 0
L[i][j] = max(L[i - 1][j], L[i][j - 1], L[i - 1][j - 1] + match)
seq = ""
i, j = m, n
while i > 0 and j > 0:
if x[i - 1] == y[j - 1]:
match = 1
else:
match = 0
if L[i][j] == L[i - 1][j - 1] + match:
if match == 1:
seq = x[i - 1] + seq
i -= 1
j -= 1
elif L[i][j] == L[i - 1][j]:
i -= 1
else:
j -= 1
return L[m][n], seq
if __name__ == "__main__":
a = "AGGTAB"
b = "GXTXAYB"
expected_ln = 4
expected_subseq = "GTAB"
ln, subseq = longest_common_subsequence(a, b)
print("len =", ln, ", sub-sequence =", subseq)
import doctest
doctest.testmod()
| """
LCS Problem Statement: Given two sequences, find the length of longest subsequence
present in both of them. A subsequence is a sequence that appears in the same relative
order, but not necessarily continuous.
Example:"abc", "abg" are subsequences of "abcdefgh".
"""
def longest_common_subsequence(x: str, y: str):
"""
Finds the longest common subsequence between two strings. Also returns the
The subsequence found
Parameters
----------
x: str, one of the strings
y: str, the other string
Returns
-------
L[m][n]: int, the length of the longest subsequence. Also equal to len(seq)
Seq: str, the subsequence found
>>> longest_common_subsequence("programming", "gaming")
(6, 'gaming')
>>> longest_common_subsequence("physics", "smartphone")
(2, 'ph')
>>> longest_common_subsequence("computer", "food")
(1, 'o')
"""
# find the length of strings
assert x is not None
assert y is not None
m = len(x)
n = len(y)
# declaring the array for storing the dp values
L = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
match = 1
else:
match = 0
L[i][j] = max(L[i - 1][j], L[i][j - 1], L[i - 1][j - 1] + match)
seq = ""
i, j = m, n
while i > 0 and j > 0:
if x[i - 1] == y[j - 1]:
match = 1
else:
match = 0
if L[i][j] == L[i - 1][j - 1] + match:
if match == 1:
seq = x[i - 1] + seq
i -= 1
j -= 1
elif L[i][j] == L[i - 1][j]:
i -= 1
else:
j -= 1
return L[m][n], seq
if __name__ == "__main__":
a = "AGGTAB"
b = "GXTXAYB"
expected_ln = 4
expected_subseq = "GTAB"
ln, subseq = longest_common_subsequence(a, b)
print("len =", ln, ", sub-sequence =", subseq)
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Program to join a list of strings with a given separator
"""
def join(separator: str, separated: list[str]) -> str:
"""
>>> join("", ["a", "b", "c", "d"])
'abcd'
>>> join("#", ["a", "b", "c", "d"])
'a#b#c#d'
>>> join("#", "a")
'a'
>>> join(" ", ["You", "are", "amazing!"])
'You are amazing!'
>>> join("#", ["a", "b", "c", 1])
Traceback (most recent call last):
...
Exception: join() accepts only strings to be joined
"""
joined = ""
for word_or_phrase in separated:
if not isinstance(word_or_phrase, str):
raise Exception("join() accepts only strings to be joined")
joined += word_or_phrase + separator
return joined.strip(separator)
if __name__ == "__main__":
from doctest import testmod
testmod()
| """
Program to join a list of strings with a given separator
"""
def join(separator: str, separated: list[str]) -> str:
"""
>>> join("", ["a", "b", "c", "d"])
'abcd'
>>> join("#", ["a", "b", "c", "d"])
'a#b#c#d'
>>> join("#", "a")
'a'
>>> join(" ", ["You", "are", "amazing!"])
'You are amazing!'
>>> join("#", ["a", "b", "c", 1])
Traceback (most recent call last):
...
Exception: join() accepts only strings to be joined
"""
joined = ""
for word_or_phrase in separated:
if not isinstance(word_or_phrase, str):
raise Exception("join() accepts only strings to be joined")
joined += word_or_phrase + separator
return joined.strip(separator)
if __name__ == "__main__":
from doctest import testmod
testmod()
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import sys
"""
Dynamic Programming
Implementation of Matrix Chain Multiplication
Time Complexity: O(n^3)
Space Complexity: O(n^2)
"""
def MatrixChainOrder(array):
N = len(array)
Matrix = [[0 for x in range(N)] for x in range(N)]
Sol = [[0 for x in range(N)] for x in range(N)]
for ChainLength in range(2, N):
for a in range(1, N - ChainLength + 1):
b = a + ChainLength - 1
Matrix[a][b] = sys.maxsize
for c in range(a, b):
cost = (
Matrix[a][c] + Matrix[c + 1][b] + array[a - 1] * array[c] * array[b]
)
if cost < Matrix[a][b]:
Matrix[a][b] = cost
Sol[a][b] = c
return Matrix, Sol
# Print order of matrix with Ai as Matrix
def PrintOptimalSolution(OptimalSolution, i, j):
if i == j:
print("A" + str(i), end=" ")
else:
print("(", end=" ")
PrintOptimalSolution(OptimalSolution, i, OptimalSolution[i][j])
PrintOptimalSolution(OptimalSolution, OptimalSolution[i][j] + 1, j)
print(")", end=" ")
def main():
array = [30, 35, 15, 5, 10, 20, 25]
n = len(array)
# Size of matrix created from above array will be
# 30*35 35*15 15*5 5*10 10*20 20*25
Matrix, OptimalSolution = MatrixChainOrder(array)
print("No. of Operation required: " + str(Matrix[1][n - 1]))
PrintOptimalSolution(OptimalSolution, 1, n - 1)
if __name__ == "__main__":
main()
| import sys
"""
Dynamic Programming
Implementation of Matrix Chain Multiplication
Time Complexity: O(n^3)
Space Complexity: O(n^2)
"""
def MatrixChainOrder(array):
N = len(array)
Matrix = [[0 for x in range(N)] for x in range(N)]
Sol = [[0 for x in range(N)] for x in range(N)]
for ChainLength in range(2, N):
for a in range(1, N - ChainLength + 1):
b = a + ChainLength - 1
Matrix[a][b] = sys.maxsize
for c in range(a, b):
cost = (
Matrix[a][c] + Matrix[c + 1][b] + array[a - 1] * array[c] * array[b]
)
if cost < Matrix[a][b]:
Matrix[a][b] = cost
Sol[a][b] = c
return Matrix, Sol
# Print order of matrix with Ai as Matrix
def PrintOptimalSolution(OptimalSolution, i, j):
if i == j:
print("A" + str(i), end=" ")
else:
print("(", end=" ")
PrintOptimalSolution(OptimalSolution, i, OptimalSolution[i][j])
PrintOptimalSolution(OptimalSolution, OptimalSolution[i][j] + 1, j)
print(")", end=" ")
def main():
array = [30, 35, 15, 5, 10, 20, 25]
n = len(array)
# Size of matrix created from above array will be
# 30*35 35*15 15*5 5*10 10*20 20*25
Matrix, OptimalSolution = MatrixChainOrder(array)
print("No. of Operation required: " + str(Matrix[1][n - 1]))
PrintOptimalSolution(OptimalSolution, 1, n - 1)
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| def isSumSubset(arr, arrLen, requiredSum):
"""
>>> isSumSubset([2, 4, 6, 8], 4, 5)
False
>>> isSumSubset([2, 4, 6, 8], 4, 14)
True
"""
# a subset value says 1 if that subset sum can be formed else 0
# initially no subsets can be formed hence False/0
subset = [[False for i in range(requiredSum + 1)] for i in range(arrLen + 1)]
# for each arr value, a sum of zero(0) can be formed by not taking any element
# hence True/1
for i in range(arrLen + 1):
subset[i][0] = True
# sum is not zero and set is empty then false
for i in range(1, requiredSum + 1):
subset[0][i] = False
for i in range(1, arrLen + 1):
for j in range(1, requiredSum + 1):
if arr[i - 1] > j:
subset[i][j] = subset[i - 1][j]
if arr[i - 1] <= j:
subset[i][j] = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]]
# uncomment to print the subset
# for i in range(arrLen+1):
# print(subset[i])
print(subset[arrLen][requiredSum])
if __name__ == "__main__":
import doctest
doctest.testmod()
| def isSumSubset(arr, arrLen, requiredSum):
"""
>>> isSumSubset([2, 4, 6, 8], 4, 5)
False
>>> isSumSubset([2, 4, 6, 8], 4, 14)
True
"""
# a subset value says 1 if that subset sum can be formed else 0
# initially no subsets can be formed hence False/0
subset = [[False for i in range(requiredSum + 1)] for i in range(arrLen + 1)]
# for each arr value, a sum of zero(0) can be formed by not taking any element
# hence True/1
for i in range(arrLen + 1):
subset[i][0] = True
# sum is not zero and set is empty then false
for i in range(1, requiredSum + 1):
subset[0][i] = False
for i in range(1, arrLen + 1):
for j in range(1, requiredSum + 1):
if arr[i - 1] > j:
subset[i][j] = subset[i - 1][j]
if arr[i - 1] <= j:
subset[i][j] = subset[i - 1][j] or subset[i - 1][j - arr[i - 1]]
# uncomment to print the subset
# for i in range(arrLen+1):
# print(subset[i])
print(subset[arrLen][requiredSum])
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/bin/sh
#
# An example hook script to prepare the commit log message.
# Called by "git commit" with the name of the file that has the
# commit message, followed by the description of the commit
# message's source. The hook's purpose is to edit the commit
# message file. If the hook fails with a non-zero status,
# the commit is aborted.
#
# To enable this hook, rename this file to "prepare-commit-msg".
# This hook includes three examples. The first one removes the
# "# Please enter the commit message..." help message.
#
# The second includes the output of "git diff --name-status -r"
# into the message, just before the "git status" output. It is
# commented because it doesn't cope with --amend or with squashed
# commits.
#
# The third example adds a Signed-off-by line to the message, that can
# still be edited. This is rarely a good idea.
COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3
/usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE"
# case "$COMMIT_SOURCE,$SHA1" in
# ,|template,)
# /usr/bin/perl -i.bak -pe '
# print "\n" . `git diff --cached --name-status -r`
# if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;;
# *) ;;
# esac
# SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
# git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE"
# if test -z "$COMMIT_SOURCE"
# then
# /usr/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE"
# fi
| #!/bin/sh
#
# An example hook script to prepare the commit log message.
# Called by "git commit" with the name of the file that has the
# commit message, followed by the description of the commit
# message's source. The hook's purpose is to edit the commit
# message file. If the hook fails with a non-zero status,
# the commit is aborted.
#
# To enable this hook, rename this file to "prepare-commit-msg".
# This hook includes three examples. The first one removes the
# "# Please enter the commit message..." help message.
#
# The second includes the output of "git diff --name-status -r"
# into the message, just before the "git status" output. It is
# commented because it doesn't cope with --amend or with squashed
# commits.
#
# The third example adds a Signed-off-by line to the message, that can
# still be edited. This is rarely a good idea.
COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3
/usr/bin/perl -i.bak -ne 'print unless(m/^. Please enter the commit message/..m/^#$/)' "$COMMIT_MSG_FILE"
# case "$COMMIT_SOURCE,$SHA1" in
# ,|template,)
# /usr/bin/perl -i.bak -pe '
# print "\n" . `git diff --cached --name-status -r`
# if /^#/ && $first++ == 0' "$COMMIT_MSG_FILE" ;;
# *) ;;
# esac
# SOB=$(git var GIT_COMMITTER_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
# git interpret-trailers --in-place --trailer "$SOB" "$COMMIT_MSG_FILE"
# if test -z "$COMMIT_SOURCE"
# then
# /usr/bin/perl -i.bak -pe 'print "\n" if !$first_line++' "$COMMIT_MSG_FILE"
# fi
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Description
The Koch snowflake is a fractal curve and one of the earliest fractals to
have been described. The Koch snowflake can be built up iteratively, in a
sequence of stages. The first stage is an equilateral triangle, and each
successive stage is formed by adding outward bends to each side of the
previous stage, making smaller equilateral triangles.
This can be achieved through the following steps for each line:
1. divide the line segment into three segments of equal length.
2. draw an equilateral triangle that has the middle segment from step 1
as its base and points outward.
3. remove the line segment that is the base of the triangle from step 2.
(description adapted from https://en.wikipedia.org/wiki/Koch_snowflake )
(for a more detailed explanation and an implementation in the
Processing language, see https://natureofcode.com/book/chapter-8-fractals/
#84-the-koch-curve-and-the-arraylist-technique )
Requirements (pip):
- matplotlib
- numpy
"""
from __future__ import annotations
import matplotlib.pyplot as plt # type: ignore
import numpy
# initial triangle of Koch snowflake
VECTOR_1 = numpy.array([0, 0])
VECTOR_2 = numpy.array([0.5, 0.8660254])
VECTOR_3 = numpy.array([1, 0])
INITIAL_VECTORS = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1]
# uncomment for simple Koch curve instead of Koch snowflake
# INITIAL_VECTORS = [VECTOR_1, VECTOR_3]
def iterate(initial_vectors: list[numpy.ndarray], steps: int) -> list[numpy.ndarray]:
"""
Go through the number of iterations determined by the argument "steps".
Be careful with high values (above 5) since the time to calculate increases
exponentially.
>>> iterate([numpy.array([0, 0]), numpy.array([1, 0])], 1)
[array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \
0.28867513]), array([0.66666667, 0. ]), array([1, 0])]
"""
vectors = initial_vectors
for i in range(steps):
vectors = iteration_step(vectors)
return vectors
def iteration_step(vectors: list[numpy.ndarray]) -> list[numpy.ndarray]:
"""
Loops through each pair of adjacent vectors. Each line between two adjacent
vectors is divided into 4 segments by adding 3 additional vectors in-between
the original two vectors. The vector in the middle is constructed through a
60 degree rotation so it is bent outwards.
>>> iteration_step([numpy.array([0, 0]), numpy.array([1, 0])])
[array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \
0.28867513]), array([0.66666667, 0. ]), array([1, 0])]
"""
new_vectors = []
for i, start_vector in enumerate(vectors[:-1]):
end_vector = vectors[i + 1]
new_vectors.append(start_vector)
difference_vector = end_vector - start_vector
new_vectors.append(start_vector + difference_vector / 3)
new_vectors.append(
start_vector + difference_vector / 3 + rotate(difference_vector / 3, 60)
)
new_vectors.append(start_vector + difference_vector * 2 / 3)
new_vectors.append(vectors[-1])
return new_vectors
def rotate(vector: numpy.ndarray, angle_in_degrees: float) -> numpy.ndarray:
"""
Standard rotation of a 2D vector with a rotation matrix
(see https://en.wikipedia.org/wiki/Rotation_matrix )
>>> rotate(numpy.array([1, 0]), 60)
array([0.5 , 0.8660254])
>>> rotate(numpy.array([1, 0]), 90)
array([6.123234e-17, 1.000000e+00])
"""
theta = numpy.radians(angle_in_degrees)
c, s = numpy.cos(theta), numpy.sin(theta)
rotation_matrix = numpy.array(((c, -s), (s, c)))
return numpy.dot(rotation_matrix, vector)
def plot(vectors: list[numpy.ndarray]) -> None:
"""
Utility function to plot the vectors using matplotlib.pyplot
No doctest was implemented since this function does not have a return value
"""
# avoid stretched display of graph
axes = plt.gca()
axes.set_aspect("equal")
# matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all
# y-coordinates as inputs, which are constructed from the vector-list using
# zip()
x_coordinates, y_coordinates = zip(*vectors)
plt.plot(x_coordinates, y_coordinates)
plt.show()
if __name__ == "__main__":
import doctest
doctest.testmod()
processed_vectors = iterate(INITIAL_VECTORS, 5)
plot(processed_vectors)
| """
Description
The Koch snowflake is a fractal curve and one of the earliest fractals to
have been described. The Koch snowflake can be built up iteratively, in a
sequence of stages. The first stage is an equilateral triangle, and each
successive stage is formed by adding outward bends to each side of the
previous stage, making smaller equilateral triangles.
This can be achieved through the following steps for each line:
1. divide the line segment into three segments of equal length.
2. draw an equilateral triangle that has the middle segment from step 1
as its base and points outward.
3. remove the line segment that is the base of the triangle from step 2.
(description adapted from https://en.wikipedia.org/wiki/Koch_snowflake )
(for a more detailed explanation and an implementation in the
Processing language, see https://natureofcode.com/book/chapter-8-fractals/
#84-the-koch-curve-and-the-arraylist-technique )
Requirements (pip):
- matplotlib
- numpy
"""
from __future__ import annotations
import matplotlib.pyplot as plt # type: ignore
import numpy
# initial triangle of Koch snowflake
VECTOR_1 = numpy.array([0, 0])
VECTOR_2 = numpy.array([0.5, 0.8660254])
VECTOR_3 = numpy.array([1, 0])
INITIAL_VECTORS = [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1]
# uncomment for simple Koch curve instead of Koch snowflake
# INITIAL_VECTORS = [VECTOR_1, VECTOR_3]
def iterate(initial_vectors: list[numpy.ndarray], steps: int) -> list[numpy.ndarray]:
"""
Go through the number of iterations determined by the argument "steps".
Be careful with high values (above 5) since the time to calculate increases
exponentially.
>>> iterate([numpy.array([0, 0]), numpy.array([1, 0])], 1)
[array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \
0.28867513]), array([0.66666667, 0. ]), array([1, 0])]
"""
vectors = initial_vectors
for i in range(steps):
vectors = iteration_step(vectors)
return vectors
def iteration_step(vectors: list[numpy.ndarray]) -> list[numpy.ndarray]:
"""
Loops through each pair of adjacent vectors. Each line between two adjacent
vectors is divided into 4 segments by adding 3 additional vectors in-between
the original two vectors. The vector in the middle is constructed through a
60 degree rotation so it is bent outwards.
>>> iteration_step([numpy.array([0, 0]), numpy.array([1, 0])])
[array([0, 0]), array([0.33333333, 0. ]), array([0.5 , \
0.28867513]), array([0.66666667, 0. ]), array([1, 0])]
"""
new_vectors = []
for i, start_vector in enumerate(vectors[:-1]):
end_vector = vectors[i + 1]
new_vectors.append(start_vector)
difference_vector = end_vector - start_vector
new_vectors.append(start_vector + difference_vector / 3)
new_vectors.append(
start_vector + difference_vector / 3 + rotate(difference_vector / 3, 60)
)
new_vectors.append(start_vector + difference_vector * 2 / 3)
new_vectors.append(vectors[-1])
return new_vectors
def rotate(vector: numpy.ndarray, angle_in_degrees: float) -> numpy.ndarray:
"""
Standard rotation of a 2D vector with a rotation matrix
(see https://en.wikipedia.org/wiki/Rotation_matrix )
>>> rotate(numpy.array([1, 0]), 60)
array([0.5 , 0.8660254])
>>> rotate(numpy.array([1, 0]), 90)
array([6.123234e-17, 1.000000e+00])
"""
theta = numpy.radians(angle_in_degrees)
c, s = numpy.cos(theta), numpy.sin(theta)
rotation_matrix = numpy.array(((c, -s), (s, c)))
return numpy.dot(rotation_matrix, vector)
def plot(vectors: list[numpy.ndarray]) -> None:
"""
Utility function to plot the vectors using matplotlib.pyplot
No doctest was implemented since this function does not have a return value
"""
# avoid stretched display of graph
axes = plt.gca()
axes.set_aspect("equal")
# matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all
# y-coordinates as inputs, which are constructed from the vector-list using
# zip()
x_coordinates, y_coordinates = zip(*vectors)
plt.plot(x_coordinates, y_coordinates)
plt.show()
if __name__ == "__main__":
import doctest
doctest.testmod()
processed_vectors = iterate(INITIAL_VECTORS, 5)
plot(processed_vectors)
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 5: https://projecteuler.net/problem=5
Smallest multiple
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is _evenly divisible_ by all
of the numbers from 1 to 20?
References:
- https://en.wiktionary.org/wiki/evenly_divisible
"""
def solution(n: int = 20) -> int:
"""
Returns the smallest positive number that is evenly divisible (divisible
with no remainder) by all of the numbers from 1 to n.
>>> solution(10)
2520
>>> solution(15)
360360
>>> solution(22)
232792560
>>> solution(3.4)
6
>>> solution(0)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater than or equal to one.
>>> solution(-17)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater than or equal to one.
>>> solution([])
Traceback (most recent call last):
...
TypeError: Parameter n must be int or castable to int.
>>> solution("asd")
Traceback (most recent call last):
...
TypeError: Parameter n must be int or castable to int.
"""
try:
n = int(n)
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or castable to int.")
if n <= 0:
raise ValueError("Parameter n must be greater than or equal to one.")
i = 0
while 1:
i += n * (n - 1)
nfound = 0
for j in range(2, n):
if i % j != 0:
nfound = 1
break
if nfound == 0:
if i == 0:
i = 1
return i
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 5: https://projecteuler.net/problem=5
Smallest multiple
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is _evenly divisible_ by all
of the numbers from 1 to 20?
References:
- https://en.wiktionary.org/wiki/evenly_divisible
"""
def solution(n: int = 20) -> int:
"""
Returns the smallest positive number that is evenly divisible (divisible
with no remainder) by all of the numbers from 1 to n.
>>> solution(10)
2520
>>> solution(15)
360360
>>> solution(22)
232792560
>>> solution(3.4)
6
>>> solution(0)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater than or equal to one.
>>> solution(-17)
Traceback (most recent call last):
...
ValueError: Parameter n must be greater than or equal to one.
>>> solution([])
Traceback (most recent call last):
...
TypeError: Parameter n must be int or castable to int.
>>> solution("asd")
Traceback (most recent call last):
...
TypeError: Parameter n must be int or castable to int.
"""
try:
n = int(n)
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or castable to int.")
if n <= 0:
raise ValueError("Parameter n must be greater than or equal to one.")
i = 0
while 1:
i += n * (n - 1)
nfound = 0
for j in range(2, n):
if i % j != 0:
nfound = 1
break
if nfound == 0:
if i == 0:
i = 1
return i
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Author: Phyllipe Bezerra (https://github.com/pmba)
clothes = {
0: "underwear",
1: "pants",
2: "belt",
3: "suit",
4: "shoe",
5: "socks",
6: "shirt",
7: "tie",
8: "watch",
}
graph = [[1, 4], [2, 4], [3], [], [], [4], [2, 7], [3], []]
visited = [0 for x in range(len(graph))]
stack = []
def print_stack(stack, clothes):
order = 1
while stack:
current_clothing = stack.pop()
print(order, clothes[current_clothing])
order += 1
def depth_first_search(u, visited, graph):
visited[u] = 1
for v in graph[u]:
if not visited[v]:
depth_first_search(v, visited, graph)
stack.append(u)
def topological_sort(graph, visited):
for v in range(len(graph)):
if not visited[v]:
depth_first_search(v, visited, graph)
if __name__ == "__main__":
topological_sort(graph, visited)
print(stack)
print_stack(stack, clothes)
| # Author: Phyllipe Bezerra (https://github.com/pmba)
clothes = {
0: "underwear",
1: "pants",
2: "belt",
3: "suit",
4: "shoe",
5: "socks",
6: "shirt",
7: "tie",
8: "watch",
}
graph = [[1, 4], [2, 4], [3], [], [], [4], [2, 7], [3], []]
visited = [0 for x in range(len(graph))]
stack = []
def print_stack(stack, clothes):
order = 1
while stack:
current_clothing = stack.pop()
print(order, clothes[current_clothing])
order += 1
def depth_first_search(u, visited, graph):
visited[u] = 1
for v in graph[u]:
if not visited[v]:
depth_first_search(v, visited, graph)
stack.append(u)
def topological_sort(graph, visited):
for v in range(len(graph)):
if not visited[v]:
depth_first_search(v, visited, graph)
if __name__ == "__main__":
topological_sort(graph, visited)
print(stack)
print_stack(stack, clothes)
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
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| < 1000 and |b| < 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(k: int) -> bool:
"""
Determine if a number is prime
>>> is_prime(10)
False
>>> is_prime(11)
True
"""
if k < 2 or k % 2 == 0:
return False
elif k == 2:
return True
else:
for x in range(3, int(math.sqrt(k) + 1), 2):
if k % x == 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| < 1000 and |b| < 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(k: int) -> bool:
"""
Determine if a number is prime
>>> is_prime(10)
False
>>> is_prime(11)
True
"""
if k < 2 or k % 2 == 0:
return False
elif k == 2:
return True
else:
for x in range(3, int(math.sqrt(k) + 1), 2):
if k % x == 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 | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import numpy as np
def power_iteration(
input_matrix: np.ndarray,
vector: np.ndarray,
error_tol: float = 1e-12,
max_iterations: int = 100,
) -> tuple[float, np.ndarray]:
"""
Power Iteration.
Find the largest eignevalue and corresponding eigenvector
of matrix input_matrix given a random vector in the same space.
Will work so long as vector has component of largest eigenvector.
input_matrix must be symmetric.
Input
input_matrix: input matrix whose largest eigenvalue we will find.
Numpy array. np.shape(input_matrix) == (N,N).
vector: random initial vector in same space as matrix.
Numpy array. np.shape(vector) == (N,) or (N,1)
Output
largest_eigenvalue: largest eigenvalue of the matrix input_matrix.
Float. Scalar.
largest_eigenvector: eigenvector corresponding to largest_eigenvalue.
Numpy array. np.shape(largest_eigenvector) == (N,) or (N,1).
>>> import numpy as np
>>> input_matrix = np.array([
... [41, 4, 20],
... [ 4, 26, 30],
... [20, 30, 50]
... ])
>>> vector = np.array([41,4,20])
>>> power_iteration(input_matrix,vector)
(79.66086378788381, array([0.44472726, 0.46209842, 0.76725662]))
"""
# Ensure matrix is square.
assert np.shape(input_matrix)[0] == np.shape(input_matrix)[1]
# Ensure proper dimensionality.
assert np.shape(input_matrix)[0] == np.shape(vector)[0]
# Set convergence to False. Will define convergence when we exceed max_iterations
# or when we have small changes from one iteration to next.
convergence = False
lamda_previous = 0
iterations = 0
error = 1e12
while not convergence:
# Multiple matrix by the vector.
w = np.dot(input_matrix, vector)
# Normalize the resulting output vector.
vector = w / np.linalg.norm(w)
# Find rayleigh quotient
# (faster than usual b/c we know vector is normalized already)
lamda = np.dot(vector.T, np.dot(input_matrix, vector))
# Check convergence.
error = np.abs(lamda - lamda_previous) / lamda
iterations += 1
if error <= error_tol or iterations >= max_iterations:
convergence = True
lamda_previous = lamda
return lamda, vector
def test_power_iteration() -> None:
"""
>>> test_power_iteration() # self running tests
"""
# Our implementation.
input_matrix = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]])
vector = np.array([41, 4, 20])
eigen_value, eigen_vector = power_iteration(input_matrix, vector)
# Numpy implementation.
# Get eigen values and eigen vectors using built in numpy
# eigh (eigh used for symmetric or hermetian matrices).
eigen_values, eigen_vectors = np.linalg.eigh(input_matrix)
# Last eigen value is the maximum one.
eigen_value_max = eigen_values[-1]
# Last column in this matrix is eigen vector corresponding to largest eigen value.
eigen_vector_max = eigen_vectors[:, -1]
# Check our implementation and numpy gives close answers.
assert np.abs(eigen_value - eigen_value_max) <= 1e-6
# Take absolute values element wise of each eigenvector.
# as they are only unique to a minus sign.
assert np.linalg.norm(np.abs(eigen_vector) - np.abs(eigen_vector_max)) <= 1e-6
if __name__ == "__main__":
import doctest
doctest.testmod()
test_power_iteration()
| import numpy as np
def power_iteration(
input_matrix: np.ndarray,
vector: np.ndarray,
error_tol: float = 1e-12,
max_iterations: int = 100,
) -> tuple[float, np.ndarray]:
"""
Power Iteration.
Find the largest eignevalue and corresponding eigenvector
of matrix input_matrix given a random vector in the same space.
Will work so long as vector has component of largest eigenvector.
input_matrix must be symmetric.
Input
input_matrix: input matrix whose largest eigenvalue we will find.
Numpy array. np.shape(input_matrix) == (N,N).
vector: random initial vector in same space as matrix.
Numpy array. np.shape(vector) == (N,) or (N,1)
Output
largest_eigenvalue: largest eigenvalue of the matrix input_matrix.
Float. Scalar.
largest_eigenvector: eigenvector corresponding to largest_eigenvalue.
Numpy array. np.shape(largest_eigenvector) == (N,) or (N,1).
>>> import numpy as np
>>> input_matrix = np.array([
... [41, 4, 20],
... [ 4, 26, 30],
... [20, 30, 50]
... ])
>>> vector = np.array([41,4,20])
>>> power_iteration(input_matrix,vector)
(79.66086378788381, array([0.44472726, 0.46209842, 0.76725662]))
"""
# Ensure matrix is square.
assert np.shape(input_matrix)[0] == np.shape(input_matrix)[1]
# Ensure proper dimensionality.
assert np.shape(input_matrix)[0] == np.shape(vector)[0]
# Set convergence to False. Will define convergence when we exceed max_iterations
# or when we have small changes from one iteration to next.
convergence = False
lamda_previous = 0
iterations = 0
error = 1e12
while not convergence:
# Multiple matrix by the vector.
w = np.dot(input_matrix, vector)
# Normalize the resulting output vector.
vector = w / np.linalg.norm(w)
# Find rayleigh quotient
# (faster than usual b/c we know vector is normalized already)
lamda = np.dot(vector.T, np.dot(input_matrix, vector))
# Check convergence.
error = np.abs(lamda - lamda_previous) / lamda
iterations += 1
if error <= error_tol or iterations >= max_iterations:
convergence = True
lamda_previous = lamda
return lamda, vector
def test_power_iteration() -> None:
"""
>>> test_power_iteration() # self running tests
"""
# Our implementation.
input_matrix = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]])
vector = np.array([41, 4, 20])
eigen_value, eigen_vector = power_iteration(input_matrix, vector)
# Numpy implementation.
# Get eigen values and eigen vectors using built in numpy
# eigh (eigh used for symmetric or hermetian matrices).
eigen_values, eigen_vectors = np.linalg.eigh(input_matrix)
# Last eigen value is the maximum one.
eigen_value_max = eigen_values[-1]
# Last column in this matrix is eigen vector corresponding to largest eigen value.
eigen_vector_max = eigen_vectors[:, -1]
# Check our implementation and numpy gives close answers.
assert np.abs(eigen_value - eigen_value_max) <= 1e-6
# Take absolute values element wise of each eigenvector.
# as they are only unique to a minus sign.
assert np.linalg.norm(np.abs(eigen_vector) - np.abs(eigen_vector_max)) <= 1e-6
if __name__ == "__main__":
import doctest
doctest.testmod()
test_power_iteration()
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Is IP v4 address valid?
A valid IP address must be four octets in the form of A.B.C.D,
where A,B,C and D are numbers from 0-254
for example: 192.168.23.1, 172.254.254.254 are valid IP address
192.168.255.0, 255.192.3.121 are invalid IP address
"""
def is_ip_v4_address_valid(ip_v4_address: str) -> bool:
"""
print "Valid IP address" If IP is valid.
or
print "Invalid IP address" If IP is invalid.
>>> is_ip_v4_address_valid("192.168.0.23")
True
>>> is_ip_v4_address_valid("192.255.15.8")
False
>>> is_ip_v4_address_valid("172.100.0.8")
True
>>> is_ip_v4_address_valid("254.255.0.255")
False
>>> is_ip_v4_address_valid("1.2.33333333.4")
False
>>> is_ip_v4_address_valid("1.2.-3.4")
False
>>> is_ip_v4_address_valid("1.2.3")
False
>>> is_ip_v4_address_valid("1.2.3.4.5")
False
>>> is_ip_v4_address_valid("1.2.A.4")
False
>>> is_ip_v4_address_valid("0.0.0.0")
True
>>> is_ip_v4_address_valid("1.2.3.")
False
"""
octets = [int(i) for i in ip_v4_address.split(".") if i.isdigit()]
return len(octets) == 4 and all(0 <= int(octet) <= 254 for octet in octets)
if __name__ == "__main__":
ip = input().strip()
valid_or_invalid = "valid" if is_ip_v4_address_valid(ip) else "invalid"
print(f"{ip} is a {valid_or_invalid} IP v4 address.")
| """
Is IP v4 address valid?
A valid IP address must be four octets in the form of A.B.C.D,
where A,B,C and D are numbers from 0-254
for example: 192.168.23.1, 172.254.254.254 are valid IP address
192.168.255.0, 255.192.3.121 are invalid IP address
"""
def is_ip_v4_address_valid(ip_v4_address: str) -> bool:
"""
print "Valid IP address" If IP is valid.
or
print "Invalid IP address" If IP is invalid.
>>> is_ip_v4_address_valid("192.168.0.23")
True
>>> is_ip_v4_address_valid("192.255.15.8")
False
>>> is_ip_v4_address_valid("172.100.0.8")
True
>>> is_ip_v4_address_valid("254.255.0.255")
False
>>> is_ip_v4_address_valid("1.2.33333333.4")
False
>>> is_ip_v4_address_valid("1.2.-3.4")
False
>>> is_ip_v4_address_valid("1.2.3")
False
>>> is_ip_v4_address_valid("1.2.3.4.5")
False
>>> is_ip_v4_address_valid("1.2.A.4")
False
>>> is_ip_v4_address_valid("0.0.0.0")
True
>>> is_ip_v4_address_valid("1.2.3.")
False
"""
octets = [int(i) for i in ip_v4_address.split(".") if i.isdigit()]
return len(octets) == 4 and all(0 <= int(octet) <= 254 for octet in octets)
if __name__ == "__main__":
ip = input().strip()
valid_or_invalid = "valid" if is_ip_v4_address_valid(ip) else "invalid"
print(f"{ip} is a {valid_or_invalid} IP v4 address.")
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import unittest
from knapsack import greedy_knapsack as kp
class TestClass(unittest.TestCase):
"""
Test cases for knapsack
"""
def test_sorted(self):
"""
kp.calc_profit takes the required argument (profit, weight, max_weight)
and returns whether the answer matches to the expected ones
"""
profit = [10, 20, 30, 40, 50, 60]
weight = [2, 4, 6, 8, 10, 12]
max_weight = 100
self.assertEqual(kp.calc_profit(profit, weight, max_weight), 210)
def test_negative_max_weight(self):
"""
Returns ValueError for any negative max_weight value
:return: ValueError
"""
# profit = [10, 20, 30, 40, 50, 60]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = -15
self.assertRaisesRegex(ValueError, "max_weight must greater than zero.")
def test_negative_profit_value(self):
"""
Returns ValueError for any negative profit value in the list
:return: ValueError
"""
# profit = [10, -20, 30, 40, 50, 60]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = 15
self.assertRaisesRegex(ValueError, "Weight can not be negative.")
def test_negative_weight_value(self):
"""
Returns ValueError for any negative weight value in the list
:return: ValueError
"""
# profit = [10, 20, 30, 40, 50, 60]
# weight = [2, -4, 6, -8, 10, 12]
# max_weight = 15
self.assertRaisesRegex(ValueError, "Profit can not be negative.")
def test_null_max_weight(self):
"""
Returns ValueError for any zero max_weight value
:return: ValueError
"""
# profit = [10, 20, 30, 40, 50, 60]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = null
self.assertRaisesRegex(ValueError, "max_weight must greater than zero.")
def test_unequal_list_length(self):
"""
Returns IndexError if length of lists (profit and weight) are unequal.
:return: IndexError
"""
# profit = [10, 20, 30, 40, 50]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = 100
self.assertRaisesRegex(
IndexError, "The length of profit and weight must be same."
)
if __name__ == "__main__":
unittest.main()
| import unittest
from knapsack import greedy_knapsack as kp
class TestClass(unittest.TestCase):
"""
Test cases for knapsack
"""
def test_sorted(self):
"""
kp.calc_profit takes the required argument (profit, weight, max_weight)
and returns whether the answer matches to the expected ones
"""
profit = [10, 20, 30, 40, 50, 60]
weight = [2, 4, 6, 8, 10, 12]
max_weight = 100
self.assertEqual(kp.calc_profit(profit, weight, max_weight), 210)
def test_negative_max_weight(self):
"""
Returns ValueError for any negative max_weight value
:return: ValueError
"""
# profit = [10, 20, 30, 40, 50, 60]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = -15
self.assertRaisesRegex(ValueError, "max_weight must greater than zero.")
def test_negative_profit_value(self):
"""
Returns ValueError for any negative profit value in the list
:return: ValueError
"""
# profit = [10, -20, 30, 40, 50, 60]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = 15
self.assertRaisesRegex(ValueError, "Weight can not be negative.")
def test_negative_weight_value(self):
"""
Returns ValueError for any negative weight value in the list
:return: ValueError
"""
# profit = [10, 20, 30, 40, 50, 60]
# weight = [2, -4, 6, -8, 10, 12]
# max_weight = 15
self.assertRaisesRegex(ValueError, "Profit can not be negative.")
def test_null_max_weight(self):
"""
Returns ValueError for any zero max_weight value
:return: ValueError
"""
# profit = [10, 20, 30, 40, 50, 60]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = null
self.assertRaisesRegex(ValueError, "max_weight must greater than zero.")
def test_unequal_list_length(self):
"""
Returns IndexError if length of lists (profit and weight) are unequal.
:return: IndexError
"""
# profit = [10, 20, 30, 40, 50]
# weight = [2, 4, 6, 8, 10, 12]
# max_weight = 100
self.assertRaisesRegex(
IndexError, "The length of profit and weight must be same."
)
if __name__ == "__main__":
unittest.main()
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from typing import Callable
def bisection(function: Callable[[float], float], a: float, b: float) -> float:
"""
finds where function becomes 0 in [a,b] using bolzano
>>> bisection(lambda x: x ** 3 - 1, -5, 5)
1.0000000149011612
>>> bisection(lambda x: x ** 3 - 1, 2, 1000)
Traceback (most recent call last):
...
ValueError: could not find root in given interval.
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 0, 2)
1.0
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 2, 4)
3.0
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 4, 1000)
Traceback (most recent call last):
...
ValueError: could not find root in given interval.
"""
start: float = a
end: float = b
if function(a) == 0: # one of the a or b is a root for the function
return a
elif function(b) == 0:
return b
elif (
function(a) * function(b) > 0
): # if none of these are root and they are both positive or negative,
# then this algorithm can't find the root
raise ValueError("could not find root in given interval.")
else:
mid: float = start + (end - start) / 2.0
while abs(start - mid) > 10 ** -7: # until precisely equals to 10^-7
if function(mid) == 0:
return mid
elif function(mid) * function(start) < 0:
end = mid
else:
start = mid
mid = start + (end - start) / 2.0
return mid
def f(x: float) -> float:
return x ** 3 - 2 * x - 5
if __name__ == "__main__":
print(bisection(f, 1, 1000))
import doctest
doctest.testmod()
| from typing import Callable
def bisection(function: Callable[[float], float], a: float, b: float) -> float:
"""
finds where function becomes 0 in [a,b] using bolzano
>>> bisection(lambda x: x ** 3 - 1, -5, 5)
1.0000000149011612
>>> bisection(lambda x: x ** 3 - 1, 2, 1000)
Traceback (most recent call last):
...
ValueError: could not find root in given interval.
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 0, 2)
1.0
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 2, 4)
3.0
>>> bisection(lambda x: x ** 2 - 4 * x + 3, 4, 1000)
Traceback (most recent call last):
...
ValueError: could not find root in given interval.
"""
start: float = a
end: float = b
if function(a) == 0: # one of the a or b is a root for the function
return a
elif function(b) == 0:
return b
elif (
function(a) * function(b) > 0
): # if none of these are root and they are both positive or negative,
# then this algorithm can't find the root
raise ValueError("could not find root in given interval.")
else:
mid: float = start + (end - start) / 2.0
while abs(start - mid) > 10 ** -7: # until precisely equals to 10^-7
if function(mid) == 0:
return mid
elif function(mid) * function(start) < 0:
end = mid
else:
start = mid
mid = start + (end - start) / 2.0
return mid
def f(x: float) -> float:
return x ** 3 - 2 * x - 5
if __name__ == "__main__":
print(bisection(f, 1, 1000))
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 1: https://projecteuler.net/problem=1
Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def solution(n: int = 1000) -> int:
"""
Returns the sum of all the multiples of 3 or 5 below n.
>>> solution(3)
0
>>> solution(4)
3
>>> solution(10)
23
>>> solution(600)
83700
>>> solution(-7)
0
"""
return sum(e for e in range(3, n) if e % 3 == 0 or e % 5 == 0)
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 1: https://projecteuler.net/problem=1
Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def solution(n: int = 1000) -> int:
"""
Returns the sum of all the multiples of 3 or 5 below n.
>>> solution(3)
0
>>> solution(4)
3
>>> solution(10)
23
>>> solution(600)
83700
>>> solution(-7)
0
"""
return sum(e for e in range(3, n) if e % 3 == 0 or e % 5 == 0)
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 57: https://projecteuler.net/problem=57
It is possible to show that the square root of two can be expressed as an infinite
continued fraction.
sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + ...)))
By expanding this for the first four iterations, we get:
1 + 1 / 2 = 3 / 2 = 1.5
1 + 1 / (2 + 1 / 2} = 7 / 5 = 1.4
1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17 / 12 = 1.41666...
1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/ 29 = 1.41379...
The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion,
1393/985, is the first example where the number of digits in the numerator exceeds
the number of digits in the denominator.
In the first one-thousand expansions, how many fractions contain a numerator with
more digits than the denominator?
"""
def solution(n: int = 1000) -> int:
"""
returns number of fractions containing a numerator with more digits than
the denominator in the first n expansions.
>>> solution(14)
2
>>> solution(100)
15
>>> solution(10000)
1508
"""
prev_numerator, prev_denominator = 1, 1
result = []
for i in range(1, n + 1):
numerator = prev_numerator + 2 * prev_denominator
denominator = prev_numerator + prev_denominator
if len(str(numerator)) > len(str(denominator)):
result.append(i)
prev_numerator = numerator
prev_denominator = denominator
return len(result)
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 57: https://projecteuler.net/problem=57
It is possible to show that the square root of two can be expressed as an infinite
continued fraction.
sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + ...)))
By expanding this for the first four iterations, we get:
1 + 1 / 2 = 3 / 2 = 1.5
1 + 1 / (2 + 1 / 2} = 7 / 5 = 1.4
1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17 / 12 = 1.41666...
1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/ 29 = 1.41379...
The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion,
1393/985, is the first example where the number of digits in the numerator exceeds
the number of digits in the denominator.
In the first one-thousand expansions, how many fractions contain a numerator with
more digits than the denominator?
"""
def solution(n: int = 1000) -> int:
"""
returns number of fractions containing a numerator with more digits than
the denominator in the first n expansions.
>>> solution(14)
2
>>> solution(100)
15
>>> solution(10000)
1508
"""
prev_numerator, prev_denominator = 1, 1
result = []
for i in range(1, n + 1):
numerator = prev_numerator + 2 * prev_denominator
denominator = prev_numerator + prev_denominator
if len(str(numerator)) > len(str(denominator)):
result.append(i)
prev_numerator = numerator
prev_denominator = denominator
return len(result)
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
https://en.wikipedia.org/wiki/Best-first_search#Greedy_BFS
"""
from __future__ import annotations
Path = list[tuple[int, int]]
grid = [
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
]
delta = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right
class Node:
"""
>>> k = Node(0, 0, 4, 5, 0, None)
>>> k.calculate_heuristic()
9
>>> n = Node(1, 4, 3, 4, 2, None)
>>> n.calculate_heuristic()
2
>>> l = [k, n]
>>> n == l[0]
False
>>> l.sort()
>>> n == l[0]
True
"""
def __init__(
self,
pos_x: int,
pos_y: int,
goal_x: int,
goal_y: int,
g_cost: float,
parent: Node | None,
):
self.pos_x = pos_x
self.pos_y = pos_y
self.pos = (pos_y, pos_x)
self.goal_x = goal_x
self.goal_y = goal_y
self.g_cost = g_cost
self.parent = parent
self.f_cost = self.calculate_heuristic()
def calculate_heuristic(self) -> float:
"""
The heuristic here is the Manhattan Distance
Could elaborate to offer more than one choice
"""
dy = abs(self.pos_x - self.goal_x)
dx = abs(self.pos_y - self.goal_y)
return dx + dy
def __lt__(self, other) -> bool:
return self.f_cost < other.f_cost
class GreedyBestFirst:
"""
>>> gbf = GreedyBestFirst((0, 0), (len(grid) - 1, len(grid[0]) - 1))
>>> [x.pos for x in gbf.get_successors(gbf.start)]
[(1, 0), (0, 1)]
>>> (gbf.start.pos_y + delta[3][0], gbf.start.pos_x + delta[3][1])
(0, 1)
>>> (gbf.start.pos_y + delta[2][0], gbf.start.pos_x + delta[2][1])
(1, 0)
>>> gbf.retrace_path(gbf.start)
[(0, 0)]
>>> gbf.search() # doctest: +NORMALIZE_WHITESPACE
[(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (4, 1), (5, 1), (6, 1),
(6, 2), (6, 3), (5, 3), (5, 4), (5, 5), (6, 5), (6, 6)]
"""
def __init__(self, start: tuple[int, int], goal: tuple[int, int]):
self.start = Node(start[1], start[0], goal[1], goal[0], 0, None)
self.target = Node(goal[1], goal[0], goal[1], goal[0], 99999, None)
self.open_nodes = [self.start]
self.closed_nodes: list[Node] = []
self.reached = False
def search(self) -> Path | None:
"""
Search for the path,
if a path is not found, only the starting position is returned
"""
while self.open_nodes:
# Open Nodes are sorted using __lt__
self.open_nodes.sort()
current_node = self.open_nodes.pop(0)
if current_node.pos == self.target.pos:
self.reached = True
return self.retrace_path(current_node)
self.closed_nodes.append(current_node)
successors = self.get_successors(current_node)
for child_node in successors:
if child_node in self.closed_nodes:
continue
if child_node not in self.open_nodes:
self.open_nodes.append(child_node)
else:
# retrieve the best current path
better_node = self.open_nodes.pop(self.open_nodes.index(child_node))
if child_node.g_cost < better_node.g_cost:
self.open_nodes.append(child_node)
else:
self.open_nodes.append(better_node)
if not self.reached:
return [self.start.pos]
return None
def get_successors(self, parent: Node) -> list[Node]:
"""
Returns a list of successors (both in the grid and free spaces)
"""
successors = []
for action in delta:
pos_x = parent.pos_x + action[1]
pos_y = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(grid) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(
pos_x,
pos_y,
self.target.pos_y,
self.target.pos_x,
parent.g_cost + 1,
parent,
)
)
return successors
def retrace_path(self, node: Node | None) -> Path:
"""
Retrace the path from parents to parents until start node
"""
current_node = node
path = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x))
current_node = current_node.parent
path.reverse()
return path
if __name__ == "__main__":
init = (0, 0)
goal = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
print("------")
greedy_bf = GreedyBestFirst(init, goal)
path = greedy_bf.search()
if path:
for pos_x, pos_y in path:
grid[pos_x][pos_y] = 2
for elem in grid:
print(elem)
| """
https://en.wikipedia.org/wiki/Best-first_search#Greedy_BFS
"""
from __future__ import annotations
Path = list[tuple[int, int]]
grid = [
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
]
delta = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right
class Node:
"""
>>> k = Node(0, 0, 4, 5, 0, None)
>>> k.calculate_heuristic()
9
>>> n = Node(1, 4, 3, 4, 2, None)
>>> n.calculate_heuristic()
2
>>> l = [k, n]
>>> n == l[0]
False
>>> l.sort()
>>> n == l[0]
True
"""
def __init__(
self,
pos_x: int,
pos_y: int,
goal_x: int,
goal_y: int,
g_cost: float,
parent: Node | None,
):
self.pos_x = pos_x
self.pos_y = pos_y
self.pos = (pos_y, pos_x)
self.goal_x = goal_x
self.goal_y = goal_y
self.g_cost = g_cost
self.parent = parent
self.f_cost = self.calculate_heuristic()
def calculate_heuristic(self) -> float:
"""
The heuristic here is the Manhattan Distance
Could elaborate to offer more than one choice
"""
dy = abs(self.pos_x - self.goal_x)
dx = abs(self.pos_y - self.goal_y)
return dx + dy
def __lt__(self, other) -> bool:
return self.f_cost < other.f_cost
class GreedyBestFirst:
"""
>>> gbf = GreedyBestFirst((0, 0), (len(grid) - 1, len(grid[0]) - 1))
>>> [x.pos for x in gbf.get_successors(gbf.start)]
[(1, 0), (0, 1)]
>>> (gbf.start.pos_y + delta[3][0], gbf.start.pos_x + delta[3][1])
(0, 1)
>>> (gbf.start.pos_y + delta[2][0], gbf.start.pos_x + delta[2][1])
(1, 0)
>>> gbf.retrace_path(gbf.start)
[(0, 0)]
>>> gbf.search() # doctest: +NORMALIZE_WHITESPACE
[(0, 0), (1, 0), (2, 0), (3, 0), (3, 1), (4, 1), (5, 1), (6, 1),
(6, 2), (6, 3), (5, 3), (5, 4), (5, 5), (6, 5), (6, 6)]
"""
def __init__(self, start: tuple[int, int], goal: tuple[int, int]):
self.start = Node(start[1], start[0], goal[1], goal[0], 0, None)
self.target = Node(goal[1], goal[0], goal[1], goal[0], 99999, None)
self.open_nodes = [self.start]
self.closed_nodes: list[Node] = []
self.reached = False
def search(self) -> Path | None:
"""
Search for the path,
if a path is not found, only the starting position is returned
"""
while self.open_nodes:
# Open Nodes are sorted using __lt__
self.open_nodes.sort()
current_node = self.open_nodes.pop(0)
if current_node.pos == self.target.pos:
self.reached = True
return self.retrace_path(current_node)
self.closed_nodes.append(current_node)
successors = self.get_successors(current_node)
for child_node in successors:
if child_node in self.closed_nodes:
continue
if child_node not in self.open_nodes:
self.open_nodes.append(child_node)
else:
# retrieve the best current path
better_node = self.open_nodes.pop(self.open_nodes.index(child_node))
if child_node.g_cost < better_node.g_cost:
self.open_nodes.append(child_node)
else:
self.open_nodes.append(better_node)
if not self.reached:
return [self.start.pos]
return None
def get_successors(self, parent: Node) -> list[Node]:
"""
Returns a list of successors (both in the grid and free spaces)
"""
successors = []
for action in delta:
pos_x = parent.pos_x + action[1]
pos_y = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0]) - 1 and 0 <= pos_y <= len(grid) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(
pos_x,
pos_y,
self.target.pos_y,
self.target.pos_x,
parent.g_cost + 1,
parent,
)
)
return successors
def retrace_path(self, node: Node | None) -> Path:
"""
Retrace the path from parents to parents until start node
"""
current_node = node
path = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x))
current_node = current_node.parent
path.reverse()
return path
if __name__ == "__main__":
init = (0, 0)
goal = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
print("------")
greedy_bf = GreedyBestFirst(init, goal)
path = greedy_bf.search()
if path:
for pos_x, pos_y in path:
grid[pos_x][pos_y] = 2
for elem in grid:
print(elem)
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
2D Transformations are regularly used in Linear Algebra.
I have added the codes for reflection, projection, scaling and rotation 2D matrices.
scaling(5) = [[5.0, 0.0], [0.0, 5.0]]
rotation(45) = [[0.5253219888177297, -0.8509035245341184],
[0.8509035245341184, 0.5253219888177297]]
projection(45) = [[0.27596319193541496, 0.446998331800279],
[0.446998331800279, 0.7240368080645851]]
reflection(45) = [[0.05064397763545947, 0.893996663600558],
[0.893996663600558, 0.7018070490682369]]
"""
from math import cos, sin
def scaling(scaling_factor: float) -> list[list[float]]:
"""
>>> scaling(5)
[[5.0, 0.0], [0.0, 5.0]]
"""
scaling_factor = float(scaling_factor)
return [[scaling_factor * int(x == y) for x in range(2)] for y in range(2)]
def rotation(angle: float) -> list[list[float]]:
"""
>>> rotation(45) # doctest: +NORMALIZE_WHITESPACE
[[0.5253219888177297, -0.8509035245341184],
[0.8509035245341184, 0.5253219888177297]]
"""
c, s = cos(angle), sin(angle)
return [[c, -s], [s, c]]
def projection(angle: float) -> list[list[float]]:
"""
>>> projection(45) # doctest: +NORMALIZE_WHITESPACE
[[0.27596319193541496, 0.446998331800279],
[0.446998331800279, 0.7240368080645851]]
"""
c, s = cos(angle), sin(angle)
cs = c * s
return [[c * c, cs], [cs, s * s]]
def reflection(angle: float) -> list[list[float]]:
"""
>>> reflection(45) # doctest: +NORMALIZE_WHITESPACE
[[0.05064397763545947, 0.893996663600558],
[0.893996663600558, 0.7018070490682369]]
"""
c, s = cos(angle), sin(angle)
cs = c * s
return [[2 * c - 1, 2 * cs], [2 * cs, 2 * s - 1]]
print(f" {scaling(5) = }")
print(f" {rotation(45) = }")
print(f"{projection(45) = }")
print(f"{reflection(45) = }")
| """
2D Transformations are regularly used in Linear Algebra.
I have added the codes for reflection, projection, scaling and rotation 2D matrices.
scaling(5) = [[5.0, 0.0], [0.0, 5.0]]
rotation(45) = [[0.5253219888177297, -0.8509035245341184],
[0.8509035245341184, 0.5253219888177297]]
projection(45) = [[0.27596319193541496, 0.446998331800279],
[0.446998331800279, 0.7240368080645851]]
reflection(45) = [[0.05064397763545947, 0.893996663600558],
[0.893996663600558, 0.7018070490682369]]
"""
from math import cos, sin
def scaling(scaling_factor: float) -> list[list[float]]:
"""
>>> scaling(5)
[[5.0, 0.0], [0.0, 5.0]]
"""
scaling_factor = float(scaling_factor)
return [[scaling_factor * int(x == y) for x in range(2)] for y in range(2)]
def rotation(angle: float) -> list[list[float]]:
"""
>>> rotation(45) # doctest: +NORMALIZE_WHITESPACE
[[0.5253219888177297, -0.8509035245341184],
[0.8509035245341184, 0.5253219888177297]]
"""
c, s = cos(angle), sin(angle)
return [[c, -s], [s, c]]
def projection(angle: float) -> list[list[float]]:
"""
>>> projection(45) # doctest: +NORMALIZE_WHITESPACE
[[0.27596319193541496, 0.446998331800279],
[0.446998331800279, 0.7240368080645851]]
"""
c, s = cos(angle), sin(angle)
cs = c * s
return [[c * c, cs], [cs, s * s]]
def reflection(angle: float) -> list[list[float]]:
"""
>>> reflection(45) # doctest: +NORMALIZE_WHITESPACE
[[0.05064397763545947, 0.893996663600558],
[0.893996663600558, 0.7018070490682369]]
"""
c, s = cos(angle), sin(angle)
cs = c * s
return [[2 * c - 1, 2 * cs], [2 * cs, 2 * s - 1]]
print(f" {scaling(5) = }")
print(f" {rotation(45) = }")
print(f"{projection(45) = }")
print(f"{reflection(45) = }")
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
A Python implementation of the quick select algorithm, which is efficient for
calculating the value that would appear in the index of a list if it would be
sorted, even if it is not already sorted
https://en.wikipedia.org/wiki/Quickselect
"""
import random
def _partition(data: list, pivot) -> tuple:
"""
Three way partition the data into smaller, equal and greater lists,
in relationship to the pivot
:param data: The data to be sorted (a list)
:param pivot: The value to partition the data on
:return: Three list: smaller, equal and greater
"""
less, equal, greater = [], [], []
for element in data:
if element < pivot:
less.append(element)
elif element > pivot:
greater.append(element)
else:
equal.append(element)
return less, equal, greater
def quick_select(items: list, index: int):
"""
>>> quick_select([2, 4, 5, 7, 899, 54, 32], 5)
54
>>> quick_select([2, 4, 5, 7, 899, 54, 32], 1)
4
>>> quick_select([5, 4, 3, 2], 2)
4
>>> quick_select([3, 5, 7, 10, 2, 12], 3)
7
"""
# index = len(items) // 2 when trying to find the median
# (value of index when items is sorted)
# invalid input
if index >= len(items) or index < 0:
return None
pivot = items[random.randint(0, len(items) - 1)]
count = 0
smaller, equal, larger = _partition(items, pivot)
count = len(equal)
m = len(smaller)
# index is the pivot
if m <= index < m + count:
return pivot
# must be in smaller
elif m > index:
return quick_select(smaller, index)
# must be in larger
else:
return quick_select(larger, index - (m + count))
| """
A Python implementation of the quick select algorithm, which is efficient for
calculating the value that would appear in the index of a list if it would be
sorted, even if it is not already sorted
https://en.wikipedia.org/wiki/Quickselect
"""
import random
def _partition(data: list, pivot) -> tuple:
"""
Three way partition the data into smaller, equal and greater lists,
in relationship to the pivot
:param data: The data to be sorted (a list)
:param pivot: The value to partition the data on
:return: Three list: smaller, equal and greater
"""
less, equal, greater = [], [], []
for element in data:
if element < pivot:
less.append(element)
elif element > pivot:
greater.append(element)
else:
equal.append(element)
return less, equal, greater
def quick_select(items: list, index: int):
"""
>>> quick_select([2, 4, 5, 7, 899, 54, 32], 5)
54
>>> quick_select([2, 4, 5, 7, 899, 54, 32], 1)
4
>>> quick_select([5, 4, 3, 2], 2)
4
>>> quick_select([3, 5, 7, 10, 2, 12], 3)
7
"""
# index = len(items) // 2 when trying to find the median
# (value of index when items is sorted)
# invalid input
if index >= len(items) or index < 0:
return None
pivot = items[random.randint(0, len(items) - 1)]
count = 0
smaller, equal, larger = _partition(items, pivot)
count = len(equal)
m = len(smaller)
# index is the pivot
if m <= index < m + count:
return pivot
# must be in smaller
elif m > index:
return quick_select(smaller, index)
# must be in larger
else:
return quick_select(larger, index - (m + count))
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from collections import deque
from math import floor
from random import random
from time import time
# the default weight is 1 if not assigned but all the implementation is weighted
class DirectedGraph:
def __init__(self):
self.graph = {}
# adding vertices and edges
# adding the weight is optional
# handles repetition
def add_pair(self, u, v, w=1):
if self.graph.get(u):
if self.graph[u].count([w, v]) == 0:
self.graph[u].append([w, v])
else:
self.graph[u] = [[w, v]]
if not self.graph.get(v):
self.graph[v] = []
def all_nodes(self):
return list(self.graph)
# handles if the input does not exist
def remove_pair(self, u, v):
if self.graph.get(u):
for _ in self.graph[u]:
if _[1] == v:
self.graph[u].remove(_)
# if no destination is meant the default value is -1
def dfs(self, s=-2, d=-1):
if s == d:
return []
stack = []
visited = []
if s == -2:
s = list(self.graph)[0]
stack.append(s)
visited.append(s)
ss = s
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if visited.count(node[1]) < 1:
if node[1] == d:
visited.append(d)
return visited
else:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return visited
# c is the count of nodes you want and if you leave it or pass -1 to the function
# the count will be random from 10 to 10000
def fill_graph_randomly(self, c=-1):
if c == -1:
c = floor(random() * 10000) + 10
for i in range(c):
# every vertex has max 100 edges
for _ in range(floor(random() * 102) + 1):
n = floor(random() * c) + 1
if n != i:
self.add_pair(i, n, 1)
def bfs(self, s=-2):
d = deque()
visited = []
if s == -2:
s = list(self.graph)[0]
d.append(s)
visited.append(s)
while d:
s = d.popleft()
if len(self.graph[s]) != 0:
for node in self.graph[s]:
if visited.count(node[1]) < 1:
d.append(node[1])
visited.append(node[1])
return visited
def in_degree(self, u):
count = 0
for x in self.graph:
for y in self.graph[x]:
if y[1] == u:
count += 1
return count
def out_degree(self, u):
return len(self.graph[u])
def topological_sort(self, s=-2):
stack = []
visited = []
if s == -2:
s = list(self.graph)[0]
stack.append(s)
visited.append(s)
ss = s
sorted_nodes = []
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
sorted_nodes.append(stack.pop())
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return sorted_nodes
def cycle_nodes(self):
stack = []
visited = []
s = list(self.graph)[0]
stack.append(s)
visited.append(s)
parent = -2
indirect_parents = []
ss = s
on_the_way_back = False
anticipating_nodes = set()
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if (
visited.count(node[1]) > 0
and node[1] != parent
and indirect_parents.count(node[1]) > 0
and not on_the_way_back
):
len_stack = len(stack) - 1
while True and len_stack >= 0:
if stack[len_stack] == node[1]:
anticipating_nodes.add(node[1])
break
else:
anticipating_nodes.add(stack[len_stack])
len_stack -= 1
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
on_the_way_back = True
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
on_the_way_back = False
indirect_parents.append(parent)
parent = s
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return list(anticipating_nodes)
def has_cycle(self):
stack = []
visited = []
s = list(self.graph)[0]
stack.append(s)
visited.append(s)
parent = -2
indirect_parents = []
ss = s
on_the_way_back = False
anticipating_nodes = set()
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if (
visited.count(node[1]) > 0
and node[1] != parent
and indirect_parents.count(node[1]) > 0
and not on_the_way_back
):
len_stack_minus_one = len(stack) - 1
while True and len_stack_minus_one >= 0:
if stack[len_stack_minus_one] == node[1]:
anticipating_nodes.add(node[1])
break
else:
return True
# TODO:The following code is unreachable.
anticipating_nodes.add(stack[len_stack_minus_one])
len_stack_minus_one -= 1
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
on_the_way_back = True
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
on_the_way_back = False
indirect_parents.append(parent)
parent = s
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return False
def dfs_time(self, s=-2, e=-1):
begin = time()
self.dfs(s, e)
end = time()
return end - begin
def bfs_time(self, s=-2):
begin = time()
self.bfs(s)
end = time()
return end - begin
class Graph:
def __init__(self):
self.graph = {}
# adding vertices and edges
# adding the weight is optional
# handles repetition
def add_pair(self, u, v, w=1):
# check if the u exists
if self.graph.get(u):
# if there already is a edge
if self.graph[u].count([w, v]) == 0:
self.graph[u].append([w, v])
else:
# if u does not exist
self.graph[u] = [[w, v]]
# add the other way
if self.graph.get(v):
# if there already is a edge
if self.graph[v].count([w, u]) == 0:
self.graph[v].append([w, u])
else:
# if u does not exist
self.graph[v] = [[w, u]]
# handles if the input does not exist
def remove_pair(self, u, v):
if self.graph.get(u):
for _ in self.graph[u]:
if _[1] == v:
self.graph[u].remove(_)
# the other way round
if self.graph.get(v):
for _ in self.graph[v]:
if _[1] == u:
self.graph[v].remove(_)
# if no destination is meant the default value is -1
def dfs(self, s=-2, d=-1):
if s == d:
return []
stack = []
visited = []
if s == -2:
s = list(self.graph)[0]
stack.append(s)
visited.append(s)
ss = s
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if visited.count(node[1]) < 1:
if node[1] == d:
visited.append(d)
return visited
else:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return visited
# c is the count of nodes you want and if you leave it or pass -1 to the function
# the count will be random from 10 to 10000
def fill_graph_randomly(self, c=-1):
if c == -1:
c = floor(random() * 10000) + 10
for i in range(c):
# every vertex has max 100 edges
for _ in range(floor(random() * 102) + 1):
n = floor(random() * c) + 1
if n != i:
self.add_pair(i, n, 1)
def bfs(self, s=-2):
d = deque()
visited = []
if s == -2:
s = list(self.graph)[0]
d.append(s)
visited.append(s)
while d:
s = d.popleft()
if len(self.graph[s]) != 0:
for node in self.graph[s]:
if visited.count(node[1]) < 1:
d.append(node[1])
visited.append(node[1])
return visited
def degree(self, u):
return len(self.graph[u])
def cycle_nodes(self):
stack = []
visited = []
s = list(self.graph)[0]
stack.append(s)
visited.append(s)
parent = -2
indirect_parents = []
ss = s
on_the_way_back = False
anticipating_nodes = set()
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if (
visited.count(node[1]) > 0
and node[1] != parent
and indirect_parents.count(node[1]) > 0
and not on_the_way_back
):
len_stack = len(stack) - 1
while True and len_stack >= 0:
if stack[len_stack] == node[1]:
anticipating_nodes.add(node[1])
break
else:
anticipating_nodes.add(stack[len_stack])
len_stack -= 1
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
on_the_way_back = True
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
on_the_way_back = False
indirect_parents.append(parent)
parent = s
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return list(anticipating_nodes)
def has_cycle(self):
stack = []
visited = []
s = list(self.graph)[0]
stack.append(s)
visited.append(s)
parent = -2
indirect_parents = []
ss = s
on_the_way_back = False
anticipating_nodes = set()
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if (
visited.count(node[1]) > 0
and node[1] != parent
and indirect_parents.count(node[1]) > 0
and not on_the_way_back
):
len_stack_minus_one = len(stack) - 1
while True and len_stack_minus_one >= 0:
if stack[len_stack_minus_one] == node[1]:
anticipating_nodes.add(node[1])
break
else:
return True
# TODO: the following code is unreachable
# is this meant to be called in the else ?
anticipating_nodes.add(stack[len_stack_minus_one])
len_stack_minus_one -= 1
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
on_the_way_back = True
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
on_the_way_back = False
indirect_parents.append(parent)
parent = s
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return False
def all_nodes(self):
return list(self.graph)
def dfs_time(self, s=-2, e=-1):
begin = time()
self.dfs(s, e)
end = time()
return end - begin
def bfs_time(self, s=-2):
begin = time()
self.bfs(s)
end = time()
return end - begin
| from collections import deque
from math import floor
from random import random
from time import time
# the default weight is 1 if not assigned but all the implementation is weighted
class DirectedGraph:
def __init__(self):
self.graph = {}
# adding vertices and edges
# adding the weight is optional
# handles repetition
def add_pair(self, u, v, w=1):
if self.graph.get(u):
if self.graph[u].count([w, v]) == 0:
self.graph[u].append([w, v])
else:
self.graph[u] = [[w, v]]
if not self.graph.get(v):
self.graph[v] = []
def all_nodes(self):
return list(self.graph)
# handles if the input does not exist
def remove_pair(self, u, v):
if self.graph.get(u):
for _ in self.graph[u]:
if _[1] == v:
self.graph[u].remove(_)
# if no destination is meant the default value is -1
def dfs(self, s=-2, d=-1):
if s == d:
return []
stack = []
visited = []
if s == -2:
s = list(self.graph)[0]
stack.append(s)
visited.append(s)
ss = s
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if visited.count(node[1]) < 1:
if node[1] == d:
visited.append(d)
return visited
else:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return visited
# c is the count of nodes you want and if you leave it or pass -1 to the function
# the count will be random from 10 to 10000
def fill_graph_randomly(self, c=-1):
if c == -1:
c = floor(random() * 10000) + 10
for i in range(c):
# every vertex has max 100 edges
for _ in range(floor(random() * 102) + 1):
n = floor(random() * c) + 1
if n != i:
self.add_pair(i, n, 1)
def bfs(self, s=-2):
d = deque()
visited = []
if s == -2:
s = list(self.graph)[0]
d.append(s)
visited.append(s)
while d:
s = d.popleft()
if len(self.graph[s]) != 0:
for node in self.graph[s]:
if visited.count(node[1]) < 1:
d.append(node[1])
visited.append(node[1])
return visited
def in_degree(self, u):
count = 0
for x in self.graph:
for y in self.graph[x]:
if y[1] == u:
count += 1
return count
def out_degree(self, u):
return len(self.graph[u])
def topological_sort(self, s=-2):
stack = []
visited = []
if s == -2:
s = list(self.graph)[0]
stack.append(s)
visited.append(s)
ss = s
sorted_nodes = []
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
sorted_nodes.append(stack.pop())
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return sorted_nodes
def cycle_nodes(self):
stack = []
visited = []
s = list(self.graph)[0]
stack.append(s)
visited.append(s)
parent = -2
indirect_parents = []
ss = s
on_the_way_back = False
anticipating_nodes = set()
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if (
visited.count(node[1]) > 0
and node[1] != parent
and indirect_parents.count(node[1]) > 0
and not on_the_way_back
):
len_stack = len(stack) - 1
while True and len_stack >= 0:
if stack[len_stack] == node[1]:
anticipating_nodes.add(node[1])
break
else:
anticipating_nodes.add(stack[len_stack])
len_stack -= 1
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
on_the_way_back = True
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
on_the_way_back = False
indirect_parents.append(parent)
parent = s
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return list(anticipating_nodes)
def has_cycle(self):
stack = []
visited = []
s = list(self.graph)[0]
stack.append(s)
visited.append(s)
parent = -2
indirect_parents = []
ss = s
on_the_way_back = False
anticipating_nodes = set()
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if (
visited.count(node[1]) > 0
and node[1] != parent
and indirect_parents.count(node[1]) > 0
and not on_the_way_back
):
len_stack_minus_one = len(stack) - 1
while True and len_stack_minus_one >= 0:
if stack[len_stack_minus_one] == node[1]:
anticipating_nodes.add(node[1])
break
else:
return True
# TODO:The following code is unreachable.
anticipating_nodes.add(stack[len_stack_minus_one])
len_stack_minus_one -= 1
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
on_the_way_back = True
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
on_the_way_back = False
indirect_parents.append(parent)
parent = s
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return False
def dfs_time(self, s=-2, e=-1):
begin = time()
self.dfs(s, e)
end = time()
return end - begin
def bfs_time(self, s=-2):
begin = time()
self.bfs(s)
end = time()
return end - begin
class Graph:
def __init__(self):
self.graph = {}
# adding vertices and edges
# adding the weight is optional
# handles repetition
def add_pair(self, u, v, w=1):
# check if the u exists
if self.graph.get(u):
# if there already is a edge
if self.graph[u].count([w, v]) == 0:
self.graph[u].append([w, v])
else:
# if u does not exist
self.graph[u] = [[w, v]]
# add the other way
if self.graph.get(v):
# if there already is a edge
if self.graph[v].count([w, u]) == 0:
self.graph[v].append([w, u])
else:
# if u does not exist
self.graph[v] = [[w, u]]
# handles if the input does not exist
def remove_pair(self, u, v):
if self.graph.get(u):
for _ in self.graph[u]:
if _[1] == v:
self.graph[u].remove(_)
# the other way round
if self.graph.get(v):
for _ in self.graph[v]:
if _[1] == u:
self.graph[v].remove(_)
# if no destination is meant the default value is -1
def dfs(self, s=-2, d=-1):
if s == d:
return []
stack = []
visited = []
if s == -2:
s = list(self.graph)[0]
stack.append(s)
visited.append(s)
ss = s
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if visited.count(node[1]) < 1:
if node[1] == d:
visited.append(d)
return visited
else:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return visited
# c is the count of nodes you want and if you leave it or pass -1 to the function
# the count will be random from 10 to 10000
def fill_graph_randomly(self, c=-1):
if c == -1:
c = floor(random() * 10000) + 10
for i in range(c):
# every vertex has max 100 edges
for _ in range(floor(random() * 102) + 1):
n = floor(random() * c) + 1
if n != i:
self.add_pair(i, n, 1)
def bfs(self, s=-2):
d = deque()
visited = []
if s == -2:
s = list(self.graph)[0]
d.append(s)
visited.append(s)
while d:
s = d.popleft()
if len(self.graph[s]) != 0:
for node in self.graph[s]:
if visited.count(node[1]) < 1:
d.append(node[1])
visited.append(node[1])
return visited
def degree(self, u):
return len(self.graph[u])
def cycle_nodes(self):
stack = []
visited = []
s = list(self.graph)[0]
stack.append(s)
visited.append(s)
parent = -2
indirect_parents = []
ss = s
on_the_way_back = False
anticipating_nodes = set()
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if (
visited.count(node[1]) > 0
and node[1] != parent
and indirect_parents.count(node[1]) > 0
and not on_the_way_back
):
len_stack = len(stack) - 1
while True and len_stack >= 0:
if stack[len_stack] == node[1]:
anticipating_nodes.add(node[1])
break
else:
anticipating_nodes.add(stack[len_stack])
len_stack -= 1
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
on_the_way_back = True
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
on_the_way_back = False
indirect_parents.append(parent)
parent = s
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return list(anticipating_nodes)
def has_cycle(self):
stack = []
visited = []
s = list(self.graph)[0]
stack.append(s)
visited.append(s)
parent = -2
indirect_parents = []
ss = s
on_the_way_back = False
anticipating_nodes = set()
while True:
# check if there is any non isolated nodes
if len(self.graph[s]) != 0:
ss = s
for node in self.graph[s]:
if (
visited.count(node[1]) > 0
and node[1] != parent
and indirect_parents.count(node[1]) > 0
and not on_the_way_back
):
len_stack_minus_one = len(stack) - 1
while True and len_stack_minus_one >= 0:
if stack[len_stack_minus_one] == node[1]:
anticipating_nodes.add(node[1])
break
else:
return True
# TODO: the following code is unreachable
# is this meant to be called in the else ?
anticipating_nodes.add(stack[len_stack_minus_one])
len_stack_minus_one -= 1
if visited.count(node[1]) < 1:
stack.append(node[1])
visited.append(node[1])
ss = node[1]
break
# check if all the children are visited
if s == ss:
stack.pop()
on_the_way_back = True
if len(stack) != 0:
s = stack[len(stack) - 1]
else:
on_the_way_back = False
indirect_parents.append(parent)
parent = s
s = ss
# check if se have reached the starting point
if len(stack) == 0:
return False
def all_nodes(self):
return list(self.graph)
def dfs_time(self, s=-2, e=-1):
begin = time()
self.dfs(s, e)
end = time()
return end - begin
def bfs_time(self, s=-2):
begin = time()
self.bfs(s)
end = time()
return end - begin
| -1 |
TheAlgorithms/Python | 5,814 | [Mypy] fix other/least_recently_used | ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| spazm | "2021-11-11T00:34:03Z" | "2021-11-16T14:01:18Z" | 9b9405fdcdc5ba9fc16a53f8ae6be081d4f5582a | 551c65766d1594ecd7e127ac288ed23b9e89b8c3 | [Mypy] fix other/least_recently_used. ### Describe your change:
+ fix bug in dq_removal code. Needed to pass key to .remove() rather than index.
+ remove incorrect annotation to make the `__init__` an abstract function.
+ Annotate all functions and class `Generic[T]`
+ Expand example to show creating a `LRUCache` over concrete and mixed types.
+ Adds doctest to LRUCache class
+ Adds assert test in main.
Previously opened as #5656
Closes: #4052
#### Before
```
% git checkout master
Your branch is up to date with 'origin/master'.
% mypy --ignore-missing-imports --install-types least_recently_used.py
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
Found 1 error in 1 file (checked 1 source file)
```
```
% mypy --strict least_recently_used.py
least_recently_used.py:27: error: Function is missing a type annotation
least_recently_used.py:33: error: Unsupported right operand type for in ("object")
least_recently_used.py:34: error: Argument 1 to "len" has incompatible type "object"; expected "Sized"
least_recently_used.py:35: error: "object" has no attribute "pop"
least_recently_used.py:36: error: "object" has no attribute "remove"
least_recently_used.py:39: error: Need type annotation for "key"
least_recently_used.py:39: error: Argument 1 to "enumerate" has incompatible type "object"; expected "Iterable[<nothing>]"
least_recently_used.py:43: error: "object" has no attribute "remove"
least_recently_used.py:45: error: "object" has no attribute "appendleft"
least_recently_used.py:46: error: "object" has no attribute "add"
least_recently_used.py:48: error: Function is missing a return type annotation
least_recently_used.py:48: note: Use "-> None" if function does not return a value
least_recently_used.py:52: error: "object" has no attribute "__iter__"; maybe "__str__" or "__dir__"? (not iterable)
least_recently_used.py:57: error: Cannot instantiate abstract class "LRUCache" with abstract attribute "__init__"
least_recently_used.py:58: error: Call to untyped function "refer" in typed context
least_recently_used.py:59: error: Call to untyped function "refer" in typed context
least_recently_used.py:60: error: Call to untyped function "refer" in typed context
least_recently_used.py:61: error: Call to untyped function "refer" in typed context
least_recently_used.py:62: error: Call to untyped function "refer" in typed context
least_recently_used.py:63: error: Call to untyped function "refer" in typed context
least_recently_used.py:64: error: Call to untyped function "display" in typed context
Found 20 errors in 1 file (checked 1 source file)
```
#### After
```
% git checkout mypy-fix-other-least_recently_used
Switched to branch 'mypy-fix-other-least_recently_used'
Your branch is up to date with 'origin/mypy-fix-other-least_recently_used'.
% mypy --strict least_recently_used.py
Success: no issues found in 1 source file
```
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
|
## Arithmetic Analysis
* [Bisection](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/bisection.py)
* [Gaussian Elimination](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/gaussian_elimination.py)
* [In Static Equilibrium](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/in_static_equilibrium.py)
* [Intersection](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/intersection.py)
* [Jacobi Iteration Method](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/jacobi_iteration_method.py)
* [Lu Decomposition](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/lu_decomposition.py)
* [Newton Forward Interpolation](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_forward_interpolation.py)
* [Newton Method](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_method.py)
* [Newton Raphson](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_raphson.py)
* [Secant Method](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/secant_method.py)
## Audio Filters
* [Butterworth Filter](https://github.com/TheAlgorithms/Python/blob/master/audio_filters/butterworth_filter.py)
* [Iir Filter](https://github.com/TheAlgorithms/Python/blob/master/audio_filters/iir_filter.py)
* [Show Response](https://github.com/TheAlgorithms/Python/blob/master/audio_filters/show_response.py)
## Backtracking
* [All Combinations](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_combinations.py)
* [All Permutations](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_permutations.py)
* [All Subsequences](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_subsequences.py)
* [Coloring](https://github.com/TheAlgorithms/Python/blob/master/backtracking/coloring.py)
* [Hamiltonian Cycle](https://github.com/TheAlgorithms/Python/blob/master/backtracking/hamiltonian_cycle.py)
* [Knight Tour](https://github.com/TheAlgorithms/Python/blob/master/backtracking/knight_tour.py)
* [Minimax](https://github.com/TheAlgorithms/Python/blob/master/backtracking/minimax.py)
* [N Queens](https://github.com/TheAlgorithms/Python/blob/master/backtracking/n_queens.py)
* [N Queens Math](https://github.com/TheAlgorithms/Python/blob/master/backtracking/n_queens_math.py)
* [Rat In Maze](https://github.com/TheAlgorithms/Python/blob/master/backtracking/rat_in_maze.py)
* [Sudoku](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sudoku.py)
* [Sum Of Subsets](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sum_of_subsets.py)
## Bit Manipulation
* [Binary And Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_and_operator.py)
* [Binary Count Setbits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_count_setbits.py)
* [Binary Count Trailing Zeros](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_count_trailing_zeros.py)
* [Binary Or Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_or_operator.py)
* [Binary Shifts](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_shifts.py)
* [Binary Twos Complement](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_twos_complement.py)
* [Binary Xor Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_xor_operator.py)
* [Count 1S Brian Kernighan Method](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/count_1s_brian_kernighan_method.py)
* [Count Number Of One Bits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/count_number_of_one_bits.py)
* [Gray Code Sequence](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/gray_code_sequence.py)
* [Reverse Bits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/reverse_bits.py)
* [Single Bit Manipulation Operations](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/single_bit_manipulation_operations.py)
## Blockchain
* [Chinese Remainder Theorem](https://github.com/TheAlgorithms/Python/blob/master/blockchain/chinese_remainder_theorem.py)
* [Diophantine Equation](https://github.com/TheAlgorithms/Python/blob/master/blockchain/diophantine_equation.py)
* [Modular Division](https://github.com/TheAlgorithms/Python/blob/master/blockchain/modular_division.py)
## Boolean Algebra
* [Quine Mc Cluskey](https://github.com/TheAlgorithms/Python/blob/master/boolean_algebra/quine_mc_cluskey.py)
## Cellular Automata
* [Conways Game Of Life](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/conways_game_of_life.py)
* [Game Of Life](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/game_of_life.py)
* [Nagel Schrekenberg](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/nagel_schrekenberg.py)
* [One Dimensional](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/one_dimensional.py)
## Ciphers
* [A1Z26](https://github.com/TheAlgorithms/Python/blob/master/ciphers/a1z26.py)
* [Affine Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/affine_cipher.py)
* [Atbash](https://github.com/TheAlgorithms/Python/blob/master/ciphers/atbash.py)
* [Baconian Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/baconian_cipher.py)
* [Base16](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base16.py)
* [Base32](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base32.py)
* [Base64](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base64.py)
* [Base85](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base85.py)
* [Beaufort Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/beaufort_cipher.py)
* [Bifid](https://github.com/TheAlgorithms/Python/blob/master/ciphers/bifid.py)
* [Brute Force Caesar Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/brute_force_caesar_cipher.py)
* [Caesar Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/caesar_cipher.py)
* [Cryptomath Module](https://github.com/TheAlgorithms/Python/blob/master/ciphers/cryptomath_module.py)
* [Decrypt Caesar With Chi Squared](https://github.com/TheAlgorithms/Python/blob/master/ciphers/decrypt_caesar_with_chi_squared.py)
* [Deterministic Miller Rabin](https://github.com/TheAlgorithms/Python/blob/master/ciphers/deterministic_miller_rabin.py)
* [Diffie](https://github.com/TheAlgorithms/Python/blob/master/ciphers/diffie.py)
* [Diffie Hellman](https://github.com/TheAlgorithms/Python/blob/master/ciphers/diffie_hellman.py)
* [Elgamal Key Generator](https://github.com/TheAlgorithms/Python/blob/master/ciphers/elgamal_key_generator.py)
* [Enigma Machine2](https://github.com/TheAlgorithms/Python/blob/master/ciphers/enigma_machine2.py)
* [Hill Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/hill_cipher.py)
* [Mixed Keyword Cypher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/mixed_keyword_cypher.py)
* [Mono Alphabetic Ciphers](https://github.com/TheAlgorithms/Python/blob/master/ciphers/mono_alphabetic_ciphers.py)
* [Morse Code](https://github.com/TheAlgorithms/Python/blob/master/ciphers/morse_code.py)
* [Onepad Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/onepad_cipher.py)
* [Playfair Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/playfair_cipher.py)
* [Polybius](https://github.com/TheAlgorithms/Python/blob/master/ciphers/polybius.py)
* [Porta Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/porta_cipher.py)
* [Rabin Miller](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rabin_miller.py)
* [Rail Fence Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rail_fence_cipher.py)
* [Rot13](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rot13.py)
* [Rsa Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_cipher.py)
* [Rsa Factorization](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_factorization.py)
* [Rsa Key Generator](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_key_generator.py)
* [Shuffled Shift Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/shuffled_shift_cipher.py)
* [Simple Keyword Cypher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/simple_keyword_cypher.py)
* [Simple Substitution Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/simple_substitution_cipher.py)
* [Trafid Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/trafid_cipher.py)
* [Transposition Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/transposition_cipher.py)
* [Transposition Cipher Encrypt Decrypt File](https://github.com/TheAlgorithms/Python/blob/master/ciphers/transposition_cipher_encrypt_decrypt_file.py)
* [Vigenere Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/vigenere_cipher.py)
* [Xor Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/xor_cipher.py)
## Compression
* [Burrows Wheeler](https://github.com/TheAlgorithms/Python/blob/master/compression/burrows_wheeler.py)
* [Huffman](https://github.com/TheAlgorithms/Python/blob/master/compression/huffman.py)
* [Lempel Ziv](https://github.com/TheAlgorithms/Python/blob/master/compression/lempel_ziv.py)
* [Lempel Ziv Decompress](https://github.com/TheAlgorithms/Python/blob/master/compression/lempel_ziv_decompress.py)
* [Peak Signal To Noise Ratio](https://github.com/TheAlgorithms/Python/blob/master/compression/peak_signal_to_noise_ratio.py)
## Computer Vision
* [Cnn Classification](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/cnn_classification.py)
* [Flip Augmentation](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/flip_augmentation.py)
* [Harris Corner](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/harris_corner.py)
* [Mean Threshold](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/mean_threshold.py)
* [Mosaic Augmentation](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/mosaic_augmentation.py)
## Conversions
* [Binary To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_decimal.py)
* [Binary To Hexadecimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_hexadecimal.py)
* [Binary To Octal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_octal.py)
* [Decimal To Any](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_any.py)
* [Decimal To Binary](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_binary.py)
* [Decimal To Binary Recursion](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_binary_recursion.py)
* [Decimal To Hexadecimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_hexadecimal.py)
* [Decimal To Octal](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_octal.py)
* [Hex To Bin](https://github.com/TheAlgorithms/Python/blob/master/conversions/hex_to_bin.py)
* [Hexadecimal To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/hexadecimal_to_decimal.py)
* [Length Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/length_conversion.py)
* [Molecular Chemistry](https://github.com/TheAlgorithms/Python/blob/master/conversions/molecular_chemistry.py)
* [Octal To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/octal_to_decimal.py)
* [Prefix Conversions](https://github.com/TheAlgorithms/Python/blob/master/conversions/prefix_conversions.py)
* [Pressure Conversions](https://github.com/TheAlgorithms/Python/blob/master/conversions/pressure_conversions.py)
* [Rgb Hsv Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/rgb_hsv_conversion.py)
* [Roman Numerals](https://github.com/TheAlgorithms/Python/blob/master/conversions/roman_numerals.py)
* [Temperature Conversions](https://github.com/TheAlgorithms/Python/blob/master/conversions/temperature_conversions.py)
* [Volume Conversions](https://github.com/TheAlgorithms/Python/blob/master/conversions/volume_conversions.py)
* [Weight Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/weight_conversion.py)
## Data Structures
* Binary Tree
* [Avl Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/avl_tree.py)
* [Basic Binary Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/basic_binary_tree.py)
* [Binary Search Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_search_tree.py)
* [Binary Search Tree Recursive](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_search_tree_recursive.py)
* [Binary Tree Mirror](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_tree_mirror.py)
* [Binary Tree Traversals](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_tree_traversals.py)
* [Fenwick Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/fenwick_tree.py)
* [Lazy Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/lazy_segment_tree.py)
* [Lowest Common Ancestor](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/lowest_common_ancestor.py)
* [Merge Two Binary Trees](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/merge_two_binary_trees.py)
* [Non Recursive Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/non_recursive_segment_tree.py)
* [Number Of Possible Binary Trees](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/number_of_possible_binary_trees.py)
* [Red Black Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/red_black_tree.py)
* [Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/segment_tree.py)
* [Segment Tree Other](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/segment_tree_other.py)
* [Treap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/treap.py)
* [Wavelet Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/wavelet_tree.py)
* Disjoint Set
* [Alternate Disjoint Set](https://github.com/TheAlgorithms/Python/blob/master/data_structures/disjoint_set/alternate_disjoint_set.py)
* [Disjoint Set](https://github.com/TheAlgorithms/Python/blob/master/data_structures/disjoint_set/disjoint_set.py)
* Hashing
* [Double Hash](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/double_hash.py)
* [Hash Table](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/hash_table.py)
* [Hash Table With Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/hash_table_with_linked_list.py)
* Number Theory
* [Prime Numbers](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/number_theory/prime_numbers.py)
* [Quadratic Probing](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/quadratic_probing.py)
* Heap
* [Binomial Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/binomial_heap.py)
* [Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/heap.py)
* [Heap Generic](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/heap_generic.py)
* [Max Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/max_heap.py)
* [Min Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/min_heap.py)
* [Randomized Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/randomized_heap.py)
* [Skew Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/skew_heap.py)
* Linked List
* [Circular Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/circular_linked_list.py)
* [Deque Doubly](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/deque_doubly.py)
* [Doubly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/doubly_linked_list.py)
* [Doubly Linked List Two](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/doubly_linked_list_two.py)
* [From Sequence](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/from_sequence.py)
* [Has Loop](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/has_loop.py)
* [Is Palindrome](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/is_palindrome.py)
* [Merge Two Lists](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/merge_two_lists.py)
* [Middle Element Of Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/middle_element_of_linked_list.py)
* [Print Reverse](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/print_reverse.py)
* [Singly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/singly_linked_list.py)
* [Skip List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/skip_list.py)
* [Swap Nodes](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/swap_nodes.py)
* Queue
* [Circular Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/circular_queue.py)
* [Circular Queue Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/circular_queue_linked_list.py)
* [Double Ended Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/double_ended_queue.py)
* [Linked Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/linked_queue.py)
* [Priority Queue Using List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/priority_queue_using_list.py)
* [Queue On List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/queue_on_list.py)
* [Queue On Pseudo Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/queue_on_pseudo_stack.py)
* Stacks
* [Balanced Parentheses](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/balanced_parentheses.py)
* [Dijkstras Two Stack Algorithm](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/dijkstras_two_stack_algorithm.py)
* [Evaluate Postfix Notations](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/evaluate_postfix_notations.py)
* [Infix To Postfix Conversion](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/infix_to_postfix_conversion.py)
* [Infix To Prefix Conversion](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/infix_to_prefix_conversion.py)
* [Next Greater Element](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/next_greater_element.py)
* [Postfix Evaluation](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/postfix_evaluation.py)
* [Prefix Evaluation](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/prefix_evaluation.py)
* [Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stack.py)
* [Stack With Doubly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stack_with_doubly_linked_list.py)
* [Stack With Singly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stack_with_singly_linked_list.py)
* [Stock Span Problem](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stock_span_problem.py)
* Trie
* [Trie](https://github.com/TheAlgorithms/Python/blob/master/data_structures/trie/trie.py)
## Digital Image Processing
* [Change Brightness](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/change_brightness.py)
* [Change Contrast](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/change_contrast.py)
* [Convert To Negative](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/convert_to_negative.py)
* Dithering
* [Burkes](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/dithering/burkes.py)
* Edge Detection
* [Canny](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/edge_detection/canny.py)
* Filters
* [Bilateral Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/bilateral_filter.py)
* [Convolve](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/convolve.py)
* [Gabor Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/gabor_filter.py)
* [Gaussian Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/gaussian_filter.py)
* [Median Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/median_filter.py)
* [Sobel Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/sobel_filter.py)
* Histogram Equalization
* [Histogram Stretch](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/histogram_equalization/histogram_stretch.py)
* [Index Calculation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/index_calculation.py)
* Morphological Operations
* [Dilation Operation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/morphological_operations/dilation_operation.py)
* [Erosion Operation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/morphological_operations/erosion_operation.py)
* Resize
* [Resize](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/resize/resize.py)
* Rotation
* [Rotation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/rotation/rotation.py)
* [Sepia](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/sepia.py)
* [Test Digital Image Processing](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/test_digital_image_processing.py)
## Divide And Conquer
* [Closest Pair Of Points](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/closest_pair_of_points.py)
* [Convex Hull](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/convex_hull.py)
* [Heaps Algorithm](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/heaps_algorithm.py)
* [Heaps Algorithm Iterative](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/heaps_algorithm_iterative.py)
* [Inversions](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/inversions.py)
* [Kth Order Statistic](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/kth_order_statistic.py)
* [Max Difference Pair](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/max_difference_pair.py)
* [Max Subarray Sum](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/max_subarray_sum.py)
* [Mergesort](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/mergesort.py)
* [Peak](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/peak.py)
* [Power](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/power.py)
* [Strassen Matrix Multiplication](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/strassen_matrix_multiplication.py)
## Dynamic Programming
* [Abbreviation](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/abbreviation.py)
* [All Construct](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/all_construct.py)
* [Bitmask](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/bitmask.py)
* [Catalan Numbers](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/catalan_numbers.py)
* [Climbing Stairs](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/climbing_stairs.py)
* [Edit Distance](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/edit_distance.py)
* [Factorial](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/factorial.py)
* [Fast Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fast_fibonacci.py)
* [Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fibonacci.py)
* [Floyd Warshall](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/floyd_warshall.py)
* [Fractional Knapsack](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fractional_knapsack.py)
* [Fractional Knapsack 2](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fractional_knapsack_2.py)
* [Integer Partition](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/integer_partition.py)
* [Iterating Through Submasks](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/iterating_through_submasks.py)
* [Knapsack](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/knapsack.py)
* [Longest Common Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_common_subsequence.py)
* [Longest Increasing Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_increasing_subsequence.py)
* [Longest Increasing Subsequence O(Nlogn)](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_increasing_subsequence_o(nlogn).py)
* [Longest Sub Array](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_sub_array.py)
* [Matrix Chain Order](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/matrix_chain_order.py)
* [Max Non Adjacent Sum](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_non_adjacent_sum.py)
* [Max Sub Array](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_sub_array.py)
* [Max Sum Contiguous Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_sum_contiguous_subsequence.py)
* [Minimum Coin Change](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_coin_change.py)
* [Minimum Cost Path](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_cost_path.py)
* [Minimum Partition](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_partition.py)
* [Minimum Steps To One](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_steps_to_one.py)
* [Optimal Binary Search Tree](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/optimal_binary_search_tree.py)
* [Rod Cutting](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/rod_cutting.py)
* [Subset Generation](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/subset_generation.py)
* [Sum Of Subset](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/sum_of_subset.py)
## Electronics
* [Carrier Concentration](https://github.com/TheAlgorithms/Python/blob/master/electronics/carrier_concentration.py)
* [Coulombs Law](https://github.com/TheAlgorithms/Python/blob/master/electronics/coulombs_law.py)
* [Electric Power](https://github.com/TheAlgorithms/Python/blob/master/electronics/electric_power.py)
* [Ohms Law](https://github.com/TheAlgorithms/Python/blob/master/electronics/ohms_law.py)
## File Transfer
* [Receive File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/receive_file.py)
* [Send File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/send_file.py)
* Tests
* [Test Send File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/tests/test_send_file.py)
## Financial
* [Equated Monthly Installments](https://github.com/TheAlgorithms/Python/blob/master/financial/equated_monthly_installments.py)
* [Interest](https://github.com/TheAlgorithms/Python/blob/master/financial/interest.py)
## Fractals
* [Julia Sets](https://github.com/TheAlgorithms/Python/blob/master/fractals/julia_sets.py)
* [Koch Snowflake](https://github.com/TheAlgorithms/Python/blob/master/fractals/koch_snowflake.py)
* [Mandelbrot](https://github.com/TheAlgorithms/Python/blob/master/fractals/mandelbrot.py)
* [Sierpinski Triangle](https://github.com/TheAlgorithms/Python/blob/master/fractals/sierpinski_triangle.py)
## Fuzzy Logic
* [Fuzzy Operations](https://github.com/TheAlgorithms/Python/blob/master/fuzzy_logic/fuzzy_operations.py)
## Genetic Algorithm
* [Basic String](https://github.com/TheAlgorithms/Python/blob/master/genetic_algorithm/basic_string.py)
## Geodesy
* [Haversine Distance](https://github.com/TheAlgorithms/Python/blob/master/geodesy/haversine_distance.py)
* [Lamberts Ellipsoidal Distance](https://github.com/TheAlgorithms/Python/blob/master/geodesy/lamberts_ellipsoidal_distance.py)
## Graphics
* [Bezier Curve](https://github.com/TheAlgorithms/Python/blob/master/graphics/bezier_curve.py)
* [Vector3 For 2D Rendering](https://github.com/TheAlgorithms/Python/blob/master/graphics/vector3_for_2d_rendering.py)
## Graphs
* [A Star](https://github.com/TheAlgorithms/Python/blob/master/graphs/a_star.py)
* [Articulation Points](https://github.com/TheAlgorithms/Python/blob/master/graphs/articulation_points.py)
* [Basic Graphs](https://github.com/TheAlgorithms/Python/blob/master/graphs/basic_graphs.py)
* [Bellman Ford](https://github.com/TheAlgorithms/Python/blob/master/graphs/bellman_ford.py)
* [Bfs Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/bfs_shortest_path.py)
* [Bfs Zero One Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/bfs_zero_one_shortest_path.py)
* [Bidirectional A Star](https://github.com/TheAlgorithms/Python/blob/master/graphs/bidirectional_a_star.py)
* [Bidirectional Breadth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/bidirectional_breadth_first_search.py)
* [Boruvka](https://github.com/TheAlgorithms/Python/blob/master/graphs/boruvka.py)
* [Breadth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search.py)
* [Breadth First Search 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search_2.py)
* [Breadth First Search Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search_shortest_path.py)
* [Check Bipartite Graph Bfs](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_bipartite_graph_bfs.py)
* [Check Bipartite Graph Dfs](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_bipartite_graph_dfs.py)
* [Check Cycle](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_cycle.py)
* [Connected Components](https://github.com/TheAlgorithms/Python/blob/master/graphs/connected_components.py)
* [Depth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/depth_first_search.py)
* [Depth First Search 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/depth_first_search_2.py)
* [Dijkstra](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra.py)
* [Dijkstra 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra_2.py)
* [Dijkstra Algorithm](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra_algorithm.py)
* [Dinic](https://github.com/TheAlgorithms/Python/blob/master/graphs/dinic.py)
* [Directed And Undirected (Weighted) Graph](https://github.com/TheAlgorithms/Python/blob/master/graphs/directed_and_undirected_(weighted)_graph.py)
* [Edmonds Karp Multiple Source And Sink](https://github.com/TheAlgorithms/Python/blob/master/graphs/edmonds_karp_multiple_source_and_sink.py)
* [Eulerian Path And Circuit For Undirected Graph](https://github.com/TheAlgorithms/Python/blob/master/graphs/eulerian_path_and_circuit_for_undirected_graph.py)
* [Even Tree](https://github.com/TheAlgorithms/Python/blob/master/graphs/even_tree.py)
* [Finding Bridges](https://github.com/TheAlgorithms/Python/blob/master/graphs/finding_bridges.py)
* [Frequent Pattern Graph Miner](https://github.com/TheAlgorithms/Python/blob/master/graphs/frequent_pattern_graph_miner.py)
* [G Topological Sort](https://github.com/TheAlgorithms/Python/blob/master/graphs/g_topological_sort.py)
* [Gale Shapley Bigraph](https://github.com/TheAlgorithms/Python/blob/master/graphs/gale_shapley_bigraph.py)
* [Graph List](https://github.com/TheAlgorithms/Python/blob/master/graphs/graph_list.py)
* [Graph Matrix](https://github.com/TheAlgorithms/Python/blob/master/graphs/graph_matrix.py)
* [Graphs Floyd Warshall](https://github.com/TheAlgorithms/Python/blob/master/graphs/graphs_floyd_warshall.py)
* [Greedy Best First](https://github.com/TheAlgorithms/Python/blob/master/graphs/greedy_best_first.py)
* [Greedy Min Vertex Cover](https://github.com/TheAlgorithms/Python/blob/master/graphs/greedy_min_vertex_cover.py)
* [Kahns Algorithm Long](https://github.com/TheAlgorithms/Python/blob/master/graphs/kahns_algorithm_long.py)
* [Kahns Algorithm Topo](https://github.com/TheAlgorithms/Python/blob/master/graphs/kahns_algorithm_topo.py)
* [Karger](https://github.com/TheAlgorithms/Python/blob/master/graphs/karger.py)
* [Markov Chain](https://github.com/TheAlgorithms/Python/blob/master/graphs/markov_chain.py)
* [Matching Min Vertex Cover](https://github.com/TheAlgorithms/Python/blob/master/graphs/matching_min_vertex_cover.py)
* [Minimum Spanning Tree Boruvka](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_boruvka.py)
* [Minimum Spanning Tree Kruskal](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_kruskal.py)
* [Minimum Spanning Tree Kruskal2](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_kruskal2.py)
* [Minimum Spanning Tree Prims](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_prims.py)
* [Minimum Spanning Tree Prims2](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_prims2.py)
* [Multi Heuristic Astar](https://github.com/TheAlgorithms/Python/blob/master/graphs/multi_heuristic_astar.py)
* [Page Rank](https://github.com/TheAlgorithms/Python/blob/master/graphs/page_rank.py)
* [Prim](https://github.com/TheAlgorithms/Python/blob/master/graphs/prim.py)
* [Random Graph Generator](https://github.com/TheAlgorithms/Python/blob/master/graphs/random_graph_generator.py)
* [Scc Kosaraju](https://github.com/TheAlgorithms/Python/blob/master/graphs/scc_kosaraju.py)
* [Strongly Connected Components](https://github.com/TheAlgorithms/Python/blob/master/graphs/strongly_connected_components.py)
* [Tarjans Scc](https://github.com/TheAlgorithms/Python/blob/master/graphs/tarjans_scc.py)
* Tests
* [Test Min Spanning Tree Kruskal](https://github.com/TheAlgorithms/Python/blob/master/graphs/tests/test_min_spanning_tree_kruskal.py)
* [Test Min Spanning Tree Prim](https://github.com/TheAlgorithms/Python/blob/master/graphs/tests/test_min_spanning_tree_prim.py)
## Greedy Methods
* [Optimal Merge Pattern](https://github.com/TheAlgorithms/Python/blob/master/greedy_methods/optimal_merge_pattern.py)
## Hashes
* [Adler32](https://github.com/TheAlgorithms/Python/blob/master/hashes/adler32.py)
* [Chaos Machine](https://github.com/TheAlgorithms/Python/blob/master/hashes/chaos_machine.py)
* [Djb2](https://github.com/TheAlgorithms/Python/blob/master/hashes/djb2.py)
* [Enigma Machine](https://github.com/TheAlgorithms/Python/blob/master/hashes/enigma_machine.py)
* [Hamming Code](https://github.com/TheAlgorithms/Python/blob/master/hashes/hamming_code.py)
* [Luhn](https://github.com/TheAlgorithms/Python/blob/master/hashes/luhn.py)
* [Md5](https://github.com/TheAlgorithms/Python/blob/master/hashes/md5.py)
* [Sdbm](https://github.com/TheAlgorithms/Python/blob/master/hashes/sdbm.py)
* [Sha1](https://github.com/TheAlgorithms/Python/blob/master/hashes/sha1.py)
* [Sha256](https://github.com/TheAlgorithms/Python/blob/master/hashes/sha256.py)
## Knapsack
* [Greedy Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/greedy_knapsack.py)
* [Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/knapsack.py)
* Tests
* [Test Greedy Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/tests/test_greedy_knapsack.py)
* [Test Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/tests/test_knapsack.py)
## Linear Algebra
* Src
* [Conjugate Gradient](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/conjugate_gradient.py)
* [Lib](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/lib.py)
* [Polynom For Points](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/polynom_for_points.py)
* [Power Iteration](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/power_iteration.py)
* [Rayleigh Quotient](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/rayleigh_quotient.py)
* [Schur Complement](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/schur_complement.py)
* [Test Linear Algebra](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/test_linear_algebra.py)
* [Transformations 2D](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/transformations_2d.py)
## Machine Learning
* [Astar](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/astar.py)
* [Data Transformations](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/data_transformations.py)
* [Decision Tree](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/decision_tree.py)
* Forecasting
* [Run](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/forecasting/run.py)
* [Gaussian Naive Bayes](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gaussian_naive_bayes.py)
* [Gradient Boosting Regressor](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gradient_boosting_regressor.py)
* [Gradient Descent](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gradient_descent.py)
* [K Means Clust](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/k_means_clust.py)
* [K Nearest Neighbours](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/k_nearest_neighbours.py)
* [Knn Sklearn](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/knn_sklearn.py)
* [Linear Discriminant Analysis](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/linear_discriminant_analysis.py)
* [Linear Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/linear_regression.py)
* Local Weighted Learning
* [Local Weighted Learning](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/local_weighted_learning/local_weighted_learning.py)
* [Logistic Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/logistic_regression.py)
* Lstm
* [Lstm Prediction](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/lstm/lstm_prediction.py)
* [Multilayer Perceptron Classifier](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/multilayer_perceptron_classifier.py)
* [Polymonial Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/polymonial_regression.py)
* [Random Forest Classifier](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/random_forest_classifier.py)
* [Random Forest Regressor](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/random_forest_regressor.py)
* [Scoring Functions](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/scoring_functions.py)
* [Sequential Minimum Optimization](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/sequential_minimum_optimization.py)
* [Similarity Search](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/similarity_search.py)
* [Support Vector Machines](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/support_vector_machines.py)
* [Word Frequency Functions](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/word_frequency_functions.py)
## Maths
* [3N Plus 1](https://github.com/TheAlgorithms/Python/blob/master/maths/3n_plus_1.py)
* [Abs](https://github.com/TheAlgorithms/Python/blob/master/maths/abs.py)
* [Abs Max](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_max.py)
* [Abs Min](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_min.py)
* [Add](https://github.com/TheAlgorithms/Python/blob/master/maths/add.py)
* [Aliquot Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/aliquot_sum.py)
* [Allocation Number](https://github.com/TheAlgorithms/Python/blob/master/maths/allocation_number.py)
* [Area](https://github.com/TheAlgorithms/Python/blob/master/maths/area.py)
* [Area Under Curve](https://github.com/TheAlgorithms/Python/blob/master/maths/area_under_curve.py)
* [Armstrong Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/armstrong_numbers.py)
* [Average Mean](https://github.com/TheAlgorithms/Python/blob/master/maths/average_mean.py)
* [Average Median](https://github.com/TheAlgorithms/Python/blob/master/maths/average_median.py)
* [Average Mode](https://github.com/TheAlgorithms/Python/blob/master/maths/average_mode.py)
* [Bailey Borwein Plouffe](https://github.com/TheAlgorithms/Python/blob/master/maths/bailey_borwein_plouffe.py)
* [Basic Maths](https://github.com/TheAlgorithms/Python/blob/master/maths/basic_maths.py)
* [Binary Exp Mod](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exp_mod.py)
* [Binary Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation.py)
* [Binary Exponentiation 2](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation_2.py)
* [Binary Exponentiation 3](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation_3.py)
* [Binomial Coefficient](https://github.com/TheAlgorithms/Python/blob/master/maths/binomial_coefficient.py)
* [Binomial Distribution](https://github.com/TheAlgorithms/Python/blob/master/maths/binomial_distribution.py)
* [Bisection](https://github.com/TheAlgorithms/Python/blob/master/maths/bisection.py)
* [Ceil](https://github.com/TheAlgorithms/Python/blob/master/maths/ceil.py)
* [Check Polygon](https://github.com/TheAlgorithms/Python/blob/master/maths/check_polygon.py)
* [Chudnovsky Algorithm](https://github.com/TheAlgorithms/Python/blob/master/maths/chudnovsky_algorithm.py)
* [Collatz Sequence](https://github.com/TheAlgorithms/Python/blob/master/maths/collatz_sequence.py)
* [Combinations](https://github.com/TheAlgorithms/Python/blob/master/maths/combinations.py)
* [Decimal Isolate](https://github.com/TheAlgorithms/Python/blob/master/maths/decimal_isolate.py)
* [Double Factorial Iterative](https://github.com/TheAlgorithms/Python/blob/master/maths/double_factorial_iterative.py)
* [Double Factorial Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/double_factorial_recursive.py)
* [Entropy](https://github.com/TheAlgorithms/Python/blob/master/maths/entropy.py)
* [Euclidean Distance](https://github.com/TheAlgorithms/Python/blob/master/maths/euclidean_distance.py)
* [Euclidean Gcd](https://github.com/TheAlgorithms/Python/blob/master/maths/euclidean_gcd.py)
* [Euler Method](https://github.com/TheAlgorithms/Python/blob/master/maths/euler_method.py)
* [Euler Modified](https://github.com/TheAlgorithms/Python/blob/master/maths/euler_modified.py)
* [Eulers Totient](https://github.com/TheAlgorithms/Python/blob/master/maths/eulers_totient.py)
* [Extended Euclidean Algorithm](https://github.com/TheAlgorithms/Python/blob/master/maths/extended_euclidean_algorithm.py)
* [Factorial Iterative](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_iterative.py)
* [Factorial Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_recursive.py)
* [Factors](https://github.com/TheAlgorithms/Python/blob/master/maths/factors.py)
* [Fermat Little Theorem](https://github.com/TheAlgorithms/Python/blob/master/maths/fermat_little_theorem.py)
* [Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/maths/fibonacci.py)
* [Find Max](https://github.com/TheAlgorithms/Python/blob/master/maths/find_max.py)
* [Find Max Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/find_max_recursion.py)
* [Find Min](https://github.com/TheAlgorithms/Python/blob/master/maths/find_min.py)
* [Find Min Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/find_min_recursion.py)
* [Floor](https://github.com/TheAlgorithms/Python/blob/master/maths/floor.py)
* [Gamma](https://github.com/TheAlgorithms/Python/blob/master/maths/gamma.py)
* [Gamma Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/gamma_recursive.py)
* [Gaussian](https://github.com/TheAlgorithms/Python/blob/master/maths/gaussian.py)
* [Greatest Common Divisor](https://github.com/TheAlgorithms/Python/blob/master/maths/greatest_common_divisor.py)
* [Greedy Coin Change](https://github.com/TheAlgorithms/Python/blob/master/maths/greedy_coin_change.py)
* [Hardy Ramanujanalgo](https://github.com/TheAlgorithms/Python/blob/master/maths/hardy_ramanujanalgo.py)
* [Integration By Simpson Approx](https://github.com/TheAlgorithms/Python/blob/master/maths/integration_by_simpson_approx.py)
* [Is Ip V4 Address Valid](https://github.com/TheAlgorithms/Python/blob/master/maths/is_ip_v4_address_valid.py)
* [Is Square Free](https://github.com/TheAlgorithms/Python/blob/master/maths/is_square_free.py)
* [Jaccard Similarity](https://github.com/TheAlgorithms/Python/blob/master/maths/jaccard_similarity.py)
* [Kadanes](https://github.com/TheAlgorithms/Python/blob/master/maths/kadanes.py)
* [Karatsuba](https://github.com/TheAlgorithms/Python/blob/master/maths/karatsuba.py)
* [Krishnamurthy Number](https://github.com/TheAlgorithms/Python/blob/master/maths/krishnamurthy_number.py)
* [Kth Lexicographic Permutation](https://github.com/TheAlgorithms/Python/blob/master/maths/kth_lexicographic_permutation.py)
* [Largest Of Very Large Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/largest_of_very_large_numbers.py)
* [Largest Subarray Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/largest_subarray_sum.py)
* [Least Common Multiple](https://github.com/TheAlgorithms/Python/blob/master/maths/least_common_multiple.py)
* [Line Length](https://github.com/TheAlgorithms/Python/blob/master/maths/line_length.py)
* [Lucas Lehmer Primality Test](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py)
* [Lucas Series](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_series.py)
* [Matrix Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/maths/matrix_exponentiation.py)
* [Max Sum Sliding Window](https://github.com/TheAlgorithms/Python/blob/master/maths/max_sum_sliding_window.py)
* [Median Of Two Arrays](https://github.com/TheAlgorithms/Python/blob/master/maths/median_of_two_arrays.py)
* [Miller Rabin](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py)
* [Mobius Function](https://github.com/TheAlgorithms/Python/blob/master/maths/mobius_function.py)
* [Modular Exponential](https://github.com/TheAlgorithms/Python/blob/master/maths/modular_exponential.py)
* [Monte Carlo](https://github.com/TheAlgorithms/Python/blob/master/maths/monte_carlo.py)
* [Monte Carlo Dice](https://github.com/TheAlgorithms/Python/blob/master/maths/monte_carlo_dice.py)
* [Nevilles Method](https://github.com/TheAlgorithms/Python/blob/master/maths/nevilles_method.py)
* [Newton Raphson](https://github.com/TheAlgorithms/Python/blob/master/maths/newton_raphson.py)
* [Number Of Digits](https://github.com/TheAlgorithms/Python/blob/master/maths/number_of_digits.py)
* [Numerical Integration](https://github.com/TheAlgorithms/Python/blob/master/maths/numerical_integration.py)
* [Perfect Cube](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_cube.py)
* [Perfect Number](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_number.py)
* [Perfect Square](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_square.py)
* [Pi Monte Carlo Estimation](https://github.com/TheAlgorithms/Python/blob/master/maths/pi_monte_carlo_estimation.py)
* [Pollard Rho](https://github.com/TheAlgorithms/Python/blob/master/maths/pollard_rho.py)
* [Polynomial Evaluation](https://github.com/TheAlgorithms/Python/blob/master/maths/polynomial_evaluation.py)
* [Power Using Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/power_using_recursion.py)
* [Prime Check](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_check.py)
* [Prime Factors](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_factors.py)
* [Prime Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_numbers.py)
* [Prime Sieve Eratosthenes](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_sieve_eratosthenes.py)
* [Primelib](https://github.com/TheAlgorithms/Python/blob/master/maths/primelib.py)
* [Proth Number](https://github.com/TheAlgorithms/Python/blob/master/maths/proth_number.py)
* [Pythagoras](https://github.com/TheAlgorithms/Python/blob/master/maths/pythagoras.py)
* [Qr Decomposition](https://github.com/TheAlgorithms/Python/blob/master/maths/qr_decomposition.py)
* [Quadratic Equations Complex Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/quadratic_equations_complex_numbers.py)
* [Radians](https://github.com/TheAlgorithms/Python/blob/master/maths/radians.py)
* [Radix2 Fft](https://github.com/TheAlgorithms/Python/blob/master/maths/radix2_fft.py)
* [Relu](https://github.com/TheAlgorithms/Python/blob/master/maths/relu.py)
* [Runge Kutta](https://github.com/TheAlgorithms/Python/blob/master/maths/runge_kutta.py)
* [Segmented Sieve](https://github.com/TheAlgorithms/Python/blob/master/maths/segmented_sieve.py)
* Series
* [Arithmetic](https://github.com/TheAlgorithms/Python/blob/master/maths/series/arithmetic.py)
* [Geometric](https://github.com/TheAlgorithms/Python/blob/master/maths/series/geometric.py)
* [Geometric Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/geometric_series.py)
* [Harmonic](https://github.com/TheAlgorithms/Python/blob/master/maths/series/harmonic.py)
* [Harmonic Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/harmonic_series.py)
* [Hexagonal Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/series/hexagonal_numbers.py)
* [P Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/p_series.py)
* [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/Python/blob/master/maths/sieve_of_eratosthenes.py)
* [Sigmoid](https://github.com/TheAlgorithms/Python/blob/master/maths/sigmoid.py)
* [Simpson Rule](https://github.com/TheAlgorithms/Python/blob/master/maths/simpson_rule.py)
* [Sock Merchant](https://github.com/TheAlgorithms/Python/blob/master/maths/sock_merchant.py)
* [Softmax](https://github.com/TheAlgorithms/Python/blob/master/maths/softmax.py)
* [Square Root](https://github.com/TheAlgorithms/Python/blob/master/maths/square_root.py)
* [Sum Of Arithmetic Series](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_arithmetic_series.py)
* [Sum Of Digits](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_digits.py)
* [Sum Of Geometric Progression](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_geometric_progression.py)
* [Sylvester Sequence](https://github.com/TheAlgorithms/Python/blob/master/maths/sylvester_sequence.py)
* [Test Prime Check](https://github.com/TheAlgorithms/Python/blob/master/maths/test_prime_check.py)
* [Trapezoidal Rule](https://github.com/TheAlgorithms/Python/blob/master/maths/trapezoidal_rule.py)
* [Triplet Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/triplet_sum.py)
* [Two Pointer](https://github.com/TheAlgorithms/Python/blob/master/maths/two_pointer.py)
* [Two Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/two_sum.py)
* [Ugly Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/ugly_numbers.py)
* [Volume](https://github.com/TheAlgorithms/Python/blob/master/maths/volume.py)
* [Zellers Congruence](https://github.com/TheAlgorithms/Python/blob/master/maths/zellers_congruence.py)
## Matrix
* [Count Islands In Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/count_islands_in_matrix.py)
* [Inverse Of Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/inverse_of_matrix.py)
* [Matrix Class](https://github.com/TheAlgorithms/Python/blob/master/matrix/matrix_class.py)
* [Matrix Operation](https://github.com/TheAlgorithms/Python/blob/master/matrix/matrix_operation.py)
* [Nth Fibonacci Using Matrix Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/matrix/nth_fibonacci_using_matrix_exponentiation.py)
* [Rotate Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/rotate_matrix.py)
* [Searching In Sorted Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/searching_in_sorted_matrix.py)
* [Sherman Morrison](https://github.com/TheAlgorithms/Python/blob/master/matrix/sherman_morrison.py)
* [Spiral Print](https://github.com/TheAlgorithms/Python/blob/master/matrix/spiral_print.py)
* Tests
* [Test Matrix Operation](https://github.com/TheAlgorithms/Python/blob/master/matrix/tests/test_matrix_operation.py)
## Networking Flow
* [Ford Fulkerson](https://github.com/TheAlgorithms/Python/blob/master/networking_flow/ford_fulkerson.py)
* [Minimum Cut](https://github.com/TheAlgorithms/Python/blob/master/networking_flow/minimum_cut.py)
## Neural Network
* [2 Hidden Layers Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/2_hidden_layers_neural_network.py)
* [Back Propagation Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/convolution_neural_network.py)
* [Perceptron](https://github.com/TheAlgorithms/Python/blob/master/neural_network/perceptron.py)
## Other
* [Activity Selection](https://github.com/TheAlgorithms/Python/blob/master/other/activity_selection.py)
* [Alternative List Arrange](https://github.com/TheAlgorithms/Python/blob/master/other/alternative_list_arrange.py)
* [Check Strong Password](https://github.com/TheAlgorithms/Python/blob/master/other/check_strong_password.py)
* [Davisb Putnamb Logemannb Loveland](https://github.com/TheAlgorithms/Python/blob/master/other/davisb_putnamb_logemannb_loveland.py)
* [Dijkstra Bankers Algorithm](https://github.com/TheAlgorithms/Python/blob/master/other/dijkstra_bankers_algorithm.py)
* [Doomsday](https://github.com/TheAlgorithms/Python/blob/master/other/doomsday.py)
* [Fischer Yates Shuffle](https://github.com/TheAlgorithms/Python/blob/master/other/fischer_yates_shuffle.py)
* [Gauss Easter](https://github.com/TheAlgorithms/Python/blob/master/other/gauss_easter.py)
* [Graham Scan](https://github.com/TheAlgorithms/Python/blob/master/other/graham_scan.py)
* [Greedy](https://github.com/TheAlgorithms/Python/blob/master/other/greedy.py)
* [Least Recently Used](https://github.com/TheAlgorithms/Python/blob/master/other/least_recently_used.py)
* [Lfu Cache](https://github.com/TheAlgorithms/Python/blob/master/other/lfu_cache.py)
* [Linear Congruential Generator](https://github.com/TheAlgorithms/Python/blob/master/other/linear_congruential_generator.py)
* [Lru Cache](https://github.com/TheAlgorithms/Python/blob/master/other/lru_cache.py)
* [Magicdiamondpattern](https://github.com/TheAlgorithms/Python/blob/master/other/magicdiamondpattern.py)
* [Nested Brackets](https://github.com/TheAlgorithms/Python/blob/master/other/nested_brackets.py)
* [Password Generator](https://github.com/TheAlgorithms/Python/blob/master/other/password_generator.py)
* [Scoring Algorithm](https://github.com/TheAlgorithms/Python/blob/master/other/scoring_algorithm.py)
* [Sdes](https://github.com/TheAlgorithms/Python/blob/master/other/sdes.py)
* [Tower Of Hanoi](https://github.com/TheAlgorithms/Python/blob/master/other/tower_of_hanoi.py)
## Physics
* [N Body Simulation](https://github.com/TheAlgorithms/Python/blob/master/physics/n_body_simulation.py)
* [Newtons Second Law Of Motion](https://github.com/TheAlgorithms/Python/blob/master/physics/newtons_second_law_of_motion.py)
## Project Euler
* Problem 001
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol4.py)
* [Sol5](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol5.py)
* [Sol6](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol6.py)
* [Sol7](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol7.py)
* Problem 002
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol4.py)
* [Sol5](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol5.py)
* Problem 003
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol3.py)
* Problem 004
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_004/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_004/sol2.py)
* Problem 005
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_005/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_005/sol2.py)
* Problem 006
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol4.py)
* Problem 007
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol3.py)
* Problem 008
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol3.py)
* Problem 009
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol3.py)
* Problem 010
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol3.py)
* Problem 011
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_011/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_011/sol2.py)
* Problem 012
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_012/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_012/sol2.py)
* Problem 013
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_013/sol1.py)
* Problem 014
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_014/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_014/sol2.py)
* Problem 015
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_015/sol1.py)
* Problem 016
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_016/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_016/sol2.py)
* Problem 017
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_017/sol1.py)
* Problem 018
* [Solution](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_018/solution.py)
* Problem 019
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_019/sol1.py)
* Problem 020
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol4.py)
* Problem 021
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_021/sol1.py)
* Problem 022
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_022/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_022/sol2.py)
* Problem 023
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_023/sol1.py)
* Problem 024
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_024/sol1.py)
* Problem 025
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol3.py)
* Problem 026
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_026/sol1.py)
* Problem 027
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_027/sol1.py)
* Problem 028
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_028/sol1.py)
* Problem 029
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_029/sol1.py)
* Problem 030
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_030/sol1.py)
* Problem 031
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_031/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_031/sol2.py)
* Problem 032
* [Sol32](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_032/sol32.py)
* Problem 033
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_033/sol1.py)
* Problem 034
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_034/sol1.py)
* Problem 035
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_035/sol1.py)
* Problem 036
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_036/sol1.py)
* Problem 037
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_037/sol1.py)
* Problem 038
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_038/sol1.py)
* Problem 039
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_039/sol1.py)
* Problem 040
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_040/sol1.py)
* Problem 041
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_041/sol1.py)
* Problem 042
* [Solution42](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_042/solution42.py)
* Problem 043
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_043/sol1.py)
* Problem 044
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_044/sol1.py)
* Problem 045
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_045/sol1.py)
* Problem 046
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_046/sol1.py)
* Problem 047
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_047/sol1.py)
* Problem 048
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_048/sol1.py)
* Problem 049
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_049/sol1.py)
* Problem 050
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_050/sol1.py)
* Problem 051
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_051/sol1.py)
* Problem 052
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_052/sol1.py)
* Problem 053
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_053/sol1.py)
* Problem 054
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_054/sol1.py)
* [Test Poker Hand](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_054/test_poker_hand.py)
* Problem 055
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_055/sol1.py)
* Problem 056
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_056/sol1.py)
* Problem 057
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_057/sol1.py)
* Problem 058
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_058/sol1.py)
* Problem 059
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_059/sol1.py)
* Problem 062
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_062/sol1.py)
* Problem 063
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_063/sol1.py)
* Problem 064
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_064/sol1.py)
* Problem 065
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_065/sol1.py)
* Problem 067
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_067/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_067/sol2.py)
* Problem 069
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_069/sol1.py)
* Problem 070
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_070/sol1.py)
* Problem 071
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_071/sol1.py)
* Problem 072
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_072/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_072/sol2.py)
* Problem 074
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_074/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_074/sol2.py)
* Problem 075
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_075/sol1.py)
* Problem 076
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_076/sol1.py)
* Problem 077
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_077/sol1.py)
* Problem 078
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_078/sol1.py)
* Problem 080
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_080/sol1.py)
* Problem 081
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_081/sol1.py)
* Problem 085
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_085/sol1.py)
* Problem 086
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_086/sol1.py)
* Problem 087
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_087/sol1.py)
* Problem 089
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_089/sol1.py)
* Problem 091
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_091/sol1.py)
* Problem 092
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_092/sol1.py)
* Problem 097
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_097/sol1.py)
* Problem 099
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_099/sol1.py)
* Problem 101
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_101/sol1.py)
* Problem 102
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_102/sol1.py)
* Problem 107
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_107/sol1.py)
* Problem 109
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_109/sol1.py)
* Problem 112
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_112/sol1.py)
* Problem 113
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_113/sol1.py)
* Problem 119
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_119/sol1.py)
* Problem 120
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_120/sol1.py)
* Problem 121
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_121/sol1.py)
* Problem 123
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_123/sol1.py)
* Problem 125
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_125/sol1.py)
* Problem 129
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_129/sol1.py)
* Problem 135
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_135/sol1.py)
* Problem 144
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_144/sol1.py)
* Problem 173
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_173/sol1.py)
* Problem 174
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_174/sol1.py)
* Problem 180
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_180/sol1.py)
* Problem 188
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_188/sol1.py)
* Problem 191
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_191/sol1.py)
* Problem 203
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_203/sol1.py)
* Problem 205
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_205/sol1.py)
* Problem 206
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_206/sol1.py)
* Problem 207
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_207/sol1.py)
* Problem 234
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_234/sol1.py)
* Problem 301
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_301/sol1.py)
* Problem 493
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_493/sol1.py)
* Problem 551
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_551/sol1.py)
* Problem 686
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_686/sol1.py)
## Quantum
* [Deutsch Jozsa](https://github.com/TheAlgorithms/Python/blob/master/quantum/deutsch_jozsa.py)
* [Half Adder](https://github.com/TheAlgorithms/Python/blob/master/quantum/half_adder.py)
* [Not Gate](https://github.com/TheAlgorithms/Python/blob/master/quantum/not_gate.py)
* [Quantum Entanglement](https://github.com/TheAlgorithms/Python/blob/master/quantum/quantum_entanglement.py)
* [Ripple Adder Classic](https://github.com/TheAlgorithms/Python/blob/master/quantum/ripple_adder_classic.py)
* [Single Qubit Measure](https://github.com/TheAlgorithms/Python/blob/master/quantum/single_qubit_measure.py)
## Scheduling
* [First Come First Served](https://github.com/TheAlgorithms/Python/blob/master/scheduling/first_come_first_served.py)
* [Round Robin](https://github.com/TheAlgorithms/Python/blob/master/scheduling/round_robin.py)
* [Shortest Job First](https://github.com/TheAlgorithms/Python/blob/master/scheduling/shortest_job_first.py)
## Searches
* [Binary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/binary_search.py)
* [Binary Tree Traversal](https://github.com/TheAlgorithms/Python/blob/master/searches/binary_tree_traversal.py)
* [Double Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/double_linear_search.py)
* [Double Linear Search Recursion](https://github.com/TheAlgorithms/Python/blob/master/searches/double_linear_search_recursion.py)
* [Fibonacci Search](https://github.com/TheAlgorithms/Python/blob/master/searches/fibonacci_search.py)
* [Hill Climbing](https://github.com/TheAlgorithms/Python/blob/master/searches/hill_climbing.py)
* [Interpolation Search](https://github.com/TheAlgorithms/Python/blob/master/searches/interpolation_search.py)
* [Jump Search](https://github.com/TheAlgorithms/Python/blob/master/searches/jump_search.py)
* [Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/linear_search.py)
* [Quick Select](https://github.com/TheAlgorithms/Python/blob/master/searches/quick_select.py)
* [Sentinel Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/sentinel_linear_search.py)
* [Simple Binary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/simple_binary_search.py)
* [Simulated Annealing](https://github.com/TheAlgorithms/Python/blob/master/searches/simulated_annealing.py)
* [Tabu Search](https://github.com/TheAlgorithms/Python/blob/master/searches/tabu_search.py)
* [Ternary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/ternary_search.py)
## Sorts
* [Bead Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bead_sort.py)
* [Bitonic Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bitonic_sort.py)
* [Bogo Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bogo_sort.py)
* [Bubble Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bubble_sort.py)
* [Bucket Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bucket_sort.py)
* [Cocktail Shaker Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/cocktail_shaker_sort.py)
* [Comb Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/comb_sort.py)
* [Counting Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/counting_sort.py)
* [Cycle Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/cycle_sort.py)
* [Double Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/double_sort.py)
* [Dutch National Flag Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/dutch_national_flag_sort.py)
* [Exchange Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/exchange_sort.py)
* [External Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/external_sort.py)
* [Gnome Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/gnome_sort.py)
* [Heap Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/heap_sort.py)
* [Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/insertion_sort.py)
* [Intro Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/intro_sort.py)
* [Iterative Merge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/iterative_merge_sort.py)
* [Merge Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/merge_insertion_sort.py)
* [Merge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/merge_sort.py)
* [Msd Radix Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/msd_radix_sort.py)
* [Natural Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/natural_sort.py)
* [Odd Even Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_sort.py)
* [Odd Even Transposition Parallel](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_transposition_parallel.py)
* [Odd Even Transposition Single Threaded](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_transposition_single_threaded.py)
* [Pancake Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pancake_sort.py)
* [Patience Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/patience_sort.py)
* [Pigeon Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pigeon_sort.py)
* [Pigeonhole Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pigeonhole_sort.py)
* [Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/quick_sort.py)
* [Quick Sort 3 Partition](https://github.com/TheAlgorithms/Python/blob/master/sorts/quick_sort_3_partition.py)
* [Radix Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/radix_sort.py)
* [Random Normal Distribution Quicksort](https://github.com/TheAlgorithms/Python/blob/master/sorts/random_normal_distribution_quicksort.py)
* [Random Pivot Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/random_pivot_quick_sort.py)
* [Recursive Bubble Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_bubble_sort.py)
* [Recursive Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_insertion_sort.py)
* [Recursive Mergesort Array](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_mergesort_array.py)
* [Recursive Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_quick_sort.py)
* [Selection Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/selection_sort.py)
* [Shell Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/shell_sort.py)
* [Slowsort](https://github.com/TheAlgorithms/Python/blob/master/sorts/slowsort.py)
* [Stooge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/stooge_sort.py)
* [Strand Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/strand_sort.py)
* [Tim Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/tim_sort.py)
* [Topological Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/topological_sort.py)
* [Tree Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/tree_sort.py)
* [Unknown Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/unknown_sort.py)
* [Wiggle Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/wiggle_sort.py)
## Strings
* [Aho Corasick](https://github.com/TheAlgorithms/Python/blob/master/strings/aho_corasick.py)
* [Alternative String Arrange](https://github.com/TheAlgorithms/Python/blob/master/strings/alternative_string_arrange.py)
* [Anagrams](https://github.com/TheAlgorithms/Python/blob/master/strings/anagrams.py)
* [Autocomplete Using Trie](https://github.com/TheAlgorithms/Python/blob/master/strings/autocomplete_using_trie.py)
* [Boyer Moore Search](https://github.com/TheAlgorithms/Python/blob/master/strings/boyer_moore_search.py)
* [Can String Be Rearranged As Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/can_string_be_rearranged_as_palindrome.py)
* [Capitalize](https://github.com/TheAlgorithms/Python/blob/master/strings/capitalize.py)
* [Check Anagrams](https://github.com/TheAlgorithms/Python/blob/master/strings/check_anagrams.py)
* [Check Pangram](https://github.com/TheAlgorithms/Python/blob/master/strings/check_pangram.py)
* [Credit Card Validator](https://github.com/TheAlgorithms/Python/blob/master/strings/credit_card_validator.py)
* [Detecting English Programmatically](https://github.com/TheAlgorithms/Python/blob/master/strings/detecting_english_programmatically.py)
* [Frequency Finder](https://github.com/TheAlgorithms/Python/blob/master/strings/frequency_finder.py)
* [Indian Phone Validator](https://github.com/TheAlgorithms/Python/blob/master/strings/indian_phone_validator.py)
* [Is Contains Unique Chars](https://github.com/TheAlgorithms/Python/blob/master/strings/is_contains_unique_chars.py)
* [Is Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/is_palindrome.py)
* [Jaro Winkler](https://github.com/TheAlgorithms/Python/blob/master/strings/jaro_winkler.py)
* [Join](https://github.com/TheAlgorithms/Python/blob/master/strings/join.py)
* [Knuth Morris Pratt](https://github.com/TheAlgorithms/Python/blob/master/strings/knuth_morris_pratt.py)
* [Levenshtein Distance](https://github.com/TheAlgorithms/Python/blob/master/strings/levenshtein_distance.py)
* [Lower](https://github.com/TheAlgorithms/Python/blob/master/strings/lower.py)
* [Manacher](https://github.com/TheAlgorithms/Python/blob/master/strings/manacher.py)
* [Min Cost String Conversion](https://github.com/TheAlgorithms/Python/blob/master/strings/min_cost_string_conversion.py)
* [Naive String Search](https://github.com/TheAlgorithms/Python/blob/master/strings/naive_string_search.py)
* [Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/palindrome.py)
* [Prefix Function](https://github.com/TheAlgorithms/Python/blob/master/strings/prefix_function.py)
* [Rabin Karp](https://github.com/TheAlgorithms/Python/blob/master/strings/rabin_karp.py)
* [Remove Duplicate](https://github.com/TheAlgorithms/Python/blob/master/strings/remove_duplicate.py)
* [Reverse Letters](https://github.com/TheAlgorithms/Python/blob/master/strings/reverse_letters.py)
* [Reverse Long Words](https://github.com/TheAlgorithms/Python/blob/master/strings/reverse_long_words.py)
* [Reverse Words](https://github.com/TheAlgorithms/Python/blob/master/strings/reverse_words.py)
* [Split](https://github.com/TheAlgorithms/Python/blob/master/strings/split.py)
* [Upper](https://github.com/TheAlgorithms/Python/blob/master/strings/upper.py)
* [Wildcard Pattern Matching](https://github.com/TheAlgorithms/Python/blob/master/strings/wildcard_pattern_matching.py)
* [Word Occurrence](https://github.com/TheAlgorithms/Python/blob/master/strings/word_occurrence.py)
* [Word Patterns](https://github.com/TheAlgorithms/Python/blob/master/strings/word_patterns.py)
* [Z Function](https://github.com/TheAlgorithms/Python/blob/master/strings/z_function.py)
## Web Programming
* [Co2 Emission](https://github.com/TheAlgorithms/Python/blob/master/web_programming/co2_emission.py)
* [Covid Stats Via Xpath](https://github.com/TheAlgorithms/Python/blob/master/web_programming/covid_stats_via_xpath.py)
* [Crawl Google Results](https://github.com/TheAlgorithms/Python/blob/master/web_programming/crawl_google_results.py)
* [Crawl Google Scholar Citation](https://github.com/TheAlgorithms/Python/blob/master/web_programming/crawl_google_scholar_citation.py)
* [Currency Converter](https://github.com/TheAlgorithms/Python/blob/master/web_programming/currency_converter.py)
* [Current Stock Price](https://github.com/TheAlgorithms/Python/blob/master/web_programming/current_stock_price.py)
* [Current Weather](https://github.com/TheAlgorithms/Python/blob/master/web_programming/current_weather.py)
* [Daily Horoscope](https://github.com/TheAlgorithms/Python/blob/master/web_programming/daily_horoscope.py)
* [Download Images From Google Query](https://github.com/TheAlgorithms/Python/blob/master/web_programming/download_images_from_google_query.py)
* [Emails From Url](https://github.com/TheAlgorithms/Python/blob/master/web_programming/emails_from_url.py)
* [Fetch Bbc News](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_bbc_news.py)
* [Fetch Github Info](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_github_info.py)
* [Fetch Jobs](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_jobs.py)
* [Get Imdb Top 250 Movies Csv](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_imdb_top_250_movies_csv.py)
* [Get Imdbtop](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_imdbtop.py)
* [Get Top Hn Posts](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_top_hn_posts.py)
* [Get User Tweets](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_user_tweets.py)
* [Giphy](https://github.com/TheAlgorithms/Python/blob/master/web_programming/giphy.py)
* [Instagram Crawler](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_crawler.py)
* [Instagram Pic](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_pic.py)
* [Instagram Video](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_video.py)
* [Nasa Data](https://github.com/TheAlgorithms/Python/blob/master/web_programming/nasa_data.py)
* [Random Anime Character](https://github.com/TheAlgorithms/Python/blob/master/web_programming/random_anime_character.py)
* [Recaptcha Verification](https://github.com/TheAlgorithms/Python/blob/master/web_programming/recaptcha_verification.py)
* [Reddit](https://github.com/TheAlgorithms/Python/blob/master/web_programming/reddit.py)
* [Search Books By Isbn](https://github.com/TheAlgorithms/Python/blob/master/web_programming/search_books_by_isbn.py)
* [Slack Message](https://github.com/TheAlgorithms/Python/blob/master/web_programming/slack_message.py)
* [Test Fetch Github Info](https://github.com/TheAlgorithms/Python/blob/master/web_programming/test_fetch_github_info.py)
* [World Covid19 Stats](https://github.com/TheAlgorithms/Python/blob/master/web_programming/world_covid19_stats.py)
|
## Arithmetic Analysis
* [Bisection](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/bisection.py)
* [Gaussian Elimination](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/gaussian_elimination.py)
* [In Static Equilibrium](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/in_static_equilibrium.py)
* [Intersection](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/intersection.py)
* [Jacobi Iteration Method](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/jacobi_iteration_method.py)
* [Lu Decomposition](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/lu_decomposition.py)
* [Newton Forward Interpolation](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_forward_interpolation.py)
* [Newton Method](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_method.py)
* [Newton Raphson](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/newton_raphson.py)
* [Secant Method](https://github.com/TheAlgorithms/Python/blob/master/arithmetic_analysis/secant_method.py)
## Audio Filters
* [Butterworth Filter](https://github.com/TheAlgorithms/Python/blob/master/audio_filters/butterworth_filter.py)
* [Iir Filter](https://github.com/TheAlgorithms/Python/blob/master/audio_filters/iir_filter.py)
* [Show Response](https://github.com/TheAlgorithms/Python/blob/master/audio_filters/show_response.py)
## Backtracking
* [All Combinations](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_combinations.py)
* [All Permutations](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_permutations.py)
* [All Subsequences](https://github.com/TheAlgorithms/Python/blob/master/backtracking/all_subsequences.py)
* [Coloring](https://github.com/TheAlgorithms/Python/blob/master/backtracking/coloring.py)
* [Hamiltonian Cycle](https://github.com/TheAlgorithms/Python/blob/master/backtracking/hamiltonian_cycle.py)
* [Knight Tour](https://github.com/TheAlgorithms/Python/blob/master/backtracking/knight_tour.py)
* [Minimax](https://github.com/TheAlgorithms/Python/blob/master/backtracking/minimax.py)
* [N Queens](https://github.com/TheAlgorithms/Python/blob/master/backtracking/n_queens.py)
* [N Queens Math](https://github.com/TheAlgorithms/Python/blob/master/backtracking/n_queens_math.py)
* [Rat In Maze](https://github.com/TheAlgorithms/Python/blob/master/backtracking/rat_in_maze.py)
* [Sudoku](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sudoku.py)
* [Sum Of Subsets](https://github.com/TheAlgorithms/Python/blob/master/backtracking/sum_of_subsets.py)
## Bit Manipulation
* [Binary And Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_and_operator.py)
* [Binary Count Setbits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_count_setbits.py)
* [Binary Count Trailing Zeros](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_count_trailing_zeros.py)
* [Binary Or Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_or_operator.py)
* [Binary Shifts](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_shifts.py)
* [Binary Twos Complement](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_twos_complement.py)
* [Binary Xor Operator](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/binary_xor_operator.py)
* [Count 1S Brian Kernighan Method](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/count_1s_brian_kernighan_method.py)
* [Count Number Of One Bits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/count_number_of_one_bits.py)
* [Gray Code Sequence](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/gray_code_sequence.py)
* [Reverse Bits](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/reverse_bits.py)
* [Single Bit Manipulation Operations](https://github.com/TheAlgorithms/Python/blob/master/bit_manipulation/single_bit_manipulation_operations.py)
## Blockchain
* [Chinese Remainder Theorem](https://github.com/TheAlgorithms/Python/blob/master/blockchain/chinese_remainder_theorem.py)
* [Diophantine Equation](https://github.com/TheAlgorithms/Python/blob/master/blockchain/diophantine_equation.py)
* [Modular Division](https://github.com/TheAlgorithms/Python/blob/master/blockchain/modular_division.py)
## Boolean Algebra
* [Quine Mc Cluskey](https://github.com/TheAlgorithms/Python/blob/master/boolean_algebra/quine_mc_cluskey.py)
## Cellular Automata
* [Conways Game Of Life](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/conways_game_of_life.py)
* [Game Of Life](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/game_of_life.py)
* [Nagel Schrekenberg](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/nagel_schrekenberg.py)
* [One Dimensional](https://github.com/TheAlgorithms/Python/blob/master/cellular_automata/one_dimensional.py)
## Ciphers
* [A1Z26](https://github.com/TheAlgorithms/Python/blob/master/ciphers/a1z26.py)
* [Affine Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/affine_cipher.py)
* [Atbash](https://github.com/TheAlgorithms/Python/blob/master/ciphers/atbash.py)
* [Baconian Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/baconian_cipher.py)
* [Base16](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base16.py)
* [Base32](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base32.py)
* [Base64](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base64.py)
* [Base85](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base85.py)
* [Beaufort Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/beaufort_cipher.py)
* [Bifid](https://github.com/TheAlgorithms/Python/blob/master/ciphers/bifid.py)
* [Brute Force Caesar Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/brute_force_caesar_cipher.py)
* [Caesar Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/caesar_cipher.py)
* [Cryptomath Module](https://github.com/TheAlgorithms/Python/blob/master/ciphers/cryptomath_module.py)
* [Decrypt Caesar With Chi Squared](https://github.com/TheAlgorithms/Python/blob/master/ciphers/decrypt_caesar_with_chi_squared.py)
* [Deterministic Miller Rabin](https://github.com/TheAlgorithms/Python/blob/master/ciphers/deterministic_miller_rabin.py)
* [Diffie](https://github.com/TheAlgorithms/Python/blob/master/ciphers/diffie.py)
* [Diffie Hellman](https://github.com/TheAlgorithms/Python/blob/master/ciphers/diffie_hellman.py)
* [Elgamal Key Generator](https://github.com/TheAlgorithms/Python/blob/master/ciphers/elgamal_key_generator.py)
* [Enigma Machine2](https://github.com/TheAlgorithms/Python/blob/master/ciphers/enigma_machine2.py)
* [Hill Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/hill_cipher.py)
* [Mixed Keyword Cypher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/mixed_keyword_cypher.py)
* [Mono Alphabetic Ciphers](https://github.com/TheAlgorithms/Python/blob/master/ciphers/mono_alphabetic_ciphers.py)
* [Morse Code](https://github.com/TheAlgorithms/Python/blob/master/ciphers/morse_code.py)
* [Onepad Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/onepad_cipher.py)
* [Playfair Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/playfair_cipher.py)
* [Polybius](https://github.com/TheAlgorithms/Python/blob/master/ciphers/polybius.py)
* [Porta Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/porta_cipher.py)
* [Rabin Miller](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rabin_miller.py)
* [Rail Fence Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rail_fence_cipher.py)
* [Rot13](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rot13.py)
* [Rsa Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_cipher.py)
* [Rsa Factorization](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_factorization.py)
* [Rsa Key Generator](https://github.com/TheAlgorithms/Python/blob/master/ciphers/rsa_key_generator.py)
* [Shuffled Shift Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/shuffled_shift_cipher.py)
* [Simple Keyword Cypher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/simple_keyword_cypher.py)
* [Simple Substitution Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/simple_substitution_cipher.py)
* [Trafid Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/trafid_cipher.py)
* [Transposition Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/transposition_cipher.py)
* [Transposition Cipher Encrypt Decrypt File](https://github.com/TheAlgorithms/Python/blob/master/ciphers/transposition_cipher_encrypt_decrypt_file.py)
* [Vigenere Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/vigenere_cipher.py)
* [Xor Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/xor_cipher.py)
## Compression
* [Burrows Wheeler](https://github.com/TheAlgorithms/Python/blob/master/compression/burrows_wheeler.py)
* [Huffman](https://github.com/TheAlgorithms/Python/blob/master/compression/huffman.py)
* [Lempel Ziv](https://github.com/TheAlgorithms/Python/blob/master/compression/lempel_ziv.py)
* [Lempel Ziv Decompress](https://github.com/TheAlgorithms/Python/blob/master/compression/lempel_ziv_decompress.py)
* [Peak Signal To Noise Ratio](https://github.com/TheAlgorithms/Python/blob/master/compression/peak_signal_to_noise_ratio.py)
## Computer Vision
* [Cnn Classification](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/cnn_classification.py)
* [Flip Augmentation](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/flip_augmentation.py)
* [Harris Corner](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/harris_corner.py)
* [Mean Threshold](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/mean_threshold.py)
* [Mosaic Augmentation](https://github.com/TheAlgorithms/Python/blob/master/computer_vision/mosaic_augmentation.py)
## Conversions
* [Binary To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_decimal.py)
* [Binary To Hexadecimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_hexadecimal.py)
* [Binary To Octal](https://github.com/TheAlgorithms/Python/blob/master/conversions/binary_to_octal.py)
* [Decimal To Any](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_any.py)
* [Decimal To Binary](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_binary.py)
* [Decimal To Binary Recursion](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_binary_recursion.py)
* [Decimal To Hexadecimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_hexadecimal.py)
* [Decimal To Octal](https://github.com/TheAlgorithms/Python/blob/master/conversions/decimal_to_octal.py)
* [Hex To Bin](https://github.com/TheAlgorithms/Python/blob/master/conversions/hex_to_bin.py)
* [Hexadecimal To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/hexadecimal_to_decimal.py)
* [Length Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/length_conversion.py)
* [Molecular Chemistry](https://github.com/TheAlgorithms/Python/blob/master/conversions/molecular_chemistry.py)
* [Octal To Decimal](https://github.com/TheAlgorithms/Python/blob/master/conversions/octal_to_decimal.py)
* [Prefix Conversions](https://github.com/TheAlgorithms/Python/blob/master/conversions/prefix_conversions.py)
* [Pressure Conversions](https://github.com/TheAlgorithms/Python/blob/master/conversions/pressure_conversions.py)
* [Rgb Hsv Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/rgb_hsv_conversion.py)
* [Roman Numerals](https://github.com/TheAlgorithms/Python/blob/master/conversions/roman_numerals.py)
* [Temperature Conversions](https://github.com/TheAlgorithms/Python/blob/master/conversions/temperature_conversions.py)
* [Volume Conversions](https://github.com/TheAlgorithms/Python/blob/master/conversions/volume_conversions.py)
* [Weight Conversion](https://github.com/TheAlgorithms/Python/blob/master/conversions/weight_conversion.py)
## Data Structures
* Binary Tree
* [Avl Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/avl_tree.py)
* [Basic Binary Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/basic_binary_tree.py)
* [Binary Search Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_search_tree.py)
* [Binary Search Tree Recursive](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_search_tree_recursive.py)
* [Binary Tree Mirror](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_tree_mirror.py)
* [Binary Tree Traversals](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/binary_tree_traversals.py)
* [Fenwick Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/fenwick_tree.py)
* [Lazy Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/lazy_segment_tree.py)
* [Lowest Common Ancestor](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/lowest_common_ancestor.py)
* [Merge Two Binary Trees](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/merge_two_binary_trees.py)
* [Non Recursive Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/non_recursive_segment_tree.py)
* [Number Of Possible Binary Trees](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/number_of_possible_binary_trees.py)
* [Red Black Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/red_black_tree.py)
* [Segment Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/segment_tree.py)
* [Segment Tree Other](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/segment_tree_other.py)
* [Treap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/treap.py)
* [Wavelet Tree](https://github.com/TheAlgorithms/Python/blob/master/data_structures/binary_tree/wavelet_tree.py)
* Disjoint Set
* [Alternate Disjoint Set](https://github.com/TheAlgorithms/Python/blob/master/data_structures/disjoint_set/alternate_disjoint_set.py)
* [Disjoint Set](https://github.com/TheAlgorithms/Python/blob/master/data_structures/disjoint_set/disjoint_set.py)
* Hashing
* [Double Hash](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/double_hash.py)
* [Hash Table](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/hash_table.py)
* [Hash Table With Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/hash_table_with_linked_list.py)
* Number Theory
* [Prime Numbers](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/number_theory/prime_numbers.py)
* [Quadratic Probing](https://github.com/TheAlgorithms/Python/blob/master/data_structures/hashing/quadratic_probing.py)
* Heap
* [Binomial Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/binomial_heap.py)
* [Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/heap.py)
* [Heap Generic](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/heap_generic.py)
* [Max Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/max_heap.py)
* [Min Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/min_heap.py)
* [Randomized Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/randomized_heap.py)
* [Skew Heap](https://github.com/TheAlgorithms/Python/blob/master/data_structures/heap/skew_heap.py)
* Linked List
* [Circular Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/circular_linked_list.py)
* [Deque Doubly](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/deque_doubly.py)
* [Doubly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/doubly_linked_list.py)
* [Doubly Linked List Two](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/doubly_linked_list_two.py)
* [From Sequence](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/from_sequence.py)
* [Has Loop](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/has_loop.py)
* [Is Palindrome](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/is_palindrome.py)
* [Merge Two Lists](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/merge_two_lists.py)
* [Middle Element Of Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/middle_element_of_linked_list.py)
* [Print Reverse](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/print_reverse.py)
* [Singly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/singly_linked_list.py)
* [Skip List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/skip_list.py)
* [Swap Nodes](https://github.com/TheAlgorithms/Python/blob/master/data_structures/linked_list/swap_nodes.py)
* Queue
* [Circular Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/circular_queue.py)
* [Circular Queue Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/circular_queue_linked_list.py)
* [Double Ended Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/double_ended_queue.py)
* [Linked Queue](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/linked_queue.py)
* [Priority Queue Using List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/priority_queue_using_list.py)
* [Queue On List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/queue_on_list.py)
* [Queue On Pseudo Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/queue/queue_on_pseudo_stack.py)
* Stacks
* [Balanced Parentheses](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/balanced_parentheses.py)
* [Dijkstras Two Stack Algorithm](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/dijkstras_two_stack_algorithm.py)
* [Evaluate Postfix Notations](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/evaluate_postfix_notations.py)
* [Infix To Postfix Conversion](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/infix_to_postfix_conversion.py)
* [Infix To Prefix Conversion](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/infix_to_prefix_conversion.py)
* [Next Greater Element](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/next_greater_element.py)
* [Postfix Evaluation](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/postfix_evaluation.py)
* [Prefix Evaluation](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/prefix_evaluation.py)
* [Stack](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stack.py)
* [Stack With Doubly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stack_with_doubly_linked_list.py)
* [Stack With Singly Linked List](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stack_with_singly_linked_list.py)
* [Stock Span Problem](https://github.com/TheAlgorithms/Python/blob/master/data_structures/stacks/stock_span_problem.py)
* Trie
* [Trie](https://github.com/TheAlgorithms/Python/blob/master/data_structures/trie/trie.py)
## Digital Image Processing
* [Change Brightness](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/change_brightness.py)
* [Change Contrast](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/change_contrast.py)
* [Convert To Negative](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/convert_to_negative.py)
* Dithering
* [Burkes](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/dithering/burkes.py)
* Edge Detection
* [Canny](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/edge_detection/canny.py)
* Filters
* [Bilateral Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/bilateral_filter.py)
* [Convolve](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/convolve.py)
* [Gabor Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/gabor_filter.py)
* [Gaussian Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/gaussian_filter.py)
* [Median Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/median_filter.py)
* [Sobel Filter](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/filters/sobel_filter.py)
* Histogram Equalization
* [Histogram Stretch](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/histogram_equalization/histogram_stretch.py)
* [Index Calculation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/index_calculation.py)
* Morphological Operations
* [Dilation Operation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/morphological_operations/dilation_operation.py)
* [Erosion Operation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/morphological_operations/erosion_operation.py)
* Resize
* [Resize](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/resize/resize.py)
* Rotation
* [Rotation](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/rotation/rotation.py)
* [Sepia](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/sepia.py)
* [Test Digital Image Processing](https://github.com/TheAlgorithms/Python/blob/master/digital_image_processing/test_digital_image_processing.py)
## Divide And Conquer
* [Closest Pair Of Points](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/closest_pair_of_points.py)
* [Convex Hull](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/convex_hull.py)
* [Heaps Algorithm](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/heaps_algorithm.py)
* [Heaps Algorithm Iterative](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/heaps_algorithm_iterative.py)
* [Inversions](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/inversions.py)
* [Kth Order Statistic](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/kth_order_statistic.py)
* [Max Difference Pair](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/max_difference_pair.py)
* [Max Subarray Sum](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/max_subarray_sum.py)
* [Mergesort](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/mergesort.py)
* [Peak](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/peak.py)
* [Power](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/power.py)
* [Strassen Matrix Multiplication](https://github.com/TheAlgorithms/Python/blob/master/divide_and_conquer/strassen_matrix_multiplication.py)
## Dynamic Programming
* [Abbreviation](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/abbreviation.py)
* [All Construct](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/all_construct.py)
* [Bitmask](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/bitmask.py)
* [Catalan Numbers](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/catalan_numbers.py)
* [Climbing Stairs](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/climbing_stairs.py)
* [Edit Distance](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/edit_distance.py)
* [Factorial](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/factorial.py)
* [Fast Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fast_fibonacci.py)
* [Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fibonacci.py)
* [Floyd Warshall](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/floyd_warshall.py)
* [Fractional Knapsack](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fractional_knapsack.py)
* [Fractional Knapsack 2](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/fractional_knapsack_2.py)
* [Integer Partition](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/integer_partition.py)
* [Iterating Through Submasks](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/iterating_through_submasks.py)
* [Knapsack](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/knapsack.py)
* [Longest Common Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_common_subsequence.py)
* [Longest Increasing Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_increasing_subsequence.py)
* [Longest Increasing Subsequence O(Nlogn)](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_increasing_subsequence_o(nlogn).py)
* [Longest Sub Array](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/longest_sub_array.py)
* [Matrix Chain Order](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/matrix_chain_order.py)
* [Max Non Adjacent Sum](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_non_adjacent_sum.py)
* [Max Sub Array](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_sub_array.py)
* [Max Sum Contiguous Subsequence](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/max_sum_contiguous_subsequence.py)
* [Minimum Coin Change](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_coin_change.py)
* [Minimum Cost Path](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_cost_path.py)
* [Minimum Partition](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_partition.py)
* [Minimum Steps To One](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/minimum_steps_to_one.py)
* [Optimal Binary Search Tree](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/optimal_binary_search_tree.py)
* [Rod Cutting](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/rod_cutting.py)
* [Subset Generation](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/subset_generation.py)
* [Sum Of Subset](https://github.com/TheAlgorithms/Python/blob/master/dynamic_programming/sum_of_subset.py)
## Electronics
* [Carrier Concentration](https://github.com/TheAlgorithms/Python/blob/master/electronics/carrier_concentration.py)
* [Coulombs Law](https://github.com/TheAlgorithms/Python/blob/master/electronics/coulombs_law.py)
* [Electric Power](https://github.com/TheAlgorithms/Python/blob/master/electronics/electric_power.py)
* [Ohms Law](https://github.com/TheAlgorithms/Python/blob/master/electronics/ohms_law.py)
## File Transfer
* [Receive File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/receive_file.py)
* [Send File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/send_file.py)
* Tests
* [Test Send File](https://github.com/TheAlgorithms/Python/blob/master/file_transfer/tests/test_send_file.py)
## Financial
* [Equated Monthly Installments](https://github.com/TheAlgorithms/Python/blob/master/financial/equated_monthly_installments.py)
* [Interest](https://github.com/TheAlgorithms/Python/blob/master/financial/interest.py)
## Fractals
* [Julia Sets](https://github.com/TheAlgorithms/Python/blob/master/fractals/julia_sets.py)
* [Koch Snowflake](https://github.com/TheAlgorithms/Python/blob/master/fractals/koch_snowflake.py)
* [Mandelbrot](https://github.com/TheAlgorithms/Python/blob/master/fractals/mandelbrot.py)
* [Sierpinski Triangle](https://github.com/TheAlgorithms/Python/blob/master/fractals/sierpinski_triangle.py)
## Fuzzy Logic
* [Fuzzy Operations](https://github.com/TheAlgorithms/Python/blob/master/fuzzy_logic/fuzzy_operations.py)
## Genetic Algorithm
* [Basic String](https://github.com/TheAlgorithms/Python/blob/master/genetic_algorithm/basic_string.py)
## Geodesy
* [Haversine Distance](https://github.com/TheAlgorithms/Python/blob/master/geodesy/haversine_distance.py)
* [Lamberts Ellipsoidal Distance](https://github.com/TheAlgorithms/Python/blob/master/geodesy/lamberts_ellipsoidal_distance.py)
## Graphics
* [Bezier Curve](https://github.com/TheAlgorithms/Python/blob/master/graphics/bezier_curve.py)
* [Vector3 For 2D Rendering](https://github.com/TheAlgorithms/Python/blob/master/graphics/vector3_for_2d_rendering.py)
## Graphs
* [A Star](https://github.com/TheAlgorithms/Python/blob/master/graphs/a_star.py)
* [Articulation Points](https://github.com/TheAlgorithms/Python/blob/master/graphs/articulation_points.py)
* [Basic Graphs](https://github.com/TheAlgorithms/Python/blob/master/graphs/basic_graphs.py)
* [Bellman Ford](https://github.com/TheAlgorithms/Python/blob/master/graphs/bellman_ford.py)
* [Bfs Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/bfs_shortest_path.py)
* [Bfs Zero One Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/bfs_zero_one_shortest_path.py)
* [Bidirectional A Star](https://github.com/TheAlgorithms/Python/blob/master/graphs/bidirectional_a_star.py)
* [Bidirectional Breadth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/bidirectional_breadth_first_search.py)
* [Boruvka](https://github.com/TheAlgorithms/Python/blob/master/graphs/boruvka.py)
* [Breadth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search.py)
* [Breadth First Search 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search_2.py)
* [Breadth First Search Shortest Path](https://github.com/TheAlgorithms/Python/blob/master/graphs/breadth_first_search_shortest_path.py)
* [Check Bipartite Graph Bfs](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_bipartite_graph_bfs.py)
* [Check Bipartite Graph Dfs](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_bipartite_graph_dfs.py)
* [Check Cycle](https://github.com/TheAlgorithms/Python/blob/master/graphs/check_cycle.py)
* [Connected Components](https://github.com/TheAlgorithms/Python/blob/master/graphs/connected_components.py)
* [Depth First Search](https://github.com/TheAlgorithms/Python/blob/master/graphs/depth_first_search.py)
* [Depth First Search 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/depth_first_search_2.py)
* [Dijkstra](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra.py)
* [Dijkstra 2](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra_2.py)
* [Dijkstra Algorithm](https://github.com/TheAlgorithms/Python/blob/master/graphs/dijkstra_algorithm.py)
* [Dinic](https://github.com/TheAlgorithms/Python/blob/master/graphs/dinic.py)
* [Directed And Undirected (Weighted) Graph](https://github.com/TheAlgorithms/Python/blob/master/graphs/directed_and_undirected_(weighted)_graph.py)
* [Edmonds Karp Multiple Source And Sink](https://github.com/TheAlgorithms/Python/blob/master/graphs/edmonds_karp_multiple_source_and_sink.py)
* [Eulerian Path And Circuit For Undirected Graph](https://github.com/TheAlgorithms/Python/blob/master/graphs/eulerian_path_and_circuit_for_undirected_graph.py)
* [Even Tree](https://github.com/TheAlgorithms/Python/blob/master/graphs/even_tree.py)
* [Finding Bridges](https://github.com/TheAlgorithms/Python/blob/master/graphs/finding_bridges.py)
* [Frequent Pattern Graph Miner](https://github.com/TheAlgorithms/Python/blob/master/graphs/frequent_pattern_graph_miner.py)
* [G Topological Sort](https://github.com/TheAlgorithms/Python/blob/master/graphs/g_topological_sort.py)
* [Gale Shapley Bigraph](https://github.com/TheAlgorithms/Python/blob/master/graphs/gale_shapley_bigraph.py)
* [Graph List](https://github.com/TheAlgorithms/Python/blob/master/graphs/graph_list.py)
* [Graph Matrix](https://github.com/TheAlgorithms/Python/blob/master/graphs/graph_matrix.py)
* [Graphs Floyd Warshall](https://github.com/TheAlgorithms/Python/blob/master/graphs/graphs_floyd_warshall.py)
* [Greedy Best First](https://github.com/TheAlgorithms/Python/blob/master/graphs/greedy_best_first.py)
* [Greedy Min Vertex Cover](https://github.com/TheAlgorithms/Python/blob/master/graphs/greedy_min_vertex_cover.py)
* [Kahns Algorithm Long](https://github.com/TheAlgorithms/Python/blob/master/graphs/kahns_algorithm_long.py)
* [Kahns Algorithm Topo](https://github.com/TheAlgorithms/Python/blob/master/graphs/kahns_algorithm_topo.py)
* [Karger](https://github.com/TheAlgorithms/Python/blob/master/graphs/karger.py)
* [Markov Chain](https://github.com/TheAlgorithms/Python/blob/master/graphs/markov_chain.py)
* [Matching Min Vertex Cover](https://github.com/TheAlgorithms/Python/blob/master/graphs/matching_min_vertex_cover.py)
* [Minimum Spanning Tree Boruvka](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_boruvka.py)
* [Minimum Spanning Tree Kruskal](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_kruskal.py)
* [Minimum Spanning Tree Kruskal2](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_kruskal2.py)
* [Minimum Spanning Tree Prims](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_prims.py)
* [Minimum Spanning Tree Prims2](https://github.com/TheAlgorithms/Python/blob/master/graphs/minimum_spanning_tree_prims2.py)
* [Multi Heuristic Astar](https://github.com/TheAlgorithms/Python/blob/master/graphs/multi_heuristic_astar.py)
* [Page Rank](https://github.com/TheAlgorithms/Python/blob/master/graphs/page_rank.py)
* [Prim](https://github.com/TheAlgorithms/Python/blob/master/graphs/prim.py)
* [Random Graph Generator](https://github.com/TheAlgorithms/Python/blob/master/graphs/random_graph_generator.py)
* [Scc Kosaraju](https://github.com/TheAlgorithms/Python/blob/master/graphs/scc_kosaraju.py)
* [Strongly Connected Components](https://github.com/TheAlgorithms/Python/blob/master/graphs/strongly_connected_components.py)
* [Tarjans Scc](https://github.com/TheAlgorithms/Python/blob/master/graphs/tarjans_scc.py)
* Tests
* [Test Min Spanning Tree Kruskal](https://github.com/TheAlgorithms/Python/blob/master/graphs/tests/test_min_spanning_tree_kruskal.py)
* [Test Min Spanning Tree Prim](https://github.com/TheAlgorithms/Python/blob/master/graphs/tests/test_min_spanning_tree_prim.py)
## Greedy Methods
* [Optimal Merge Pattern](https://github.com/TheAlgorithms/Python/blob/master/greedy_methods/optimal_merge_pattern.py)
## Hashes
* [Adler32](https://github.com/TheAlgorithms/Python/blob/master/hashes/adler32.py)
* [Chaos Machine](https://github.com/TheAlgorithms/Python/blob/master/hashes/chaos_machine.py)
* [Djb2](https://github.com/TheAlgorithms/Python/blob/master/hashes/djb2.py)
* [Enigma Machine](https://github.com/TheAlgorithms/Python/blob/master/hashes/enigma_machine.py)
* [Hamming Code](https://github.com/TheAlgorithms/Python/blob/master/hashes/hamming_code.py)
* [Luhn](https://github.com/TheAlgorithms/Python/blob/master/hashes/luhn.py)
* [Md5](https://github.com/TheAlgorithms/Python/blob/master/hashes/md5.py)
* [Sdbm](https://github.com/TheAlgorithms/Python/blob/master/hashes/sdbm.py)
* [Sha1](https://github.com/TheAlgorithms/Python/blob/master/hashes/sha1.py)
* [Sha256](https://github.com/TheAlgorithms/Python/blob/master/hashes/sha256.py)
## Knapsack
* [Greedy Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/greedy_knapsack.py)
* [Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/knapsack.py)
* Tests
* [Test Greedy Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/tests/test_greedy_knapsack.py)
* [Test Knapsack](https://github.com/TheAlgorithms/Python/blob/master/knapsack/tests/test_knapsack.py)
## Linear Algebra
* Src
* [Conjugate Gradient](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/conjugate_gradient.py)
* [Lib](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/lib.py)
* [Polynom For Points](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/polynom_for_points.py)
* [Power Iteration](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/power_iteration.py)
* [Rayleigh Quotient](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/rayleigh_quotient.py)
* [Schur Complement](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/schur_complement.py)
* [Test Linear Algebra](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/test_linear_algebra.py)
* [Transformations 2D](https://github.com/TheAlgorithms/Python/blob/master/linear_algebra/src/transformations_2d.py)
## Machine Learning
* [Astar](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/astar.py)
* [Data Transformations](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/data_transformations.py)
* [Decision Tree](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/decision_tree.py)
* Forecasting
* [Run](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/forecasting/run.py)
* [Gaussian Naive Bayes](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gaussian_naive_bayes.py)
* [Gradient Boosting Regressor](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gradient_boosting_regressor.py)
* [Gradient Descent](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/gradient_descent.py)
* [K Means Clust](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/k_means_clust.py)
* [K Nearest Neighbours](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/k_nearest_neighbours.py)
* [Knn Sklearn](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/knn_sklearn.py)
* [Linear Discriminant Analysis](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/linear_discriminant_analysis.py)
* [Linear Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/linear_regression.py)
* Local Weighted Learning
* [Local Weighted Learning](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/local_weighted_learning/local_weighted_learning.py)
* [Logistic Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/logistic_regression.py)
* Lstm
* [Lstm Prediction](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/lstm/lstm_prediction.py)
* [Multilayer Perceptron Classifier](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/multilayer_perceptron_classifier.py)
* [Polymonial Regression](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/polymonial_regression.py)
* [Random Forest Classifier](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/random_forest_classifier.py)
* [Random Forest Regressor](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/random_forest_regressor.py)
* [Scoring Functions](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/scoring_functions.py)
* [Sequential Minimum Optimization](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/sequential_minimum_optimization.py)
* [Similarity Search](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/similarity_search.py)
* [Support Vector Machines](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/support_vector_machines.py)
* [Word Frequency Functions](https://github.com/TheAlgorithms/Python/blob/master/machine_learning/word_frequency_functions.py)
## Maths
* [3N Plus 1](https://github.com/TheAlgorithms/Python/blob/master/maths/3n_plus_1.py)
* [Abs](https://github.com/TheAlgorithms/Python/blob/master/maths/abs.py)
* [Abs Max](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_max.py)
* [Abs Min](https://github.com/TheAlgorithms/Python/blob/master/maths/abs_min.py)
* [Add](https://github.com/TheAlgorithms/Python/blob/master/maths/add.py)
* [Aliquot Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/aliquot_sum.py)
* [Allocation Number](https://github.com/TheAlgorithms/Python/blob/master/maths/allocation_number.py)
* [Area](https://github.com/TheAlgorithms/Python/blob/master/maths/area.py)
* [Area Under Curve](https://github.com/TheAlgorithms/Python/blob/master/maths/area_under_curve.py)
* [Armstrong Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/armstrong_numbers.py)
* [Average Mean](https://github.com/TheAlgorithms/Python/blob/master/maths/average_mean.py)
* [Average Median](https://github.com/TheAlgorithms/Python/blob/master/maths/average_median.py)
* [Average Mode](https://github.com/TheAlgorithms/Python/blob/master/maths/average_mode.py)
* [Bailey Borwein Plouffe](https://github.com/TheAlgorithms/Python/blob/master/maths/bailey_borwein_plouffe.py)
* [Basic Maths](https://github.com/TheAlgorithms/Python/blob/master/maths/basic_maths.py)
* [Binary Exp Mod](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exp_mod.py)
* [Binary Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation.py)
* [Binary Exponentiation 2](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation_2.py)
* [Binary Exponentiation 3](https://github.com/TheAlgorithms/Python/blob/master/maths/binary_exponentiation_3.py)
* [Binomial Coefficient](https://github.com/TheAlgorithms/Python/blob/master/maths/binomial_coefficient.py)
* [Binomial Distribution](https://github.com/TheAlgorithms/Python/blob/master/maths/binomial_distribution.py)
* [Bisection](https://github.com/TheAlgorithms/Python/blob/master/maths/bisection.py)
* [Ceil](https://github.com/TheAlgorithms/Python/blob/master/maths/ceil.py)
* [Check Polygon](https://github.com/TheAlgorithms/Python/blob/master/maths/check_polygon.py)
* [Chudnovsky Algorithm](https://github.com/TheAlgorithms/Python/blob/master/maths/chudnovsky_algorithm.py)
* [Collatz Sequence](https://github.com/TheAlgorithms/Python/blob/master/maths/collatz_sequence.py)
* [Combinations](https://github.com/TheAlgorithms/Python/blob/master/maths/combinations.py)
* [Decimal Isolate](https://github.com/TheAlgorithms/Python/blob/master/maths/decimal_isolate.py)
* [Double Factorial Iterative](https://github.com/TheAlgorithms/Python/blob/master/maths/double_factorial_iterative.py)
* [Double Factorial Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/double_factorial_recursive.py)
* [Entropy](https://github.com/TheAlgorithms/Python/blob/master/maths/entropy.py)
* [Euclidean Distance](https://github.com/TheAlgorithms/Python/blob/master/maths/euclidean_distance.py)
* [Euclidean Gcd](https://github.com/TheAlgorithms/Python/blob/master/maths/euclidean_gcd.py)
* [Euler Method](https://github.com/TheAlgorithms/Python/blob/master/maths/euler_method.py)
* [Euler Modified](https://github.com/TheAlgorithms/Python/blob/master/maths/euler_modified.py)
* [Eulers Totient](https://github.com/TheAlgorithms/Python/blob/master/maths/eulers_totient.py)
* [Extended Euclidean Algorithm](https://github.com/TheAlgorithms/Python/blob/master/maths/extended_euclidean_algorithm.py)
* [Factorial Iterative](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_iterative.py)
* [Factorial Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/factorial_recursive.py)
* [Factors](https://github.com/TheAlgorithms/Python/blob/master/maths/factors.py)
* [Fermat Little Theorem](https://github.com/TheAlgorithms/Python/blob/master/maths/fermat_little_theorem.py)
* [Fibonacci](https://github.com/TheAlgorithms/Python/blob/master/maths/fibonacci.py)
* [Find Max](https://github.com/TheAlgorithms/Python/blob/master/maths/find_max.py)
* [Find Max Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/find_max_recursion.py)
* [Find Min](https://github.com/TheAlgorithms/Python/blob/master/maths/find_min.py)
* [Find Min Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/find_min_recursion.py)
* [Floor](https://github.com/TheAlgorithms/Python/blob/master/maths/floor.py)
* [Gamma](https://github.com/TheAlgorithms/Python/blob/master/maths/gamma.py)
* [Gamma Recursive](https://github.com/TheAlgorithms/Python/blob/master/maths/gamma_recursive.py)
* [Gaussian](https://github.com/TheAlgorithms/Python/blob/master/maths/gaussian.py)
* [Greatest Common Divisor](https://github.com/TheAlgorithms/Python/blob/master/maths/greatest_common_divisor.py)
* [Greedy Coin Change](https://github.com/TheAlgorithms/Python/blob/master/maths/greedy_coin_change.py)
* [Hardy Ramanujanalgo](https://github.com/TheAlgorithms/Python/blob/master/maths/hardy_ramanujanalgo.py)
* [Integration By Simpson Approx](https://github.com/TheAlgorithms/Python/blob/master/maths/integration_by_simpson_approx.py)
* [Is Ip V4 Address Valid](https://github.com/TheAlgorithms/Python/blob/master/maths/is_ip_v4_address_valid.py)
* [Is Square Free](https://github.com/TheAlgorithms/Python/blob/master/maths/is_square_free.py)
* [Jaccard Similarity](https://github.com/TheAlgorithms/Python/blob/master/maths/jaccard_similarity.py)
* [Kadanes](https://github.com/TheAlgorithms/Python/blob/master/maths/kadanes.py)
* [Karatsuba](https://github.com/TheAlgorithms/Python/blob/master/maths/karatsuba.py)
* [Krishnamurthy Number](https://github.com/TheAlgorithms/Python/blob/master/maths/krishnamurthy_number.py)
* [Kth Lexicographic Permutation](https://github.com/TheAlgorithms/Python/blob/master/maths/kth_lexicographic_permutation.py)
* [Largest Of Very Large Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/largest_of_very_large_numbers.py)
* [Largest Subarray Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/largest_subarray_sum.py)
* [Least Common Multiple](https://github.com/TheAlgorithms/Python/blob/master/maths/least_common_multiple.py)
* [Line Length](https://github.com/TheAlgorithms/Python/blob/master/maths/line_length.py)
* [Lucas Lehmer Primality Test](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py)
* [Lucas Series](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_series.py)
* [Matrix Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/maths/matrix_exponentiation.py)
* [Max Sum Sliding Window](https://github.com/TheAlgorithms/Python/blob/master/maths/max_sum_sliding_window.py)
* [Median Of Two Arrays](https://github.com/TheAlgorithms/Python/blob/master/maths/median_of_two_arrays.py)
* [Miller Rabin](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py)
* [Mobius Function](https://github.com/TheAlgorithms/Python/blob/master/maths/mobius_function.py)
* [Modular Exponential](https://github.com/TheAlgorithms/Python/blob/master/maths/modular_exponential.py)
* [Monte Carlo](https://github.com/TheAlgorithms/Python/blob/master/maths/monte_carlo.py)
* [Monte Carlo Dice](https://github.com/TheAlgorithms/Python/blob/master/maths/monte_carlo_dice.py)
* [Nevilles Method](https://github.com/TheAlgorithms/Python/blob/master/maths/nevilles_method.py)
* [Newton Raphson](https://github.com/TheAlgorithms/Python/blob/master/maths/newton_raphson.py)
* [Number Of Digits](https://github.com/TheAlgorithms/Python/blob/master/maths/number_of_digits.py)
* [Numerical Integration](https://github.com/TheAlgorithms/Python/blob/master/maths/numerical_integration.py)
* [Perfect Cube](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_cube.py)
* [Perfect Number](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_number.py)
* [Perfect Square](https://github.com/TheAlgorithms/Python/blob/master/maths/perfect_square.py)
* [Pi Monte Carlo Estimation](https://github.com/TheAlgorithms/Python/blob/master/maths/pi_monte_carlo_estimation.py)
* [Pollard Rho](https://github.com/TheAlgorithms/Python/blob/master/maths/pollard_rho.py)
* [Polynomial Evaluation](https://github.com/TheAlgorithms/Python/blob/master/maths/polynomial_evaluation.py)
* [Power Using Recursion](https://github.com/TheAlgorithms/Python/blob/master/maths/power_using_recursion.py)
* [Prime Check](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_check.py)
* [Prime Factors](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_factors.py)
* [Prime Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_numbers.py)
* [Prime Sieve Eratosthenes](https://github.com/TheAlgorithms/Python/blob/master/maths/prime_sieve_eratosthenes.py)
* [Primelib](https://github.com/TheAlgorithms/Python/blob/master/maths/primelib.py)
* [Proth Number](https://github.com/TheAlgorithms/Python/blob/master/maths/proth_number.py)
* [Pythagoras](https://github.com/TheAlgorithms/Python/blob/master/maths/pythagoras.py)
* [Qr Decomposition](https://github.com/TheAlgorithms/Python/blob/master/maths/qr_decomposition.py)
* [Quadratic Equations Complex Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/quadratic_equations_complex_numbers.py)
* [Radians](https://github.com/TheAlgorithms/Python/blob/master/maths/radians.py)
* [Radix2 Fft](https://github.com/TheAlgorithms/Python/blob/master/maths/radix2_fft.py)
* [Relu](https://github.com/TheAlgorithms/Python/blob/master/maths/relu.py)
* [Runge Kutta](https://github.com/TheAlgorithms/Python/blob/master/maths/runge_kutta.py)
* [Segmented Sieve](https://github.com/TheAlgorithms/Python/blob/master/maths/segmented_sieve.py)
* Series
* [Arithmetic](https://github.com/TheAlgorithms/Python/blob/master/maths/series/arithmetic.py)
* [Geometric](https://github.com/TheAlgorithms/Python/blob/master/maths/series/geometric.py)
* [Geometric Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/geometric_series.py)
* [Harmonic](https://github.com/TheAlgorithms/Python/blob/master/maths/series/harmonic.py)
* [Harmonic Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/harmonic_series.py)
* [Hexagonal Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/series/hexagonal_numbers.py)
* [P Series](https://github.com/TheAlgorithms/Python/blob/master/maths/series/p_series.py)
* [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/Python/blob/master/maths/sieve_of_eratosthenes.py)
* [Sigmoid](https://github.com/TheAlgorithms/Python/blob/master/maths/sigmoid.py)
* [Simpson Rule](https://github.com/TheAlgorithms/Python/blob/master/maths/simpson_rule.py)
* [Sock Merchant](https://github.com/TheAlgorithms/Python/blob/master/maths/sock_merchant.py)
* [Softmax](https://github.com/TheAlgorithms/Python/blob/master/maths/softmax.py)
* [Square Root](https://github.com/TheAlgorithms/Python/blob/master/maths/square_root.py)
* [Sum Of Arithmetic Series](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_arithmetic_series.py)
* [Sum Of Digits](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_digits.py)
* [Sum Of Geometric Progression](https://github.com/TheAlgorithms/Python/blob/master/maths/sum_of_geometric_progression.py)
* [Sylvester Sequence](https://github.com/TheAlgorithms/Python/blob/master/maths/sylvester_sequence.py)
* [Test Prime Check](https://github.com/TheAlgorithms/Python/blob/master/maths/test_prime_check.py)
* [Trapezoidal Rule](https://github.com/TheAlgorithms/Python/blob/master/maths/trapezoidal_rule.py)
* [Triplet Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/triplet_sum.py)
* [Two Pointer](https://github.com/TheAlgorithms/Python/blob/master/maths/two_pointer.py)
* [Two Sum](https://github.com/TheAlgorithms/Python/blob/master/maths/two_sum.py)
* [Ugly Numbers](https://github.com/TheAlgorithms/Python/blob/master/maths/ugly_numbers.py)
* [Volume](https://github.com/TheAlgorithms/Python/blob/master/maths/volume.py)
* [Zellers Congruence](https://github.com/TheAlgorithms/Python/blob/master/maths/zellers_congruence.py)
## Matrix
* [Count Islands In Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/count_islands_in_matrix.py)
* [Inverse Of Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/inverse_of_matrix.py)
* [Matrix Class](https://github.com/TheAlgorithms/Python/blob/master/matrix/matrix_class.py)
* [Matrix Operation](https://github.com/TheAlgorithms/Python/blob/master/matrix/matrix_operation.py)
* [Nth Fibonacci Using Matrix Exponentiation](https://github.com/TheAlgorithms/Python/blob/master/matrix/nth_fibonacci_using_matrix_exponentiation.py)
* [Rotate Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/rotate_matrix.py)
* [Searching In Sorted Matrix](https://github.com/TheAlgorithms/Python/blob/master/matrix/searching_in_sorted_matrix.py)
* [Sherman Morrison](https://github.com/TheAlgorithms/Python/blob/master/matrix/sherman_morrison.py)
* [Spiral Print](https://github.com/TheAlgorithms/Python/blob/master/matrix/spiral_print.py)
* Tests
* [Test Matrix Operation](https://github.com/TheAlgorithms/Python/blob/master/matrix/tests/test_matrix_operation.py)
## Networking Flow
* [Ford Fulkerson](https://github.com/TheAlgorithms/Python/blob/master/networking_flow/ford_fulkerson.py)
* [Minimum Cut](https://github.com/TheAlgorithms/Python/blob/master/networking_flow/minimum_cut.py)
## Neural Network
* [2 Hidden Layers Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/2_hidden_layers_neural_network.py)
* [Back Propagation Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](https://github.com/TheAlgorithms/Python/blob/master/neural_network/convolution_neural_network.py)
* [Perceptron](https://github.com/TheAlgorithms/Python/blob/master/neural_network/perceptron.py)
## Other
* [Activity Selection](https://github.com/TheAlgorithms/Python/blob/master/other/activity_selection.py)
* [Alternative List Arrange](https://github.com/TheAlgorithms/Python/blob/master/other/alternative_list_arrange.py)
* [Check Strong Password](https://github.com/TheAlgorithms/Python/blob/master/other/check_strong_password.py)
* [Davisb Putnamb Logemannb Loveland](https://github.com/TheAlgorithms/Python/blob/master/other/davisb_putnamb_logemannb_loveland.py)
* [Dijkstra Bankers Algorithm](https://github.com/TheAlgorithms/Python/blob/master/other/dijkstra_bankers_algorithm.py)
* [Doomsday](https://github.com/TheAlgorithms/Python/blob/master/other/doomsday.py)
* [Fischer Yates Shuffle](https://github.com/TheAlgorithms/Python/blob/master/other/fischer_yates_shuffle.py)
* [Gauss Easter](https://github.com/TheAlgorithms/Python/blob/master/other/gauss_easter.py)
* [Graham Scan](https://github.com/TheAlgorithms/Python/blob/master/other/graham_scan.py)
* [Greedy](https://github.com/TheAlgorithms/Python/blob/master/other/greedy.py)
* [Least Recently Used](https://github.com/TheAlgorithms/Python/blob/master/other/least_recently_used.py)
* [Lfu Cache](https://github.com/TheAlgorithms/Python/blob/master/other/lfu_cache.py)
* [Linear Congruential Generator](https://github.com/TheAlgorithms/Python/blob/master/other/linear_congruential_generator.py)
* [Lru Cache](https://github.com/TheAlgorithms/Python/blob/master/other/lru_cache.py)
* [Magicdiamondpattern](https://github.com/TheAlgorithms/Python/blob/master/other/magicdiamondpattern.py)
* [Nested Brackets](https://github.com/TheAlgorithms/Python/blob/master/other/nested_brackets.py)
* [Password Generator](https://github.com/TheAlgorithms/Python/blob/master/other/password_generator.py)
* [Scoring Algorithm](https://github.com/TheAlgorithms/Python/blob/master/other/scoring_algorithm.py)
* [Sdes](https://github.com/TheAlgorithms/Python/blob/master/other/sdes.py)
* [Tower Of Hanoi](https://github.com/TheAlgorithms/Python/blob/master/other/tower_of_hanoi.py)
## Physics
* [N Body Simulation](https://github.com/TheAlgorithms/Python/blob/master/physics/n_body_simulation.py)
* [Newtons Second Law Of Motion](https://github.com/TheAlgorithms/Python/blob/master/physics/newtons_second_law_of_motion.py)
## Project Euler
* Problem 001
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol4.py)
* [Sol5](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol5.py)
* [Sol6](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol6.py)
* [Sol7](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_001/sol7.py)
* Problem 002
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol4.py)
* [Sol5](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_002/sol5.py)
* Problem 003
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_003/sol3.py)
* Problem 004
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_004/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_004/sol2.py)
* Problem 005
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_005/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_005/sol2.py)
* Problem 006
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_006/sol4.py)
* Problem 007
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_007/sol3.py)
* Problem 008
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_008/sol3.py)
* Problem 009
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_009/sol3.py)
* Problem 010
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_010/sol3.py)
* Problem 011
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_011/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_011/sol2.py)
* Problem 012
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_012/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_012/sol2.py)
* Problem 013
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_013/sol1.py)
* Problem 014
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_014/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_014/sol2.py)
* Problem 015
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_015/sol1.py)
* Problem 016
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_016/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_016/sol2.py)
* Problem 017
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_017/sol1.py)
* Problem 018
* [Solution](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_018/solution.py)
* Problem 019
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_019/sol1.py)
* Problem 020
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol3.py)
* [Sol4](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_020/sol4.py)
* Problem 021
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_021/sol1.py)
* Problem 022
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_022/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_022/sol2.py)
* Problem 023
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_023/sol1.py)
* Problem 024
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_024/sol1.py)
* Problem 025
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol2.py)
* [Sol3](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_025/sol3.py)
* Problem 026
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_026/sol1.py)
* Problem 027
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_027/sol1.py)
* Problem 028
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_028/sol1.py)
* Problem 029
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_029/sol1.py)
* Problem 030
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_030/sol1.py)
* Problem 031
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_031/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_031/sol2.py)
* Problem 032
* [Sol32](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_032/sol32.py)
* Problem 033
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_033/sol1.py)
* Problem 034
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_034/sol1.py)
* Problem 035
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_035/sol1.py)
* Problem 036
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_036/sol1.py)
* Problem 037
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_037/sol1.py)
* Problem 038
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_038/sol1.py)
* Problem 039
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_039/sol1.py)
* Problem 040
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_040/sol1.py)
* Problem 041
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_041/sol1.py)
* Problem 042
* [Solution42](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_042/solution42.py)
* Problem 043
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_043/sol1.py)
* Problem 044
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_044/sol1.py)
* Problem 045
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_045/sol1.py)
* Problem 046
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_046/sol1.py)
* Problem 047
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_047/sol1.py)
* Problem 048
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_048/sol1.py)
* Problem 049
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_049/sol1.py)
* Problem 050
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_050/sol1.py)
* Problem 051
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_051/sol1.py)
* Problem 052
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_052/sol1.py)
* Problem 053
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_053/sol1.py)
* Problem 054
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_054/sol1.py)
* [Test Poker Hand](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_054/test_poker_hand.py)
* Problem 055
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_055/sol1.py)
* Problem 056
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_056/sol1.py)
* Problem 057
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_057/sol1.py)
* Problem 058
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_058/sol1.py)
* Problem 059
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_059/sol1.py)
* Problem 062
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_062/sol1.py)
* Problem 063
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_063/sol1.py)
* Problem 064
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_064/sol1.py)
* Problem 065
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_065/sol1.py)
* Problem 067
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_067/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_067/sol2.py)
* Problem 069
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_069/sol1.py)
* Problem 070
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_070/sol1.py)
* Problem 071
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_071/sol1.py)
* Problem 072
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_072/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_072/sol2.py)
* Problem 074
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_074/sol1.py)
* [Sol2](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_074/sol2.py)
* Problem 075
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_075/sol1.py)
* Problem 076
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_076/sol1.py)
* Problem 077
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_077/sol1.py)
* Problem 078
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_078/sol1.py)
* Problem 080
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_080/sol1.py)
* Problem 081
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_081/sol1.py)
* Problem 085
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_085/sol1.py)
* Problem 086
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_086/sol1.py)
* Problem 087
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_087/sol1.py)
* Problem 089
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_089/sol1.py)
* Problem 091
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_091/sol1.py)
* Problem 092
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_092/sol1.py)
* Problem 097
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_097/sol1.py)
* Problem 099
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_099/sol1.py)
* Problem 101
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_101/sol1.py)
* Problem 102
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_102/sol1.py)
* Problem 107
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_107/sol1.py)
* Problem 109
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_109/sol1.py)
* Problem 112
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_112/sol1.py)
* Problem 113
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_113/sol1.py)
* Problem 119
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_119/sol1.py)
* Problem 120
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_120/sol1.py)
* Problem 121
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_121/sol1.py)
* Problem 123
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_123/sol1.py)
* Problem 125
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_125/sol1.py)
* Problem 129
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_129/sol1.py)
* Problem 135
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_135/sol1.py)
* Problem 144
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_144/sol1.py)
* Problem 145
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_145/sol1.py)
* Problem 173
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_173/sol1.py)
* Problem 174
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_174/sol1.py)
* Problem 180
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_180/sol1.py)
* Problem 188
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_188/sol1.py)
* Problem 191
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_191/sol1.py)
* Problem 203
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_203/sol1.py)
* Problem 205
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_205/sol1.py)
* Problem 206
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_206/sol1.py)
* Problem 207
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_207/sol1.py)
* Problem 234
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_234/sol1.py)
* Problem 301
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_301/sol1.py)
* Problem 493
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_493/sol1.py)
* Problem 551
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_551/sol1.py)
* Problem 686
* [Sol1](https://github.com/TheAlgorithms/Python/blob/master/project_euler/problem_686/sol1.py)
## Quantum
* [Deutsch Jozsa](https://github.com/TheAlgorithms/Python/blob/master/quantum/deutsch_jozsa.py)
* [Half Adder](https://github.com/TheAlgorithms/Python/blob/master/quantum/half_adder.py)
* [Not Gate](https://github.com/TheAlgorithms/Python/blob/master/quantum/not_gate.py)
* [Quantum Entanglement](https://github.com/TheAlgorithms/Python/blob/master/quantum/quantum_entanglement.py)
* [Ripple Adder Classic](https://github.com/TheAlgorithms/Python/blob/master/quantum/ripple_adder_classic.py)
* [Single Qubit Measure](https://github.com/TheAlgorithms/Python/blob/master/quantum/single_qubit_measure.py)
## Scheduling
* [First Come First Served](https://github.com/TheAlgorithms/Python/blob/master/scheduling/first_come_first_served.py)
* [Round Robin](https://github.com/TheAlgorithms/Python/blob/master/scheduling/round_robin.py)
* [Shortest Job First](https://github.com/TheAlgorithms/Python/blob/master/scheduling/shortest_job_first.py)
## Searches
* [Binary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/binary_search.py)
* [Binary Tree Traversal](https://github.com/TheAlgorithms/Python/blob/master/searches/binary_tree_traversal.py)
* [Double Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/double_linear_search.py)
* [Double Linear Search Recursion](https://github.com/TheAlgorithms/Python/blob/master/searches/double_linear_search_recursion.py)
* [Fibonacci Search](https://github.com/TheAlgorithms/Python/blob/master/searches/fibonacci_search.py)
* [Hill Climbing](https://github.com/TheAlgorithms/Python/blob/master/searches/hill_climbing.py)
* [Interpolation Search](https://github.com/TheAlgorithms/Python/blob/master/searches/interpolation_search.py)
* [Jump Search](https://github.com/TheAlgorithms/Python/blob/master/searches/jump_search.py)
* [Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/linear_search.py)
* [Quick Select](https://github.com/TheAlgorithms/Python/blob/master/searches/quick_select.py)
* [Sentinel Linear Search](https://github.com/TheAlgorithms/Python/blob/master/searches/sentinel_linear_search.py)
* [Simple Binary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/simple_binary_search.py)
* [Simulated Annealing](https://github.com/TheAlgorithms/Python/blob/master/searches/simulated_annealing.py)
* [Tabu Search](https://github.com/TheAlgorithms/Python/blob/master/searches/tabu_search.py)
* [Ternary Search](https://github.com/TheAlgorithms/Python/blob/master/searches/ternary_search.py)
## Sorts
* [Bead Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bead_sort.py)
* [Bitonic Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bitonic_sort.py)
* [Bogo Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bogo_sort.py)
* [Bubble Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bubble_sort.py)
* [Bucket Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/bucket_sort.py)
* [Cocktail Shaker Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/cocktail_shaker_sort.py)
* [Comb Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/comb_sort.py)
* [Counting Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/counting_sort.py)
* [Cycle Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/cycle_sort.py)
* [Double Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/double_sort.py)
* [Dutch National Flag Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/dutch_national_flag_sort.py)
* [Exchange Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/exchange_sort.py)
* [External Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/external_sort.py)
* [Gnome Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/gnome_sort.py)
* [Heap Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/heap_sort.py)
* [Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/insertion_sort.py)
* [Intro Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/intro_sort.py)
* [Iterative Merge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/iterative_merge_sort.py)
* [Merge Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/merge_insertion_sort.py)
* [Merge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/merge_sort.py)
* [Msd Radix Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/msd_radix_sort.py)
* [Natural Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/natural_sort.py)
* [Odd Even Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_sort.py)
* [Odd Even Transposition Parallel](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_transposition_parallel.py)
* [Odd Even Transposition Single Threaded](https://github.com/TheAlgorithms/Python/blob/master/sorts/odd_even_transposition_single_threaded.py)
* [Pancake Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pancake_sort.py)
* [Patience Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/patience_sort.py)
* [Pigeon Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pigeon_sort.py)
* [Pigeonhole Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/pigeonhole_sort.py)
* [Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/quick_sort.py)
* [Quick Sort 3 Partition](https://github.com/TheAlgorithms/Python/blob/master/sorts/quick_sort_3_partition.py)
* [Radix Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/radix_sort.py)
* [Random Normal Distribution Quicksort](https://github.com/TheAlgorithms/Python/blob/master/sorts/random_normal_distribution_quicksort.py)
* [Random Pivot Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/random_pivot_quick_sort.py)
* [Recursive Bubble Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_bubble_sort.py)
* [Recursive Insertion Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_insertion_sort.py)
* [Recursive Mergesort Array](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_mergesort_array.py)
* [Recursive Quick Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/recursive_quick_sort.py)
* [Selection Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/selection_sort.py)
* [Shell Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/shell_sort.py)
* [Slowsort](https://github.com/TheAlgorithms/Python/blob/master/sorts/slowsort.py)
* [Stooge Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/stooge_sort.py)
* [Strand Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/strand_sort.py)
* [Tim Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/tim_sort.py)
* [Topological Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/topological_sort.py)
* [Tree Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/tree_sort.py)
* [Unknown Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/unknown_sort.py)
* [Wiggle Sort](https://github.com/TheAlgorithms/Python/blob/master/sorts/wiggle_sort.py)
## Strings
* [Aho Corasick](https://github.com/TheAlgorithms/Python/blob/master/strings/aho_corasick.py)
* [Alternative String Arrange](https://github.com/TheAlgorithms/Python/blob/master/strings/alternative_string_arrange.py)
* [Anagrams](https://github.com/TheAlgorithms/Python/blob/master/strings/anagrams.py)
* [Autocomplete Using Trie](https://github.com/TheAlgorithms/Python/blob/master/strings/autocomplete_using_trie.py)
* [Boyer Moore Search](https://github.com/TheAlgorithms/Python/blob/master/strings/boyer_moore_search.py)
* [Can String Be Rearranged As Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/can_string_be_rearranged_as_palindrome.py)
* [Capitalize](https://github.com/TheAlgorithms/Python/blob/master/strings/capitalize.py)
* [Check Anagrams](https://github.com/TheAlgorithms/Python/blob/master/strings/check_anagrams.py)
* [Check Pangram](https://github.com/TheAlgorithms/Python/blob/master/strings/check_pangram.py)
* [Credit Card Validator](https://github.com/TheAlgorithms/Python/blob/master/strings/credit_card_validator.py)
* [Detecting English Programmatically](https://github.com/TheAlgorithms/Python/blob/master/strings/detecting_english_programmatically.py)
* [Frequency Finder](https://github.com/TheAlgorithms/Python/blob/master/strings/frequency_finder.py)
* [Indian Phone Validator](https://github.com/TheAlgorithms/Python/blob/master/strings/indian_phone_validator.py)
* [Is Contains Unique Chars](https://github.com/TheAlgorithms/Python/blob/master/strings/is_contains_unique_chars.py)
* [Is Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/is_palindrome.py)
* [Jaro Winkler](https://github.com/TheAlgorithms/Python/blob/master/strings/jaro_winkler.py)
* [Join](https://github.com/TheAlgorithms/Python/blob/master/strings/join.py)
* [Knuth Morris Pratt](https://github.com/TheAlgorithms/Python/blob/master/strings/knuth_morris_pratt.py)
* [Levenshtein Distance](https://github.com/TheAlgorithms/Python/blob/master/strings/levenshtein_distance.py)
* [Lower](https://github.com/TheAlgorithms/Python/blob/master/strings/lower.py)
* [Manacher](https://github.com/TheAlgorithms/Python/blob/master/strings/manacher.py)
* [Min Cost String Conversion](https://github.com/TheAlgorithms/Python/blob/master/strings/min_cost_string_conversion.py)
* [Naive String Search](https://github.com/TheAlgorithms/Python/blob/master/strings/naive_string_search.py)
* [Palindrome](https://github.com/TheAlgorithms/Python/blob/master/strings/palindrome.py)
* [Prefix Function](https://github.com/TheAlgorithms/Python/blob/master/strings/prefix_function.py)
* [Rabin Karp](https://github.com/TheAlgorithms/Python/blob/master/strings/rabin_karp.py)
* [Remove Duplicate](https://github.com/TheAlgorithms/Python/blob/master/strings/remove_duplicate.py)
* [Reverse Letters](https://github.com/TheAlgorithms/Python/blob/master/strings/reverse_letters.py)
* [Reverse Long Words](https://github.com/TheAlgorithms/Python/blob/master/strings/reverse_long_words.py)
* [Reverse Words](https://github.com/TheAlgorithms/Python/blob/master/strings/reverse_words.py)
* [Split](https://github.com/TheAlgorithms/Python/blob/master/strings/split.py)
* [Upper](https://github.com/TheAlgorithms/Python/blob/master/strings/upper.py)
* [Wildcard Pattern Matching](https://github.com/TheAlgorithms/Python/blob/master/strings/wildcard_pattern_matching.py)
* [Word Occurrence](https://github.com/TheAlgorithms/Python/blob/master/strings/word_occurrence.py)
* [Word Patterns](https://github.com/TheAlgorithms/Python/blob/master/strings/word_patterns.py)
* [Z Function](https://github.com/TheAlgorithms/Python/blob/master/strings/z_function.py)
## Web Programming
* [Co2 Emission](https://github.com/TheAlgorithms/Python/blob/master/web_programming/co2_emission.py)
* [Covid Stats Via Xpath](https://github.com/TheAlgorithms/Python/blob/master/web_programming/covid_stats_via_xpath.py)
* [Crawl Google Results](https://github.com/TheAlgorithms/Python/blob/master/web_programming/crawl_google_results.py)
* [Crawl Google Scholar Citation](https://github.com/TheAlgorithms/Python/blob/master/web_programming/crawl_google_scholar_citation.py)
* [Currency Converter](https://github.com/TheAlgorithms/Python/blob/master/web_programming/currency_converter.py)
* [Current Stock Price](https://github.com/TheAlgorithms/Python/blob/master/web_programming/current_stock_price.py)
* [Current Weather](https://github.com/TheAlgorithms/Python/blob/master/web_programming/current_weather.py)
* [Daily Horoscope](https://github.com/TheAlgorithms/Python/blob/master/web_programming/daily_horoscope.py)
* [Download Images From Google Query](https://github.com/TheAlgorithms/Python/blob/master/web_programming/download_images_from_google_query.py)
* [Emails From Url](https://github.com/TheAlgorithms/Python/blob/master/web_programming/emails_from_url.py)
* [Fetch Bbc News](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_bbc_news.py)
* [Fetch Github Info](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_github_info.py)
* [Fetch Jobs](https://github.com/TheAlgorithms/Python/blob/master/web_programming/fetch_jobs.py)
* [Get Imdb Top 250 Movies Csv](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_imdb_top_250_movies_csv.py)
* [Get Imdbtop](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_imdbtop.py)
* [Get Top Hn Posts](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_top_hn_posts.py)
* [Get User Tweets](https://github.com/TheAlgorithms/Python/blob/master/web_programming/get_user_tweets.py)
* [Giphy](https://github.com/TheAlgorithms/Python/blob/master/web_programming/giphy.py)
* [Instagram Crawler](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_crawler.py)
* [Instagram Pic](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_pic.py)
* [Instagram Video](https://github.com/TheAlgorithms/Python/blob/master/web_programming/instagram_video.py)
* [Nasa Data](https://github.com/TheAlgorithms/Python/blob/master/web_programming/nasa_data.py)
* [Random Anime Character](https://github.com/TheAlgorithms/Python/blob/master/web_programming/random_anime_character.py)
* [Recaptcha Verification](https://github.com/TheAlgorithms/Python/blob/master/web_programming/recaptcha_verification.py)
* [Reddit](https://github.com/TheAlgorithms/Python/blob/master/web_programming/reddit.py)
* [Search Books By Isbn](https://github.com/TheAlgorithms/Python/blob/master/web_programming/search_books_by_isbn.py)
* [Slack Message](https://github.com/TheAlgorithms/Python/blob/master/web_programming/slack_message.py)
* [Test Fetch Github Info](https://github.com/TheAlgorithms/Python/blob/master/web_programming/test_fetch_github_info.py)
* [World Covid19 Stats](https://github.com/TheAlgorithms/Python/blob/master/web_programming/world_covid19_stats.py)
| 1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Functions for 2D matrix operations
"""
from __future__ import annotations
def add(*matrix_s: list[list]) -> list[list]:
"""
>>> add([[1,2],[3,4]],[[2,3],[4,5]])
[[3, 5], [7, 9]]
>>> add([[1.2,2.4],[3,4]],[[2,3],[4,5]])
[[3.2, 5.4], [7, 9]]
>>> add([[1, 2], [4, 5]], [[3, 7], [3, 4]], [[3, 5], [5, 7]])
[[7, 14], [12, 16]]
"""
if all(_check_not_integer(m) for m in matrix_s):
for i in matrix_s[1:]:
_verify_matrix_sizes(matrix_s[0], i)
return [[sum(t) for t in zip(*m)] for m in zip(*matrix_s)]
def subtract(matrix_a: list[list], matrix_b: list[list]) -> list[list]:
"""
>>> subtract([[1,2],[3,4]],[[2,3],[4,5]])
[[-1, -1], [-1, -1]]
>>> subtract([[1,2.5],[3,4]],[[2,3],[4,5.5]])
[[-1, -0.5], [-1, -1.5]]
"""
if (
_check_not_integer(matrix_a)
and _check_not_integer(matrix_b)
and _verify_matrix_sizes(matrix_a, matrix_b)
):
return [[i - j for i, j in zip(*m)] for m in zip(matrix_a, matrix_b)]
def scalar_multiply(matrix: list[list], n: int) -> list[list]:
"""
>>> scalar_multiply([[1,2],[3,4]],5)
[[5, 10], [15, 20]]
>>> scalar_multiply([[1.4,2.3],[3,4]],5)
[[7.0, 11.5], [15, 20]]
"""
return [[x * n for x in row] for row in matrix]
def multiply(matrix_a: list[list], matrix_b: list[list]) -> list[list]:
"""
>>> multiply([[1,2],[3,4]],[[5,5],[7,5]])
[[19, 15], [43, 35]]
>>> multiply([[1,2.5],[3,4.5]],[[5,5],[7,5]])
[[22.5, 17.5], [46.5, 37.5]]
>>> multiply([[1, 2, 3]], [[2], [3], [4]])
[[20]]
"""
if _check_not_integer(matrix_a) and _check_not_integer(matrix_b):
rows, cols = _verify_matrix_sizes(matrix_a, matrix_b)
if cols[0] != rows[1]:
raise ValueError(
f"Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) "
f"and ({rows[1]},{cols[1]})"
)
return [
[sum(m * n for m, n in zip(i, j)) for j in zip(*matrix_b)] for i in matrix_a
]
def identity(n: int) -> list[list]:
"""
:param n: dimension for nxn matrix
:type n: int
:return: Identity matrix of shape [n, n]
>>> identity(3)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
"""
n = int(n)
return [[int(row == column) for column in range(n)] for row in range(n)]
def transpose(matrix: list[list], return_map: bool = True) -> list[list]:
"""
>>> transpose([[1,2],[3,4]]) # doctest: +ELLIPSIS
<map object at ...
>>> transpose([[1,2],[3,4]], return_map=False)
[[1, 3], [2, 4]]
"""
if _check_not_integer(matrix):
if return_map:
return map(list, zip(*matrix))
else:
return list(map(list, zip(*matrix)))
def minor(matrix: list[list], row: int, column: int) -> list[list]:
"""
>>> minor([[1, 2], [3, 4]], 1, 1)
[[1]]
"""
minor = matrix[:row] + matrix[row + 1 :]
return [row[:column] + row[column + 1 :] for row in minor]
def determinant(matrix: list[list]) -> int:
"""
>>> determinant([[1, 2], [3, 4]])
-2
>>> determinant([[1.5, 2.5], [3, 4]])
-1.5
"""
if len(matrix) == 1:
return matrix[0][0]
return sum(
x * determinant(minor(matrix, 0, i)) * (-1) ** i
for i, x in enumerate(matrix[0])
)
def inverse(matrix: list[list]) -> list[list]:
"""
>>> inverse([[1, 2], [3, 4]])
[[-2.0, 1.0], [1.5, -0.5]]
>>> inverse([[1, 1], [1, 1]])
"""
# https://stackoverflow.com/questions/20047519/python-doctests-test-for-none
det = determinant(matrix)
if det == 0:
return None
matrix_minor = [
[determinant(minor(matrix, i, j)) for j in range(len(matrix))]
for i in range(len(matrix))
]
cofactors = [
[x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row])]
for row in range(len(matrix))
]
adjugate = transpose(cofactors)
return scalar_multiply(adjugate, 1 / det)
def _check_not_integer(matrix: list[list]) -> bool:
if not isinstance(matrix, int) and not isinstance(matrix[0], int):
return True
raise TypeError("Expected a matrix, got int/list instead")
def _shape(matrix: list[list]) -> list:
return len(matrix), len(matrix[0])
def _verify_matrix_sizes(matrix_a: list[list], matrix_b: list[list]) -> tuple[list]:
shape = _shape(matrix_a) + _shape(matrix_b)
if shape[0] != shape[3] or shape[1] != shape[2]:
raise ValueError(
f"operands could not be broadcast together with shape "
f"({shape[0], shape[1]}), ({shape[2], shape[3]})"
)
return (shape[0], shape[2]), (shape[1], shape[3])
def main():
matrix_a = [[12, 10], [3, 9]]
matrix_b = [[3, 4], [7, 4]]
matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]
matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]]
print(f"Add Operation, {add(matrix_a, matrix_b) = } \n")
print(
f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n",
)
print(f"Identity: {identity(5)}\n")
print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n")
print(f"Determinant of {matrix_b} = {determinant(matrix_b)} \n")
print(f"Inverse of {matrix_d} = {inverse(matrix_d)}\n")
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| """
Functions for 2D matrix operations
"""
from __future__ import annotations
def add(*matrix_s: list[list]) -> list[list]:
"""
>>> add([[1,2],[3,4]],[[2,3],[4,5]])
[[3, 5], [7, 9]]
>>> add([[1.2,2.4],[3,4]],[[2,3],[4,5]])
[[3.2, 5.4], [7, 9]]
>>> add([[1, 2], [4, 5]], [[3, 7], [3, 4]], [[3, 5], [5, 7]])
[[7, 14], [12, 16]]
>>> add([3], [4, 5])
Traceback (most recent call last):
...
TypeError: Expected a matrix, got int/list instead
"""
if all(_check_not_integer(m) for m in matrix_s):
for i in matrix_s[1:]:
_verify_matrix_sizes(matrix_s[0], i)
return [[sum(t) for t in zip(*m)] for m in zip(*matrix_s)]
raise TypeError("Expected a matrix, got int/list instead")
def subtract(matrix_a: list[list], matrix_b: list[list]) -> list[list]:
"""
>>> subtract([[1,2],[3,4]],[[2,3],[4,5]])
[[-1, -1], [-1, -1]]
>>> subtract([[1,2.5],[3,4]],[[2,3],[4,5.5]])
[[-1, -0.5], [-1, -1.5]]
>>> subtract([3], [4, 5])
Traceback (most recent call last):
...
TypeError: Expected a matrix, got int/list instead
"""
if (
_check_not_integer(matrix_a)
and _check_not_integer(matrix_b)
and _verify_matrix_sizes(matrix_a, matrix_b)
):
return [[i - j for i, j in zip(*m)] for m in zip(matrix_a, matrix_b)]
raise TypeError("Expected a matrix, got int/list instead")
def scalar_multiply(matrix: list[list], n: int | float) -> list[list]:
"""
>>> scalar_multiply([[1,2],[3,4]],5)
[[5, 10], [15, 20]]
>>> scalar_multiply([[1.4,2.3],[3,4]],5)
[[7.0, 11.5], [15, 20]]
"""
return [[x * n for x in row] for row in matrix]
def multiply(matrix_a: list[list], matrix_b: list[list]) -> list[list]:
"""
>>> multiply([[1,2],[3,4]],[[5,5],[7,5]])
[[19, 15], [43, 35]]
>>> multiply([[1,2.5],[3,4.5]],[[5,5],[7,5]])
[[22.5, 17.5], [46.5, 37.5]]
>>> multiply([[1, 2, 3]], [[2], [3], [4]])
[[20]]
"""
if _check_not_integer(matrix_a) and _check_not_integer(matrix_b):
rows, cols = _verify_matrix_sizes(matrix_a, matrix_b)
if cols[0] != rows[1]:
raise ValueError(
f"Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) "
f"and ({rows[1]},{cols[1]})"
)
return [
[sum(m * n for m, n in zip(i, j)) for j in zip(*matrix_b)] for i in matrix_a
]
def identity(n: int) -> list[list]:
"""
:param n: dimension for nxn matrix
:type n: int
:return: Identity matrix of shape [n, n]
>>> identity(3)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
"""
n = int(n)
return [[int(row == column) for column in range(n)] for row in range(n)]
def transpose(matrix: list[list], return_map: bool = True) -> list[list] | map[list]:
"""
>>> transpose([[1,2],[3,4]]) # doctest: +ELLIPSIS
<map object at ...
>>> transpose([[1,2],[3,4]], return_map=False)
[[1, 3], [2, 4]]
>>> transpose([1, [2, 3]])
Traceback (most recent call last):
...
TypeError: Expected a matrix, got int/list instead
"""
if _check_not_integer(matrix):
if return_map:
return map(list, zip(*matrix))
else:
return list(map(list, zip(*matrix)))
raise TypeError("Expected a matrix, got int/list instead")
def minor(matrix: list[list], row: int, column: int) -> list[list]:
"""
>>> minor([[1, 2], [3, 4]], 1, 1)
[[1]]
"""
minor = matrix[:row] + matrix[row + 1 :]
return [row[:column] + row[column + 1 :] for row in minor]
def determinant(matrix: list[list]) -> int:
"""
>>> determinant([[1, 2], [3, 4]])
-2
>>> determinant([[1.5, 2.5], [3, 4]])
-1.5
"""
if len(matrix) == 1:
return matrix[0][0]
return sum(
x * determinant(minor(matrix, 0, i)) * (-1) ** i
for i, x in enumerate(matrix[0])
)
def inverse(matrix: list[list]) -> list[list] | None:
"""
>>> inverse([[1, 2], [3, 4]])
[[-2.0, 1.0], [1.5, -0.5]]
>>> inverse([[1, 1], [1, 1]])
"""
# https://stackoverflow.com/questions/20047519/python-doctests-test-for-none
det = determinant(matrix)
if det == 0:
return None
matrix_minor = [
[determinant(minor(matrix, i, j)) for j in range(len(matrix))]
for i in range(len(matrix))
]
cofactors = [
[x * (-1) ** (row + col) for col, x in enumerate(matrix_minor[row])]
for row in range(len(matrix))
]
adjugate = list(transpose(cofactors))
return scalar_multiply(adjugate, 1 / det)
def _check_not_integer(matrix: list[list]) -> bool:
return not isinstance(matrix, int) and not isinstance(matrix[0], int)
def _shape(matrix: list[list]) -> tuple[int, int]:
return len(matrix), len(matrix[0])
def _verify_matrix_sizes(
matrix_a: list[list], matrix_b: list[list]
) -> tuple[tuple, tuple]:
shape = _shape(matrix_a) + _shape(matrix_b)
if shape[0] != shape[3] or shape[1] != shape[2]:
raise ValueError(
f"operands could not be broadcast together with shape "
f"({shape[0], shape[1]}), ({shape[2], shape[3]})"
)
return (shape[0], shape[2]), (shape[1], shape[3])
def main():
matrix_a = [[12, 10], [3, 9]]
matrix_b = [[3, 4], [7, 4]]
matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]
matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]]
print(f"Add Operation, {add(matrix_a, matrix_b) = } \n")
print(
f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n",
)
print(f"Identity: {identity(5)}\n")
print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n")
print(f"Determinant of {matrix_b} = {determinant(matrix_b)} \n")
print(f"Inverse of {matrix_d} = {inverse(matrix_d)}\n")
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| [mypy]
ignore_missing_imports = True
install_types = True
non_interactive = True
exclude = (matrix_operation.py|other/least_recently_used.py|other/lfu_cache.py|other/lru_cache.py)
| [mypy]
ignore_missing_imports = True
install_types = True
non_interactive = True
exclude = (other/least_recently_used.py|other/lfu_cache.py|other/lru_cache.py)
| 1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/env python3
def climb_stairs(n: int) -> int:
"""
LeetCdoe No.70: Climbing Stairs
Distinct ways to climb a n step staircase where
each time you can either climb 1 or 2 steps.
Args:
n: number of steps of staircase
Returns:
Distinct ways to climb a n step staircase
Raises:
AssertionError: n not positive integer
>>> climb_stairs(3)
3
>>> climb_stairs(1)
1
>>> climb_stairs(-7) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AssertionError: n needs to be positive integer, your input -7
"""
assert (
isinstance(n, int) and n > 0
), f"n needs to be positive integer, your input {n}"
if n == 1:
return 1
dp = [0] * (n + 1)
dp[0], dp[1] = (1, 1)
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
if __name__ == "__main__":
import doctest
doctest.testmod()
| #!/usr/bin/env python3
def climb_stairs(n: int) -> int:
"""
LeetCdoe No.70: Climbing Stairs
Distinct ways to climb a n step staircase where
each time you can either climb 1 or 2 steps.
Args:
n: number of steps of staircase
Returns:
Distinct ways to climb a n step staircase
Raises:
AssertionError: n not positive integer
>>> climb_stairs(3)
3
>>> climb_stairs(1)
1
>>> climb_stairs(-7) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AssertionError: n needs to be positive integer, your input -7
"""
assert (
isinstance(n, int) and n > 0
), f"n needs to be positive integer, your input {n}"
if n == 1:
return 1
dp = [0] * (n + 1)
dp[0], dp[1] = (1, 1)
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
In this problem, we want to determine all possible permutations
of the given sequence. We use backtracking to solve this problem.
Time complexity: O(n! * n),
where n denotes the length of the given sequence.
"""
from __future__ import annotations
def generate_all_permutations(sequence: list[int | str]) -> None:
create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))])
def create_state_space_tree(
sequence: list[int | str],
current_sequence: list[int | str],
index: int,
index_used: list[int],
) -> None:
"""
Creates a state space tree to iterate through each branch using DFS.
We know that each state has exactly len(sequence) - index children.
It terminates when it reaches the end of the given sequence.
"""
if index == len(sequence):
print(current_sequence)
return
for i in range(len(sequence)):
if not index_used[i]:
current_sequence.append(sequence[i])
index_used[i] = True
create_state_space_tree(sequence, current_sequence, index + 1, index_used)
current_sequence.pop()
index_used[i] = False
"""
remove the comment to take an input from the user
print("Enter the elements")
sequence = list(map(int, input().split()))
"""
sequence: list[int | str] = [3, 1, 2, 4]
generate_all_permutations(sequence)
sequence_2: list[int | str] = ["A", "B", "C"]
generate_all_permutations(sequence_2)
| """
In this problem, we want to determine all possible permutations
of the given sequence. We use backtracking to solve this problem.
Time complexity: O(n! * n),
where n denotes the length of the given sequence.
"""
from __future__ import annotations
def generate_all_permutations(sequence: list[int | str]) -> None:
create_state_space_tree(sequence, [], 0, [0 for i in range(len(sequence))])
def create_state_space_tree(
sequence: list[int | str],
current_sequence: list[int | str],
index: int,
index_used: list[int],
) -> None:
"""
Creates a state space tree to iterate through each branch using DFS.
We know that each state has exactly len(sequence) - index children.
It terminates when it reaches the end of the given sequence.
"""
if index == len(sequence):
print(current_sequence)
return
for i in range(len(sequence)):
if not index_used[i]:
current_sequence.append(sequence[i])
index_used[i] = True
create_state_space_tree(sequence, current_sequence, index + 1, index_used)
current_sequence.pop()
index_used[i] = False
"""
remove the comment to take an input from the user
print("Enter the elements")
sequence = list(map(int, input().split()))
"""
sequence: list[int | str] = [3, 1, 2, 4]
generate_all_permutations(sequence)
sequence_2: list[int | str] = ["A", "B", "C"]
generate_all_permutations(sequence_2)
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Given a array of length n, max_subarray_sum() finds
the maximum of sum of contiguous sub-array using divide and conquer method.
Time complexity : O(n log n)
Ref : INTRODUCTION TO ALGORITHMS THIRD EDITION
(section : 4, sub-section : 4.1, page : 70)
"""
def max_sum_from_start(array):
"""This function finds the maximum contiguous sum of array from 0 index
Parameters :
array (list[int]) : given array
Returns :
max_sum (int) : maximum contiguous sum of array from 0 index
"""
array_sum = 0
max_sum = float("-inf")
for num in array:
array_sum += num
if array_sum > max_sum:
max_sum = array_sum
return max_sum
def max_cross_array_sum(array, left, mid, right):
"""This function finds the maximum contiguous sum of left and right arrays
Parameters :
array, left, mid, right (list[int], int, int, int)
Returns :
(int) : maximum of sum of contiguous sum of left and right arrays
"""
max_sum_of_left = max_sum_from_start(array[left : mid + 1][::-1])
max_sum_of_right = max_sum_from_start(array[mid + 1 : right + 1])
return max_sum_of_left + max_sum_of_right
def max_subarray_sum(array, left, right):
"""Maximum contiguous sub-array sum, using divide and conquer method
Parameters :
array, left, right (list[int], int, int) :
given array, current left index and current right index
Returns :
int : maximum of sum of contiguous sub-array
"""
# base case: array has only one element
if left == right:
return array[right]
# Recursion
mid = (left + right) // 2
left_half_sum = max_subarray_sum(array, left, mid)
right_half_sum = max_subarray_sum(array, mid + 1, right)
cross_sum = max_cross_array_sum(array, left, mid, right)
return max(left_half_sum, right_half_sum, cross_sum)
array = [-2, -5, 6, -2, -3, 1, 5, -6]
array_length = len(array)
print(
"Maximum sum of contiguous subarray:", max_subarray_sum(array, 0, array_length - 1)
)
| """
Given a array of length n, max_subarray_sum() finds
the maximum of sum of contiguous sub-array using divide and conquer method.
Time complexity : O(n log n)
Ref : INTRODUCTION TO ALGORITHMS THIRD EDITION
(section : 4, sub-section : 4.1, page : 70)
"""
def max_sum_from_start(array):
"""This function finds the maximum contiguous sum of array from 0 index
Parameters :
array (list[int]) : given array
Returns :
max_sum (int) : maximum contiguous sum of array from 0 index
"""
array_sum = 0
max_sum = float("-inf")
for num in array:
array_sum += num
if array_sum > max_sum:
max_sum = array_sum
return max_sum
def max_cross_array_sum(array, left, mid, right):
"""This function finds the maximum contiguous sum of left and right arrays
Parameters :
array, left, mid, right (list[int], int, int, int)
Returns :
(int) : maximum of sum of contiguous sum of left and right arrays
"""
max_sum_of_left = max_sum_from_start(array[left : mid + 1][::-1])
max_sum_of_right = max_sum_from_start(array[mid + 1 : right + 1])
return max_sum_of_left + max_sum_of_right
def max_subarray_sum(array, left, right):
"""Maximum contiguous sub-array sum, using divide and conquer method
Parameters :
array, left, right (list[int], int, int) :
given array, current left index and current right index
Returns :
int : maximum of sum of contiguous sub-array
"""
# base case: array has only one element
if left == right:
return array[right]
# Recursion
mid = (left + right) // 2
left_half_sum = max_subarray_sum(array, left, mid)
right_half_sum = max_subarray_sum(array, mid + 1, right)
cross_sum = max_cross_array_sum(array, left, mid, right)
return max(left_half_sum, right_half_sum, cross_sum)
array = [-2, -5, 6, -2, -3, 1, 5, -6]
array_length = len(array)
print(
"Maximum sum of contiguous subarray:", max_subarray_sum(array, 0, array_length - 1)
)
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/env python3
from __future__ import annotations
import json
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
headers = {"UserAgent": UserAgent().random}
def extract_user_profile(script) -> dict:
"""
May raise json.decoder.JSONDecodeError
"""
data = script.contents[0]
info = json.loads(data[data.find('{"config"') : -1])
return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]
class InstagramUser:
"""
Class Instagram crawl instagram user information
Usage: (doctest failing on GitHub Actions)
# >>> instagram_user = InstagramUser("github")
# >>> instagram_user.is_verified
True
# >>> instagram_user.biography
'Built for developers.'
"""
def __init__(self, username):
self.url = f"https://www.instagram.com/{username}/"
self.user_data = self.get_json()
def get_json(self) -> dict:
"""
Return a dict of user information
"""
html = requests.get(self.url, headers=headers).text
scripts = BeautifulSoup(html, "html.parser").find_all("script")
try:
return extract_user_profile(scripts[4])
except (json.decoder.JSONDecodeError, KeyError):
return extract_user_profile(scripts[3])
def __repr__(self) -> str:
return f"{self.__class__.__name__}('{self.username}')"
def __str__(self) -> str:
return f"{self.fullname} ({self.username}) is {self.biography}"
@property
def username(self) -> str:
return self.user_data["username"]
@property
def fullname(self) -> str:
return self.user_data["full_name"]
@property
def biography(self) -> str:
return self.user_data["biography"]
@property
def email(self) -> str:
return self.user_data["business_email"]
@property
def website(self) -> str:
return self.user_data["external_url"]
@property
def number_of_followers(self) -> int:
return self.user_data["edge_followed_by"]["count"]
@property
def number_of_followings(self) -> int:
return self.user_data["edge_follow"]["count"]
@property
def number_of_posts(self) -> int:
return self.user_data["edge_owner_to_timeline_media"]["count"]
@property
def profile_picture_url(self) -> str:
return self.user_data["profile_pic_url_hd"]
@property
def is_verified(self) -> bool:
return self.user_data["is_verified"]
@property
def is_private(self) -> bool:
return self.user_data["is_private"]
def test_instagram_user(username: str = "github") -> None:
"""
A self running doctest
>>> test_instagram_user()
"""
import os
if os.environ.get("CI"):
return None # test failing on GitHub Actions
instagram_user = InstagramUser(username)
assert instagram_user.user_data
assert isinstance(instagram_user.user_data, dict)
assert instagram_user.username == username
if username != "github":
return
assert instagram_user.fullname == "GitHub"
assert instagram_user.biography == "Built for developers."
assert instagram_user.number_of_posts > 150
assert instagram_user.number_of_followers > 120000
assert instagram_user.number_of_followings > 15
assert instagram_user.email == "[email protected]"
assert instagram_user.website == "https://github.com/readme"
assert instagram_user.profile_picture_url.startswith("https://instagram.")
assert instagram_user.is_verified is True
assert instagram_user.is_private is False
if __name__ == "__main__":
import doctest
doctest.testmod()
instagram_user = InstagramUser("github")
print(instagram_user)
print(f"{instagram_user.number_of_posts = }")
print(f"{instagram_user.number_of_followers = }")
print(f"{instagram_user.number_of_followings = }")
print(f"{instagram_user.email = }")
print(f"{instagram_user.website = }")
print(f"{instagram_user.profile_picture_url = }")
print(f"{instagram_user.is_verified = }")
print(f"{instagram_user.is_private = }")
| #!/usr/bin/env python3
from __future__ import annotations
import json
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
headers = {"UserAgent": UserAgent().random}
def extract_user_profile(script) -> dict:
"""
May raise json.decoder.JSONDecodeError
"""
data = script.contents[0]
info = json.loads(data[data.find('{"config"') : -1])
return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]
class InstagramUser:
"""
Class Instagram crawl instagram user information
Usage: (doctest failing on GitHub Actions)
# >>> instagram_user = InstagramUser("github")
# >>> instagram_user.is_verified
True
# >>> instagram_user.biography
'Built for developers.'
"""
def __init__(self, username):
self.url = f"https://www.instagram.com/{username}/"
self.user_data = self.get_json()
def get_json(self) -> dict:
"""
Return a dict of user information
"""
html = requests.get(self.url, headers=headers).text
scripts = BeautifulSoup(html, "html.parser").find_all("script")
try:
return extract_user_profile(scripts[4])
except (json.decoder.JSONDecodeError, KeyError):
return extract_user_profile(scripts[3])
def __repr__(self) -> str:
return f"{self.__class__.__name__}('{self.username}')"
def __str__(self) -> str:
return f"{self.fullname} ({self.username}) is {self.biography}"
@property
def username(self) -> str:
return self.user_data["username"]
@property
def fullname(self) -> str:
return self.user_data["full_name"]
@property
def biography(self) -> str:
return self.user_data["biography"]
@property
def email(self) -> str:
return self.user_data["business_email"]
@property
def website(self) -> str:
return self.user_data["external_url"]
@property
def number_of_followers(self) -> int:
return self.user_data["edge_followed_by"]["count"]
@property
def number_of_followings(self) -> int:
return self.user_data["edge_follow"]["count"]
@property
def number_of_posts(self) -> int:
return self.user_data["edge_owner_to_timeline_media"]["count"]
@property
def profile_picture_url(self) -> str:
return self.user_data["profile_pic_url_hd"]
@property
def is_verified(self) -> bool:
return self.user_data["is_verified"]
@property
def is_private(self) -> bool:
return self.user_data["is_private"]
def test_instagram_user(username: str = "github") -> None:
"""
A self running doctest
>>> test_instagram_user()
"""
import os
if os.environ.get("CI"):
return None # test failing on GitHub Actions
instagram_user = InstagramUser(username)
assert instagram_user.user_data
assert isinstance(instagram_user.user_data, dict)
assert instagram_user.username == username
if username != "github":
return
assert instagram_user.fullname == "GitHub"
assert instagram_user.biography == "Built for developers."
assert instagram_user.number_of_posts > 150
assert instagram_user.number_of_followers > 120000
assert instagram_user.number_of_followings > 15
assert instagram_user.email == "[email protected]"
assert instagram_user.website == "https://github.com/readme"
assert instagram_user.profile_picture_url.startswith("https://instagram.")
assert instagram_user.is_verified is True
assert instagram_user.is_private is False
if __name__ == "__main__":
import doctest
doctest.testmod()
instagram_user = InstagramUser("github")
print(instagram_user)
print(f"{instagram_user.number_of_posts = }")
print(f"{instagram_user.number_of_followers = }")
print(f"{instagram_user.number_of_followings = }")
print(f"{instagram_user.email = }")
print(f"{instagram_user.website = }")
print(f"{instagram_user.profile_picture_url = }")
print(f"{instagram_user.is_verified = }")
print(f"{instagram_user.is_private = }")
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import cv2
import numpy as np
"""
Harris Corner Detector
https://en.wikipedia.org/wiki/Harris_Corner_Detector
"""
class Harris_Corner:
def __init__(self, k: float, window_size: int):
"""
k : is an empirically determined constant in [0.04,0.06]
window_size : neighbourhoods considered
"""
if k in (0.04, 0.06):
self.k = k
self.window_size = window_size
else:
raise ValueError("invalid k value")
def __str__(self) -> str:
return f"Harris Corner detection with k : {self.k}"
def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]:
"""
Returns the image with corners identified
img_path : path of the image
output : list of the corner positions, image
"""
img = cv2.imread(img_path, 0)
h, w = img.shape
corner_list: list[list[int]] = []
color_img = img.copy()
color_img = cv2.cvtColor(color_img, cv2.COLOR_GRAY2RGB)
dy, dx = np.gradient(img)
ixx = dx ** 2
iyy = dy ** 2
ixy = dx * dy
k = 0.04
offset = self.window_size // 2
for y in range(offset, h - offset):
for x in range(offset, w - offset):
wxx = ixx[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
wyy = iyy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
wxy = ixy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
det = (wxx * wyy) - (wxy ** 2)
trace = wxx + wyy
r = det - k * (trace ** 2)
# Can change the value
if r > 0.5:
corner_list.append([x, y, r])
color_img.itemset((y, x, 0), 0)
color_img.itemset((y, x, 1), 0)
color_img.itemset((y, x, 2), 255)
return color_img, corner_list
if __name__ == "__main__":
edge_detect = Harris_Corner(0.04, 3)
color_img, _ = edge_detect.detect("path_to_image")
cv2.imwrite("detect.png", color_img)
| import cv2
import numpy as np
"""
Harris Corner Detector
https://en.wikipedia.org/wiki/Harris_Corner_Detector
"""
class Harris_Corner:
def __init__(self, k: float, window_size: int):
"""
k : is an empirically determined constant in [0.04,0.06]
window_size : neighbourhoods considered
"""
if k in (0.04, 0.06):
self.k = k
self.window_size = window_size
else:
raise ValueError("invalid k value")
def __str__(self) -> str:
return f"Harris Corner detection with k : {self.k}"
def detect(self, img_path: str) -> tuple[cv2.Mat, list[list[int]]]:
"""
Returns the image with corners identified
img_path : path of the image
output : list of the corner positions, image
"""
img = cv2.imread(img_path, 0)
h, w = img.shape
corner_list: list[list[int]] = []
color_img = img.copy()
color_img = cv2.cvtColor(color_img, cv2.COLOR_GRAY2RGB)
dy, dx = np.gradient(img)
ixx = dx ** 2
iyy = dy ** 2
ixy = dx * dy
k = 0.04
offset = self.window_size // 2
for y in range(offset, h - offset):
for x in range(offset, w - offset):
wxx = ixx[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
wyy = iyy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
wxy = ixy[
y - offset : y + offset + 1, x - offset : x + offset + 1
].sum()
det = (wxx * wyy) - (wxy ** 2)
trace = wxx + wyy
r = det - k * (trace ** 2)
# Can change the value
if r > 0.5:
corner_list.append([x, y, r])
color_img.itemset((y, x, 0), 0)
color_img.itemset((y, x, 1), 0)
color_img.itemset((y, x, 2), 255)
return color_img, corner_list
if __name__ == "__main__":
edge_detect = Harris_Corner(0.04, 3)
color_img, _ = edge_detect.detect("path_to_image")
cv2.imwrite("detect.png", color_img)
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Calculate the nth Proth number
Source:
https://handwiki.org/wiki/Proth_number
"""
import math
def proth(number: int) -> int:
"""
:param number: nth number to calculate in the sequence
:return: the nth number in Proth number
Note: indexing starts at 1 i.e. proth(1) gives the first Proth number of 3
>>> proth(6)
25
>>> proth(0)
Traceback (most recent call last):
...
ValueError: Input value of [number=0] must be > 0
>>> proth(-1)
Traceback (most recent call last):
...
ValueError: Input value of [number=-1] must be > 0
>>> proth(6.0)
Traceback (most recent call last):
...
TypeError: Input value of [number=6.0] must be an integer
"""
if not isinstance(number, int):
raise TypeError(f"Input value of [number={number}] must be an integer")
if number < 1:
raise ValueError(f"Input value of [number={number}] must be > 0")
elif number == 1:
return 3
elif number == 2:
return 5
else:
"""
+1 for binary starting at 0 i.e. 2^0, 2^1, etc.
+1 to start the sequence at the 3rd Proth number
Hence, we have a +2 in the below statement
"""
block_index = int(math.log(number // 3, 2)) + 2
proth_list = [3, 5]
proth_index = 2
increment = 3
for block in range(1, block_index):
for move in range(increment):
proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1])
proth_index += 1
increment *= 2
return proth_list[number - 1]
if __name__ == "__main__":
import doctest
doctest.testmod()
for number in range(11):
value = 0
try:
value = proth(number)
except ValueError:
print(f"ValueError: there is no {number}th Proth number")
continue
print(f"The {number}th Proth number: {value}")
| """
Calculate the nth Proth number
Source:
https://handwiki.org/wiki/Proth_number
"""
import math
def proth(number: int) -> int:
"""
:param number: nth number to calculate in the sequence
:return: the nth number in Proth number
Note: indexing starts at 1 i.e. proth(1) gives the first Proth number of 3
>>> proth(6)
25
>>> proth(0)
Traceback (most recent call last):
...
ValueError: Input value of [number=0] must be > 0
>>> proth(-1)
Traceback (most recent call last):
...
ValueError: Input value of [number=-1] must be > 0
>>> proth(6.0)
Traceback (most recent call last):
...
TypeError: Input value of [number=6.0] must be an integer
"""
if not isinstance(number, int):
raise TypeError(f"Input value of [number={number}] must be an integer")
if number < 1:
raise ValueError(f"Input value of [number={number}] must be > 0")
elif number == 1:
return 3
elif number == 2:
return 5
else:
"""
+1 for binary starting at 0 i.e. 2^0, 2^1, etc.
+1 to start the sequence at the 3rd Proth number
Hence, we have a +2 in the below statement
"""
block_index = int(math.log(number // 3, 2)) + 2
proth_list = [3, 5]
proth_index = 2
increment = 3
for block in range(1, block_index):
for move in range(increment):
proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1])
proth_index += 1
increment *= 2
return proth_list[number - 1]
if __name__ == "__main__":
import doctest
doctest.testmod()
for number in range(11):
value = 0
try:
value = proth(number)
except ValueError:
print(f"ValueError: there is no {number}th Proth number")
continue
print(f"The {number}th Proth number: {value}")
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from __future__ import annotations
from collections import deque
class Automaton:
def __init__(self, keywords: list[str]):
self.adlist: list[dict] = list()
self.adlist.append(
{"value": "", "next_states": [], "fail_state": 0, "output": []}
)
for keyword in keywords:
self.add_keyword(keyword)
self.set_fail_transitions()
def find_next_state(self, current_state: int, char: str) -> int | None:
for state in self.adlist[current_state]["next_states"]:
if char == self.adlist[state]["value"]:
return state
return None
def add_keyword(self, keyword: str) -> None:
current_state = 0
for character in keyword:
next_state = self.find_next_state(current_state, character)
if next_state is None:
self.adlist.append(
{
"value": character,
"next_states": [],
"fail_state": 0,
"output": [],
}
)
self.adlist[current_state]["next_states"].append(len(self.adlist) - 1)
current_state = len(self.adlist) - 1
else:
current_state = next_state
self.adlist[current_state]["output"].append(keyword)
def set_fail_transitions(self) -> None:
q: deque = deque()
for node in self.adlist[0]["next_states"]:
q.append(node)
self.adlist[node]["fail_state"] = 0
while q:
r = q.popleft()
for child in self.adlist[r]["next_states"]:
q.append(child)
state = self.adlist[r]["fail_state"]
while (
self.find_next_state(state, self.adlist[child]["value"]) is None
and state != 0
):
state = self.adlist[state]["fail_state"]
self.adlist[child]["fail_state"] = self.find_next_state(
state, self.adlist[child]["value"]
)
if self.adlist[child]["fail_state"] is None:
self.adlist[child]["fail_state"] = 0
self.adlist[child]["output"] = (
self.adlist[child]["output"]
+ self.adlist[self.adlist[child]["fail_state"]]["output"]
)
def search_in(self, string: str) -> dict[str, list[int]]:
"""
>>> A = Automaton(["what", "hat", "ver", "er"])
>>> A.search_in("whatever, err ... , wherever")
{'what': [0], 'hat': [1], 'ver': [5, 25], 'er': [6, 10, 22, 26]}
"""
result: dict = (
dict()
) # returns a dict with keywords and list of its occurrences
current_state = 0
for i in range(len(string)):
while (
self.find_next_state(current_state, string[i]) is None
and current_state != 0
):
current_state = self.adlist[current_state]["fail_state"]
next_state = self.find_next_state(current_state, string[i])
if next_state is None:
current_state = 0
else:
current_state = next_state
for key in self.adlist[current_state]["output"]:
if not (key in result):
result[key] = []
result[key].append(i - len(key) + 1)
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
| from __future__ import annotations
from collections import deque
class Automaton:
def __init__(self, keywords: list[str]):
self.adlist: list[dict] = list()
self.adlist.append(
{"value": "", "next_states": [], "fail_state": 0, "output": []}
)
for keyword in keywords:
self.add_keyword(keyword)
self.set_fail_transitions()
def find_next_state(self, current_state: int, char: str) -> int | None:
for state in self.adlist[current_state]["next_states"]:
if char == self.adlist[state]["value"]:
return state
return None
def add_keyword(self, keyword: str) -> None:
current_state = 0
for character in keyword:
next_state = self.find_next_state(current_state, character)
if next_state is None:
self.adlist.append(
{
"value": character,
"next_states": [],
"fail_state": 0,
"output": [],
}
)
self.adlist[current_state]["next_states"].append(len(self.adlist) - 1)
current_state = len(self.adlist) - 1
else:
current_state = next_state
self.adlist[current_state]["output"].append(keyword)
def set_fail_transitions(self) -> None:
q: deque = deque()
for node in self.adlist[0]["next_states"]:
q.append(node)
self.adlist[node]["fail_state"] = 0
while q:
r = q.popleft()
for child in self.adlist[r]["next_states"]:
q.append(child)
state = self.adlist[r]["fail_state"]
while (
self.find_next_state(state, self.adlist[child]["value"]) is None
and state != 0
):
state = self.adlist[state]["fail_state"]
self.adlist[child]["fail_state"] = self.find_next_state(
state, self.adlist[child]["value"]
)
if self.adlist[child]["fail_state"] is None:
self.adlist[child]["fail_state"] = 0
self.adlist[child]["output"] = (
self.adlist[child]["output"]
+ self.adlist[self.adlist[child]["fail_state"]]["output"]
)
def search_in(self, string: str) -> dict[str, list[int]]:
"""
>>> A = Automaton(["what", "hat", "ver", "er"])
>>> A.search_in("whatever, err ... , wherever")
{'what': [0], 'hat': [1], 'ver': [5, 25], 'er': [6, 10, 22, 26]}
"""
result: dict = (
dict()
) # returns a dict with keywords and list of its occurrences
current_state = 0
for i in range(len(string)):
while (
self.find_next_state(current_state, string[i]) is None
and current_state != 0
):
current_state = self.adlist[current_state]["fail_state"]
next_state = self.find_next_state(current_state, string[i])
if next_state is None:
current_state = 0
else:
current_state = next_state
for key in self.adlist[current_state]["output"]:
if not (key in result):
result[key] = []
result[key].append(i - len(key) + 1)
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #
| #
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
A Trie/Prefix Tree is a kind of search tree used to provide quick lookup
of words/patterns in a set of words. A basic Trie however has O(n^2) space complexity
making it impractical in practice. It however provides O(max(search_string, length of
longest word)) lookup time making it an optimal approach when space is not an issue.
"""
class TrieNode:
def __init__(self) -> None:
self.nodes: dict[str, TrieNode] = dict() # Mapping from char to TrieNode
self.is_leaf = False
def insert_many(self, words: list[str]) -> None:
"""
Inserts a list of words into the Trie
:param words: list of string words
:return: None
"""
for word in words:
self.insert(word)
def insert(self, word: str) -> None:
"""
Inserts a word into the Trie
:param word: word to be inserted
:return: None
"""
curr = self
for char in word:
if char not in curr.nodes:
curr.nodes[char] = TrieNode()
curr = curr.nodes[char]
curr.is_leaf = True
def find(self, word: str) -> bool:
"""
Tries to find word in a Trie
:param word: word to look for
:return: Returns True if word is found, False otherwise
"""
curr = self
for char in word:
if char not in curr.nodes:
return False
curr = curr.nodes[char]
return curr.is_leaf
def delete(self, word: str) -> None:
"""
Deletes a word in a Trie
:param word: word to delete
:return: None
"""
def _delete(curr: TrieNode, word: str, index: int) -> bool:
if index == len(word):
# If word does not exist
if not curr.is_leaf:
return False
curr.is_leaf = False
return len(curr.nodes) == 0
char = word[index]
char_node = curr.nodes.get(char)
# If char not in current trie node
if not char_node:
return False
# Flag to check if node can be deleted
delete_curr = _delete(char_node, word, index + 1)
if delete_curr:
del curr.nodes[char]
return len(curr.nodes) == 0
return delete_curr
_delete(self, word, 0)
def print_words(node: TrieNode, word: str) -> None:
"""
Prints all the words in a Trie
:param node: root node of Trie
:param word: Word variable should be empty at start
:return: None
"""
if node.is_leaf:
print(word, end=" ")
for key, value in node.nodes.items():
print_words(value, word + key)
def test_trie() -> bool:
words = "banana bananas bandana band apple all beast".split()
root = TrieNode()
root.insert_many(words)
# print_words(root, "")
assert all(root.find(word) for word in words)
assert root.find("banana")
assert not root.find("bandanas")
assert not root.find("apps")
assert root.find("apple")
assert root.find("all")
root.delete("all")
assert not root.find("all")
root.delete("banana")
assert not root.find("banana")
assert root.find("bananas")
return True
def print_results(msg: str, passes: bool) -> None:
print(str(msg), "works!" if passes else "doesn't work :(")
def pytests() -> None:
assert test_trie()
def main() -> None:
"""
>>> pytests()
"""
print_results("Testing trie functionality", test_trie())
if __name__ == "__main__":
main()
| """
A Trie/Prefix Tree is a kind of search tree used to provide quick lookup
of words/patterns in a set of words. A basic Trie however has O(n^2) space complexity
making it impractical in practice. It however provides O(max(search_string, length of
longest word)) lookup time making it an optimal approach when space is not an issue.
"""
class TrieNode:
def __init__(self) -> None:
self.nodes: dict[str, TrieNode] = dict() # Mapping from char to TrieNode
self.is_leaf = False
def insert_many(self, words: list[str]) -> None:
"""
Inserts a list of words into the Trie
:param words: list of string words
:return: None
"""
for word in words:
self.insert(word)
def insert(self, word: str) -> None:
"""
Inserts a word into the Trie
:param word: word to be inserted
:return: None
"""
curr = self
for char in word:
if char not in curr.nodes:
curr.nodes[char] = TrieNode()
curr = curr.nodes[char]
curr.is_leaf = True
def find(self, word: str) -> bool:
"""
Tries to find word in a Trie
:param word: word to look for
:return: Returns True if word is found, False otherwise
"""
curr = self
for char in word:
if char not in curr.nodes:
return False
curr = curr.nodes[char]
return curr.is_leaf
def delete(self, word: str) -> None:
"""
Deletes a word in a Trie
:param word: word to delete
:return: None
"""
def _delete(curr: TrieNode, word: str, index: int) -> bool:
if index == len(word):
# If word does not exist
if not curr.is_leaf:
return False
curr.is_leaf = False
return len(curr.nodes) == 0
char = word[index]
char_node = curr.nodes.get(char)
# If char not in current trie node
if not char_node:
return False
# Flag to check if node can be deleted
delete_curr = _delete(char_node, word, index + 1)
if delete_curr:
del curr.nodes[char]
return len(curr.nodes) == 0
return delete_curr
_delete(self, word, 0)
def print_words(node: TrieNode, word: str) -> None:
"""
Prints all the words in a Trie
:param node: root node of Trie
:param word: Word variable should be empty at start
:return: None
"""
if node.is_leaf:
print(word, end=" ")
for key, value in node.nodes.items():
print_words(value, word + key)
def test_trie() -> bool:
words = "banana bananas bandana band apple all beast".split()
root = TrieNode()
root.insert_many(words)
# print_words(root, "")
assert all(root.find(word) for word in words)
assert root.find("banana")
assert not root.find("bandanas")
assert not root.find("apps")
assert root.find("apple")
assert root.find("all")
root.delete("all")
assert not root.find("all")
root.delete("banana")
assert not root.find("banana")
assert root.find("bananas")
return True
def print_results(msg: str, passes: bool) -> None:
print(str(msg), "works!" if passes else "doesn't work :(")
def pytests() -> None:
assert test_trie()
def main() -> None:
"""
>>> pytests()
"""
print_results("Testing trie functionality", test_trie())
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Problem 120 Square remainders: https://projecteuler.net/problem=120
Description:
Let r be the remainder when (a−1)^n + (a+1)^n is divided by a^2.
For example, if a = 7 and n = 3, then r = 42: 6^3 + 8^3 = 728 ≡ 42 mod 49.
And as n varies, so too will r, but for a = 7 it turns out that r_max = 42.
For 3 ≤ a ≤ 1000, find ∑ r_max.
Solution:
On expanding the terms, we get 2 if n is even and 2an if n is odd.
For maximizing the value, 2an < a*a => n <= (a - 1)/2 (integer division)
"""
def solution(n: int = 1000) -> int:
"""
Returns ∑ r_max for 3 <= a <= n as explained above
>>> solution(10)
300
>>> solution(100)
330750
>>> solution(1000)
333082500
"""
return sum(2 * a * ((a - 1) // 2) for a in range(3, n + 1))
if __name__ == "__main__":
print(solution())
| """
Problem 120 Square remainders: https://projecteuler.net/problem=120
Description:
Let r be the remainder when (a−1)^n + (a+1)^n is divided by a^2.
For example, if a = 7 and n = 3, then r = 42: 6^3 + 8^3 = 728 ≡ 42 mod 49.
And as n varies, so too will r, but for a = 7 it turns out that r_max = 42.
For 3 ≤ a ≤ 1000, find ∑ r_max.
Solution:
On expanding the terms, we get 2 if n is even and 2an if n is odd.
For maximizing the value, 2an < a*a => n <= (a - 1)/2 (integer division)
"""
def solution(n: int = 1000) -> int:
"""
Returns ∑ r_max for 3 <= a <= n as explained above
>>> solution(10)
300
>>> solution(100)
330750
>>> solution(1000)
333082500
"""
return sum(2 * a * ((a - 1) // 2) for a in range(3, n + 1))
if __name__ == "__main__":
print(solution())
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Problem 145: https://projecteuler.net/problem=145
Name: How many reversible numbers are there below one-billion?
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)?
Solution:
Here a brute force solution is used to find and count the reversible numbers.
"""
from __future__ import annotations
def check_if_odd(sum: int = 36) -> int:
"""
Check if the last digit in the sum is even or odd. If even return 0.
If odd then floor division by 10 is used to remove the last number.
Process continues until sum becomes 0 because no more numbers.
>>> check_if_odd(36)
0
>>> check_if_odd(33)
1
"""
while sum > 0:
if (sum % 10) % 2 == 0:
return 0
sum = sum // 10
return 1
def find_reverse_number(number: int = 36) -> int:
"""
Reverses the given number. Does not work with number that end in zero.
>>> find_reverse_number(36)
63
>>> find_reverse_number(409)
904
"""
reverse = 0
while number > 0:
temp = number % 10
reverse = reverse * 10 + temp
number = number // 10
return reverse
def solution(number: int = 1000000000) -> int:
"""
Loops over the range of numbers.
Checks if they have ending zeros which disqualifies them from being reversible.
If that condition is passed it generates the reversed number.
Then sum up n and reverse(n).
Then check if all the numbers in the sum are odd. If true add to the answer.
>>> solution(1000000000)
608720
>>> solution(1000000)
18720
>>> solution(1000000)
18720
>>> solution(1000)
120
"""
answer = 0
for x in range(1, number):
if x % 10 != 0:
reversed_number = find_reverse_number(x)
sum = x + reversed_number
answer += check_if_odd(sum)
return answer
if __name__ == "__main__":
print(f"{solution() = }")
| """
Problem 145: https://projecteuler.net/problem=145
Name: How many reversible numbers are there below one-billion?
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)?
Solution:
Here a brute force solution is used to find and count the reversible numbers.
"""
from __future__ import annotations
def check_if_odd(sum: int = 36) -> int:
"""
Check if the last digit in the sum is even or odd. If even return 0.
If odd then floor division by 10 is used to remove the last number.
Process continues until sum becomes 0 because no more numbers.
>>> check_if_odd(36)
0
>>> check_if_odd(33)
1
"""
while sum > 0:
if (sum % 10) % 2 == 0:
return 0
sum = sum // 10
return 1
def find_reverse_number(number: int = 36) -> int:
"""
Reverses the given number. Does not work with number that end in zero.
>>> find_reverse_number(36)
63
>>> find_reverse_number(409)
904
"""
reverse = 0
while number > 0:
temp = number % 10
reverse = reverse * 10 + temp
number = number // 10
return reverse
def solution(number: int = 1000000000) -> int:
"""
Loops over the range of numbers.
Checks if they have ending zeros which disqualifies them from being reversible.
If that condition is passed it generates the reversed number.
Then sum up n and reverse(n).
Then check if all the numbers in the sum are odd. If true add to the answer.
>>> solution(1000000000)
608720
>>> solution(1000000)
18720
>>> solution(1000000)
18720
>>> solution(1000)
120
"""
answer = 0
for x in range(1, number):
if x % 10 != 0:
reversed_number = find_reverse_number(x)
sum = x + reversed_number
answer += check_if_odd(sum)
return answer
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 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 = 0
sum_of_ints = 0
for i in range(1, n + 1):
sum_of_squares += i ** 2
sum_of_ints += i
return sum_of_ints ** 2 - 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 = 0
sum_of_ints = 0
for i in range(1, n + 1):
sum_of_squares += i ** 2
sum_of_ints += i
return sum_of_ints ** 2 - sum_of_squares
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import numpy as np
""" Here I implemented the scoring functions.
MAE, MSE, RMSE, RMSLE are included.
Those are used for calculating differences between
predicted values and actual values.
Metrics are slightly differentiated. Sometimes squared, rooted,
even log is used.
Using log and roots can be perceived as tools for penalizing big
errors. However, using appropriate metrics depends on the situations,
and types of data
"""
# Mean Absolute Error
def mae(predict, actual):
"""
Examples(rounded for precision):
>>> actual = [1,2,3];predict = [1,4,3]
>>> np.around(mae(predict,actual),decimals = 2)
0.67
>>> actual = [1,1,1];predict = [1,1,1]
>>> mae(predict,actual)
0.0
"""
predict = np.array(predict)
actual = np.array(actual)
difference = abs(predict - actual)
score = difference.mean()
return score
# Mean Squared Error
def mse(predict, actual):
"""
Examples(rounded for precision):
>>> actual = [1,2,3];predict = [1,4,3]
>>> np.around(mse(predict,actual),decimals = 2)
1.33
>>> actual = [1,1,1];predict = [1,1,1]
>>> mse(predict,actual)
0.0
"""
predict = np.array(predict)
actual = np.array(actual)
difference = predict - actual
square_diff = np.square(difference)
score = square_diff.mean()
return score
# Root Mean Squared Error
def rmse(predict, actual):
"""
Examples(rounded for precision):
>>> actual = [1,2,3];predict = [1,4,3]
>>> np.around(rmse(predict,actual),decimals = 2)
1.15
>>> actual = [1,1,1];predict = [1,1,1]
>>> rmse(predict,actual)
0.0
"""
predict = np.array(predict)
actual = np.array(actual)
difference = predict - actual
square_diff = np.square(difference)
mean_square_diff = square_diff.mean()
score = np.sqrt(mean_square_diff)
return score
# Root Mean Square Logarithmic Error
def rmsle(predict, actual):
"""
Examples(rounded for precision):
>>> actual = [10,10,30];predict = [10,2,30]
>>> np.around(rmsle(predict,actual),decimals = 2)
0.75
>>> actual = [1,1,1];predict = [1,1,1]
>>> rmsle(predict,actual)
0.0
"""
predict = np.array(predict)
actual = np.array(actual)
log_predict = np.log(predict + 1)
log_actual = np.log(actual + 1)
difference = log_predict - log_actual
square_diff = np.square(difference)
mean_square_diff = square_diff.mean()
score = np.sqrt(mean_square_diff)
return score
# Mean Bias Deviation
def mbd(predict, actual):
"""
This value is Negative, if the model underpredicts,
positive, if it overpredicts.
Example(rounded for precision):
Here the model overpredicts
>>> actual = [1,2,3];predict = [2,3,4]
>>> np.around(mbd(predict,actual),decimals = 2)
50.0
Here the model underpredicts
>>> actual = [1,2,3];predict = [0,1,1]
>>> np.around(mbd(predict,actual),decimals = 2)
-66.67
"""
predict = np.array(predict)
actual = np.array(actual)
difference = predict - actual
numerator = np.sum(difference) / len(predict)
denumerator = np.sum(actual) / len(predict)
# print(numerator, denumerator)
score = float(numerator) / denumerator * 100
return score
def manual_accuracy(predict, actual):
return np.mean(np.array(actual) == np.array(predict))
| import numpy as np
""" Here I implemented the scoring functions.
MAE, MSE, RMSE, RMSLE are included.
Those are used for calculating differences between
predicted values and actual values.
Metrics are slightly differentiated. Sometimes squared, rooted,
even log is used.
Using log and roots can be perceived as tools for penalizing big
errors. However, using appropriate metrics depends on the situations,
and types of data
"""
# Mean Absolute Error
def mae(predict, actual):
"""
Examples(rounded for precision):
>>> actual = [1,2,3];predict = [1,4,3]
>>> np.around(mae(predict,actual),decimals = 2)
0.67
>>> actual = [1,1,1];predict = [1,1,1]
>>> mae(predict,actual)
0.0
"""
predict = np.array(predict)
actual = np.array(actual)
difference = abs(predict - actual)
score = difference.mean()
return score
# Mean Squared Error
def mse(predict, actual):
"""
Examples(rounded for precision):
>>> actual = [1,2,3];predict = [1,4,3]
>>> np.around(mse(predict,actual),decimals = 2)
1.33
>>> actual = [1,1,1];predict = [1,1,1]
>>> mse(predict,actual)
0.0
"""
predict = np.array(predict)
actual = np.array(actual)
difference = predict - actual
square_diff = np.square(difference)
score = square_diff.mean()
return score
# Root Mean Squared Error
def rmse(predict, actual):
"""
Examples(rounded for precision):
>>> actual = [1,2,3];predict = [1,4,3]
>>> np.around(rmse(predict,actual),decimals = 2)
1.15
>>> actual = [1,1,1];predict = [1,1,1]
>>> rmse(predict,actual)
0.0
"""
predict = np.array(predict)
actual = np.array(actual)
difference = predict - actual
square_diff = np.square(difference)
mean_square_diff = square_diff.mean()
score = np.sqrt(mean_square_diff)
return score
# Root Mean Square Logarithmic Error
def rmsle(predict, actual):
"""
Examples(rounded for precision):
>>> actual = [10,10,30];predict = [10,2,30]
>>> np.around(rmsle(predict,actual),decimals = 2)
0.75
>>> actual = [1,1,1];predict = [1,1,1]
>>> rmsle(predict,actual)
0.0
"""
predict = np.array(predict)
actual = np.array(actual)
log_predict = np.log(predict + 1)
log_actual = np.log(actual + 1)
difference = log_predict - log_actual
square_diff = np.square(difference)
mean_square_diff = square_diff.mean()
score = np.sqrt(mean_square_diff)
return score
# Mean Bias Deviation
def mbd(predict, actual):
"""
This value is Negative, if the model underpredicts,
positive, if it overpredicts.
Example(rounded for precision):
Here the model overpredicts
>>> actual = [1,2,3];predict = [2,3,4]
>>> np.around(mbd(predict,actual),decimals = 2)
50.0
Here the model underpredicts
>>> actual = [1,2,3];predict = [0,1,1]
>>> np.around(mbd(predict,actual),decimals = 2)
-66.67
"""
predict = np.array(predict)
actual = np.array(actual)
difference = predict - actual
numerator = np.sum(difference) / len(predict)
denumerator = np.sum(actual) / len(predict)
# print(numerator, denumerator)
score = float(numerator) / denumerator * 100
return score
def manual_accuracy(predict, actual):
return np.mean(np.array(actual) == np.array(predict))
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| [pytest]
markers =
mat_ops: tests for matrix operations
| [pytest]
markers =
mat_ops: tests for matrix operations
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Normal Distribution QuickSort
Algorithm implementing QuickSort Algorithm where the pivot element is chosen randomly between first and last elements of the array and the array elements are taken from a Standard Normal Distribution.
This is different from the ordinary quicksort in the sense, that it applies more to real life problems , where elements usually follow a normal distribution. Also the pivot is randomized to make it a more generic one.
## Array Elements
The array elements are taken from a Standard Normal Distribution , having mean = 0 and standard deviation 1.
#### The code
```python
>>> import numpy as np
>>> from tempfile import TemporaryFile
>>> outfile = TemporaryFile()
>>> p = 100 # 100 elements are to be sorted
>>> mu, sigma = 0, 1 # mean and standard deviation
>>> X = np.random.normal(mu, sigma, p)
>>> np.save(outfile, X)
>>> print('The array is')
>>> print(X)
```
------
#### The Distribution of the Array elements.
```python
>>> mu, sigma = 0, 1 # mean and standard deviation
>>> s = np.random.normal(mu, sigma, p)
>>> count, bins, ignored = plt.hist(s, 30, normed=True)
>>> plt.plot(bins , 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (bins - mu)**2 / (2 * sigma**2) ),linewidth=2, color='r')
>>> plt.show()
```
-----

---
---------------------
--
## Plotting the function for Checking 'The Number of Comparisons' taking place between Normal Distribution QuickSort and Ordinary QuickSort
```python
>>>import matplotlib.pyplot as plt
# Normal Disrtibution QuickSort is red
>>> plt.plot([1,2,4,16,32,64,128,256,512,1024,2048],[1,1,6,15,43,136,340,800,2156,6821,16325],linewidth=2, color='r')
#Ordinary QuickSort is green
>>> plt.plot([1,2,4,16,32,64,128,256,512,1024,2048],[1,1,4,16,67,122,362,949,2131,5086,12866],linewidth=2, color='g')
>>> plt.show()
```
----
------------------
| # Normal Distribution QuickSort
Algorithm implementing QuickSort Algorithm where the pivot element is chosen randomly between first and last elements of the array and the array elements are taken from a Standard Normal Distribution.
This is different from the ordinary quicksort in the sense, that it applies more to real life problems , where elements usually follow a normal distribution. Also the pivot is randomized to make it a more generic one.
## Array Elements
The array elements are taken from a Standard Normal Distribution , having mean = 0 and standard deviation 1.
#### The code
```python
>>> import numpy as np
>>> from tempfile import TemporaryFile
>>> outfile = TemporaryFile()
>>> p = 100 # 100 elements are to be sorted
>>> mu, sigma = 0, 1 # mean and standard deviation
>>> X = np.random.normal(mu, sigma, p)
>>> np.save(outfile, X)
>>> print('The array is')
>>> print(X)
```
------
#### The Distribution of the Array elements.
```python
>>> mu, sigma = 0, 1 # mean and standard deviation
>>> s = np.random.normal(mu, sigma, p)
>>> count, bins, ignored = plt.hist(s, 30, normed=True)
>>> plt.plot(bins , 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (bins - mu)**2 / (2 * sigma**2) ),linewidth=2, color='r')
>>> plt.show()
```
-----

---
---------------------
--
## Plotting the function for Checking 'The Number of Comparisons' taking place between Normal Distribution QuickSort and Ordinary QuickSort
```python
>>>import matplotlib.pyplot as plt
# Normal Disrtibution QuickSort is red
>>> plt.plot([1,2,4,16,32,64,128,256,512,1024,2048],[1,1,6,15,43,136,340,800,2156,6821,16325],linewidth=2, color='r')
#Ordinary QuickSort is green
>>> plt.plot([1,2,4,16,32,64,128,256,512,1024,2048],[1,1,4,16,67,122,362,949,2131,5086,12866],linewidth=2, color='g')
>>> plt.show()
```
----
------------------
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Coin sums
Problem 31: https://projecteuler.net/problem=31
In England the currency is made up of pound, £, and pence, p, and there are
eight coins in general circulation:
1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
It is possible to make £2 in the following way:
1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
How many different ways can £2 be made using any number of coins?
"""
def one_pence() -> int:
return 1
def two_pence(x: int) -> int:
return 0 if x < 0 else two_pence(x - 2) + one_pence()
def five_pence(x: int) -> int:
return 0 if x < 0 else five_pence(x - 5) + two_pence(x)
def ten_pence(x: int) -> int:
return 0 if x < 0 else ten_pence(x - 10) + five_pence(x)
def twenty_pence(x: int) -> int:
return 0 if x < 0 else twenty_pence(x - 20) + ten_pence(x)
def fifty_pence(x: int) -> int:
return 0 if x < 0 else fifty_pence(x - 50) + twenty_pence(x)
def one_pound(x: int) -> int:
return 0 if x < 0 else one_pound(x - 100) + fifty_pence(x)
def two_pound(x: int) -> int:
return 0 if x < 0 else two_pound(x - 200) + one_pound(x)
def solution(n: int = 200) -> int:
"""Returns the number of different ways can n pence be made using any number of
coins?
>>> solution(500)
6295434
>>> solution(200)
73682
>>> solution(50)
451
>>> solution(10)
11
"""
return two_pound(n)
if __name__ == "__main__":
print(solution(int(input().strip())))
| """
Coin sums
Problem 31: https://projecteuler.net/problem=31
In England the currency is made up of pound, £, and pence, p, and there are
eight coins in general circulation:
1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
It is possible to make £2 in the following way:
1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
How many different ways can £2 be made using any number of coins?
"""
def one_pence() -> int:
return 1
def two_pence(x: int) -> int:
return 0 if x < 0 else two_pence(x - 2) + one_pence()
def five_pence(x: int) -> int:
return 0 if x < 0 else five_pence(x - 5) + two_pence(x)
def ten_pence(x: int) -> int:
return 0 if x < 0 else ten_pence(x - 10) + five_pence(x)
def twenty_pence(x: int) -> int:
return 0 if x < 0 else twenty_pence(x - 20) + ten_pence(x)
def fifty_pence(x: int) -> int:
return 0 if x < 0 else fifty_pence(x - 50) + twenty_pence(x)
def one_pound(x: int) -> int:
return 0 if x < 0 else one_pound(x - 100) + fifty_pence(x)
def two_pound(x: int) -> int:
return 0 if x < 0 else two_pound(x - 200) + one_pound(x)
def solution(n: int = 200) -> int:
"""Returns the number of different ways can n pence be made using any number of
coins?
>>> solution(500)
6295434
>>> solution(200)
73682
>>> solution(50)
451
>>> solution(10)
11
"""
return two_pound(n)
if __name__ == "__main__":
print(solution(int(input().strip())))
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Functions useful for doing molecular chemistry:
* molarity_to_normality
* moles_to_pressure
* moles_to_volume
* pressure_and_volume_to_temperature
"""
def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float:
"""
Convert molarity to normality.
Volume is taken in litres.
Wikipedia reference: https://en.wikipedia.org/wiki/Equivalent_concentration
Wikipedia reference: https://en.wikipedia.org/wiki/Molar_concentration
>>> molarity_to_normality(2, 3.1, 0.31)
20
>>> molarity_to_normality(4, 11.4, 5.7)
8
"""
return round(float(moles / volume) * nfactor)
def moles_to_pressure(volume: float, moles: float, temperature: float) -> float:
"""
Convert moles to pressure.
Ideal gas laws are used.
Temperature is taken in kelvin.
Volume is taken in litres.
Pressure has atm as SI unit.
Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws
Wikipedia reference: https://en.wikipedia.org/wiki/Pressure
Wikipedia reference: https://en.wikipedia.org/wiki/Temperature
>>> moles_to_pressure(0.82, 3, 300)
90
>>> moles_to_pressure(8.2, 5, 200)
10
"""
return round(float((moles * 0.0821 * temperature) / (volume)))
def moles_to_volume(pressure: float, moles: float, temperature: float) -> float:
"""
Convert moles to volume.
Ideal gas laws are used.
Temperature is taken in kelvin.
Volume is taken in litres.
Pressure has atm as SI unit.
Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws
Wikipedia reference: https://en.wikipedia.org/wiki/Pressure
Wikipedia reference: https://en.wikipedia.org/wiki/Temperature
>>> moles_to_volume(0.82, 3, 300)
90
>>> moles_to_volume(8.2, 5, 200)
10
"""
return round(float((moles * 0.0821 * temperature) / (pressure)))
def pressure_and_volume_to_temperature(
pressure: float, moles: float, volume: float
) -> float:
"""
Convert pressure and volume to temperature.
Ideal gas laws are used.
Temperature is taken in kelvin.
Volume is taken in litres.
Pressure has atm as SI unit.
Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws
Wikipedia reference: https://en.wikipedia.org/wiki/Pressure
Wikipedia reference: https://en.wikipedia.org/wiki/Temperature
>>> pressure_and_volume_to_temperature(0.82, 1, 2)
20
>>> pressure_and_volume_to_temperature(8.2, 5, 3)
60
"""
return round(float((pressure * volume) / (0.0821 * moles)))
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Functions useful for doing molecular chemistry:
* molarity_to_normality
* moles_to_pressure
* moles_to_volume
* pressure_and_volume_to_temperature
"""
def molarity_to_normality(nfactor: int, moles: float, volume: float) -> float:
"""
Convert molarity to normality.
Volume is taken in litres.
Wikipedia reference: https://en.wikipedia.org/wiki/Equivalent_concentration
Wikipedia reference: https://en.wikipedia.org/wiki/Molar_concentration
>>> molarity_to_normality(2, 3.1, 0.31)
20
>>> molarity_to_normality(4, 11.4, 5.7)
8
"""
return round(float(moles / volume) * nfactor)
def moles_to_pressure(volume: float, moles: float, temperature: float) -> float:
"""
Convert moles to pressure.
Ideal gas laws are used.
Temperature is taken in kelvin.
Volume is taken in litres.
Pressure has atm as SI unit.
Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws
Wikipedia reference: https://en.wikipedia.org/wiki/Pressure
Wikipedia reference: https://en.wikipedia.org/wiki/Temperature
>>> moles_to_pressure(0.82, 3, 300)
90
>>> moles_to_pressure(8.2, 5, 200)
10
"""
return round(float((moles * 0.0821 * temperature) / (volume)))
def moles_to_volume(pressure: float, moles: float, temperature: float) -> float:
"""
Convert moles to volume.
Ideal gas laws are used.
Temperature is taken in kelvin.
Volume is taken in litres.
Pressure has atm as SI unit.
Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws
Wikipedia reference: https://en.wikipedia.org/wiki/Pressure
Wikipedia reference: https://en.wikipedia.org/wiki/Temperature
>>> moles_to_volume(0.82, 3, 300)
90
>>> moles_to_volume(8.2, 5, 200)
10
"""
return round(float((moles * 0.0821 * temperature) / (pressure)))
def pressure_and_volume_to_temperature(
pressure: float, moles: float, volume: float
) -> float:
"""
Convert pressure and volume to temperature.
Ideal gas laws are used.
Temperature is taken in kelvin.
Volume is taken in litres.
Pressure has atm as SI unit.
Wikipedia reference: https://en.wikipedia.org/wiki/Gas_laws
Wikipedia reference: https://en.wikipedia.org/wiki/Pressure
Wikipedia reference: https://en.wikipedia.org/wiki/Temperature
>>> pressure_and_volume_to_temperature(0.82, 1, 2)
20
>>> pressure_and_volume_to_temperature(8.2, 5, 3)
60
"""
return round(float((pressure * volume) / (0.0821 * moles)))
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/env python3
"""
Davis–Putnam–Logemann–Loveland (DPLL) algorithm is a complete, backtracking-based
search algorithm for deciding the satisfiability of propositional logic formulae in
conjunctive normal form, i.e, for solving the Conjunctive Normal Form SATisfiability
(CNF-SAT) problem.
For more information about the algorithm: https://en.wikipedia.org/wiki/DPLL_algorithm
"""
from __future__ import annotations
import random
from typing import Iterable
class Clause:
"""
A clause represented in Conjunctive Normal Form.
A clause is a set of literals, either complemented or otherwise.
For example:
{A1, A2, A3'} is the clause (A1 v A2 v A3')
{A5', A2', A1} is the clause (A5' v A2' v A1)
Create model
>>> clause = Clause(["A1", "A2'", "A3"])
>>> clause.evaluate({"A1": True})
True
"""
def __init__(self, literals: list[str]) -> None:
"""
Represent the literals and an assignment in a clause."
"""
# Assign all literals to None initially
self.literals: dict[str, bool | None] = {literal: None for literal in literals}
def __str__(self) -> str:
"""
To print a clause as in Conjunctive Normal Form.
>>> str(Clause(["A1", "A2'", "A3"]))
"{A1 , A2' , A3}"
"""
return "{" + " , ".join(self.literals) + "}"
def __len__(self) -> int:
"""
To print a clause as in Conjunctive Normal Form.
>>> len(Clause([]))
0
>>> len(Clause(["A1", "A2'", "A3"]))
3
"""
return len(self.literals)
def assign(self, model: dict[str, bool | None]) -> None:
"""
Assign values to literals of the clause as given by model.
"""
for literal in self.literals:
symbol = literal[:2]
if symbol in model:
value = model[symbol]
else:
continue
if value is not None:
# Complement assignment if literal is in complemented form
if literal.endswith("'"):
value = not value
self.literals[literal] = value
def evaluate(self, model: dict[str, bool | None]) -> bool | None:
"""
Evaluates the clause with the assignments in model.
This has the following steps:
1. Return True if both a literal and its complement exist in the clause.
2. Return True if a single literal has the assignment True.
3. Return None(unable to complete evaluation) if a literal has no assignment.
4. Compute disjunction of all values assigned in clause.
"""
for literal in self.literals:
symbol = literal.rstrip("'") if literal.endswith("'") else literal + "'"
if symbol in self.literals:
return True
self.assign(model)
for value in self.literals.values():
if value in (True, None):
return value
return any(self.literals.values())
class Formula:
"""
A formula represented in Conjunctive Normal Form.
A formula is a set of clauses.
For example,
{{A1, A2, A3'}, {A5', A2', A1}} is ((A1 v A2 v A3') and (A5' v A2' v A1))
"""
def __init__(self, clauses: Iterable[Clause]) -> None:
"""
Represent the number of clauses and the clauses themselves.
"""
self.clauses = list(clauses)
def __str__(self) -> str:
"""
To print a formula as in Conjunctive Normal Form.
str(Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])]))
"{{A1 , A2' , A3} , {A5' , A2' , A1}}"
"""
return "{" + " , ".join(str(clause) for clause in self.clauses) + "}"
def generate_clause() -> Clause:
"""
Randomly generate a clause.
All literals have the name Ax, where x is an integer from 1 to 5.
"""
literals = []
no_of_literals = random.randint(1, 5)
base_var = "A"
i = 0
while i < no_of_literals:
var_no = random.randint(1, 5)
var_name = base_var + str(var_no)
var_complement = random.randint(0, 1)
if var_complement == 1:
var_name += "'"
if var_name in literals:
i -= 1
else:
literals.append(var_name)
i += 1
return Clause(literals)
def generate_formula() -> Formula:
"""
Randomly generate a formula.
"""
clauses: set[Clause] = set()
no_of_clauses = random.randint(1, 10)
while len(clauses) < no_of_clauses:
clauses.add(generate_clause())
return Formula(clauses)
def generate_parameters(formula: Formula) -> tuple[list[Clause], list[str]]:
"""
Return the clauses and symbols from a formula.
A symbol is the uncomplemented form of a literal.
For example,
Symbol of A3 is A3.
Symbol of A5' is A5.
>>> formula = Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])])
>>> clauses, symbols = generate_parameters(formula)
>>> clauses_list = [str(i) for i in clauses]
>>> clauses_list
["{A1 , A2' , A3}", "{A5' , A2' , A1}"]
>>> symbols
['A1', 'A2', 'A3', 'A5']
"""
clauses = formula.clauses
symbols_set = []
for clause in formula.clauses:
for literal in clause.literals:
symbol = literal[:2]
if symbol not in symbols_set:
symbols_set.append(symbol)
return clauses, symbols_set
def find_pure_symbols(
clauses: list[Clause], symbols: list[str], model: dict[str, bool | None]
) -> tuple[list[str], dict[str, bool | None]]:
"""
Return pure symbols and their values to satisfy clause.
Pure symbols are symbols in a formula that exist only
in one form, either complemented or otherwise.
For example,
{ { A4 , A3 , A5' , A1 , A3' } , { A4 } , { A3 } } has
pure symbols A4, A5' and A1.
This has the following steps:
1. Ignore clauses that have already evaluated to be True.
2. Find symbols that occur only in one form in the rest of the clauses.
3. Assign value True or False depending on whether the symbols occurs
in normal or complemented form respectively.
>>> formula = Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])])
>>> clauses, symbols = generate_parameters(formula)
>>> pure_symbols, values = find_pure_symbols(clauses, symbols, {})
>>> pure_symbols
['A1', 'A2', 'A3', 'A5']
>>> values
{'A1': True, 'A2': False, 'A3': True, 'A5': False}
"""
pure_symbols = []
assignment: dict[str, bool | None] = dict()
literals = []
for clause in clauses:
if clause.evaluate(model):
continue
for literal in clause.literals:
literals.append(literal)
for s in symbols:
sym = s + "'"
if (s in literals and sym not in literals) or (
s not in literals and sym in literals
):
pure_symbols.append(s)
for p in pure_symbols:
assignment[p] = None
for s in pure_symbols:
sym = s + "'"
if s in literals:
assignment[s] = True
elif sym in literals:
assignment[s] = False
return pure_symbols, assignment
def find_unit_clauses(
clauses: list[Clause], model: dict[str, bool | None]
) -> tuple[list[str], dict[str, bool | None]]:
"""
Returns the unit symbols and their values to satisfy clause.
Unit symbols are symbols in a formula that are:
- Either the only symbol in a clause
- Or all other literals in that clause have been assigned False
This has the following steps:
1. Find symbols that are the only occurrences in a clause.
2. Find symbols in a clause where all other literals are assigned False.
3. Assign True or False depending on whether the symbols occurs in
normal or complemented form respectively.
>>> clause1 = Clause(["A4", "A3", "A5'", "A1", "A3'"])
>>> clause2 = Clause(["A4"])
>>> clause3 = Clause(["A3"])
>>> clauses, symbols = generate_parameters(Formula([clause1, clause2, clause3]))
>>> unit_clauses, values = find_unit_clauses(clauses, {})
>>> unit_clauses
['A4', 'A3']
>>> values
{'A4': True, 'A3': True}
"""
unit_symbols = []
for clause in clauses:
if len(clause) == 1:
unit_symbols.append(list(clause.literals.keys())[0])
else:
Fcount, Ncount = 0, 0
for literal, value in clause.literals.items():
if value is False:
Fcount += 1
elif value is None:
sym = literal
Ncount += 1
if Fcount == len(clause) - 1 and Ncount == 1:
unit_symbols.append(sym)
assignment: dict[str, bool | None] = dict()
for i in unit_symbols:
symbol = i[:2]
assignment[symbol] = len(i) == 2
unit_symbols = [i[:2] for i in unit_symbols]
return unit_symbols, assignment
def dpll_algorithm(
clauses: list[Clause], symbols: list[str], model: dict[str, bool | None]
) -> tuple[bool | None, dict[str, bool | None] | None]:
"""
Returns the model if the formula is satisfiable, else None
This has the following steps:
1. If every clause in clauses is True, return True.
2. If some clause in clauses is False, return False.
3. Find pure symbols.
4. Find unit symbols.
>>> formula = Formula([Clause(["A4", "A3", "A5'", "A1", "A3'"]), Clause(["A4"])])
>>> clauses, symbols = generate_parameters(formula)
>>> soln, model = dpll_algorithm(clauses, symbols, {})
>>> soln
True
>>> model
{'A4': True}
"""
check_clause_all_true = True
for clause in clauses:
clause_check = clause.evaluate(model)
if clause_check is False:
return False, None
elif clause_check is None:
check_clause_all_true = False
continue
if check_clause_all_true:
return True, model
try:
pure_symbols, assignment = find_pure_symbols(clauses, symbols, model)
except RecursionError:
print("raises a RecursionError and is")
return None, {}
P = None
if len(pure_symbols) > 0:
P, value = pure_symbols[0], assignment[pure_symbols[0]]
if P:
tmp_model = model
tmp_model[P] = value
tmp_symbols = [i for i in symbols]
if P in tmp_symbols:
tmp_symbols.remove(P)
return dpll_algorithm(clauses, tmp_symbols, tmp_model)
unit_symbols, assignment = find_unit_clauses(clauses, model)
P = None
if len(unit_symbols) > 0:
P, value = unit_symbols[0], assignment[unit_symbols[0]]
if P:
tmp_model = model
tmp_model[P] = value
tmp_symbols = [i for i in symbols]
if P in tmp_symbols:
tmp_symbols.remove(P)
return dpll_algorithm(clauses, tmp_symbols, tmp_model)
P = symbols[0]
rest = symbols[1:]
tmp1, tmp2 = model, model
tmp1[P], tmp2[P] = True, False
return dpll_algorithm(clauses, rest, tmp1) or dpll_algorithm(clauses, rest, tmp2)
if __name__ == "__main__":
import doctest
doctest.testmod()
formula = generate_formula()
print(f"The formula {formula} is", end=" ")
clauses, symbols = generate_parameters(formula)
solution, model = dpll_algorithm(clauses, symbols, {})
if solution:
print(f"satisfiable with the assignment {model}.")
else:
print("not satisfiable.")
| #!/usr/bin/env python3
"""
Davis–Putnam–Logemann–Loveland (DPLL) algorithm is a complete, backtracking-based
search algorithm for deciding the satisfiability of propositional logic formulae in
conjunctive normal form, i.e, for solving the Conjunctive Normal Form SATisfiability
(CNF-SAT) problem.
For more information about the algorithm: https://en.wikipedia.org/wiki/DPLL_algorithm
"""
from __future__ import annotations
import random
from typing import Iterable
class Clause:
"""
A clause represented in Conjunctive Normal Form.
A clause is a set of literals, either complemented or otherwise.
For example:
{A1, A2, A3'} is the clause (A1 v A2 v A3')
{A5', A2', A1} is the clause (A5' v A2' v A1)
Create model
>>> clause = Clause(["A1", "A2'", "A3"])
>>> clause.evaluate({"A1": True})
True
"""
def __init__(self, literals: list[str]) -> None:
"""
Represent the literals and an assignment in a clause."
"""
# Assign all literals to None initially
self.literals: dict[str, bool | None] = {literal: None for literal in literals}
def __str__(self) -> str:
"""
To print a clause as in Conjunctive Normal Form.
>>> str(Clause(["A1", "A2'", "A3"]))
"{A1 , A2' , A3}"
"""
return "{" + " , ".join(self.literals) + "}"
def __len__(self) -> int:
"""
To print a clause as in Conjunctive Normal Form.
>>> len(Clause([]))
0
>>> len(Clause(["A1", "A2'", "A3"]))
3
"""
return len(self.literals)
def assign(self, model: dict[str, bool | None]) -> None:
"""
Assign values to literals of the clause as given by model.
"""
for literal in self.literals:
symbol = literal[:2]
if symbol in model:
value = model[symbol]
else:
continue
if value is not None:
# Complement assignment if literal is in complemented form
if literal.endswith("'"):
value = not value
self.literals[literal] = value
def evaluate(self, model: dict[str, bool | None]) -> bool | None:
"""
Evaluates the clause with the assignments in model.
This has the following steps:
1. Return True if both a literal and its complement exist in the clause.
2. Return True if a single literal has the assignment True.
3. Return None(unable to complete evaluation) if a literal has no assignment.
4. Compute disjunction of all values assigned in clause.
"""
for literal in self.literals:
symbol = literal.rstrip("'") if literal.endswith("'") else literal + "'"
if symbol in self.literals:
return True
self.assign(model)
for value in self.literals.values():
if value in (True, None):
return value
return any(self.literals.values())
class Formula:
"""
A formula represented in Conjunctive Normal Form.
A formula is a set of clauses.
For example,
{{A1, A2, A3'}, {A5', A2', A1}} is ((A1 v A2 v A3') and (A5' v A2' v A1))
"""
def __init__(self, clauses: Iterable[Clause]) -> None:
"""
Represent the number of clauses and the clauses themselves.
"""
self.clauses = list(clauses)
def __str__(self) -> str:
"""
To print a formula as in Conjunctive Normal Form.
str(Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])]))
"{{A1 , A2' , A3} , {A5' , A2' , A1}}"
"""
return "{" + " , ".join(str(clause) for clause in self.clauses) + "}"
def generate_clause() -> Clause:
"""
Randomly generate a clause.
All literals have the name Ax, where x is an integer from 1 to 5.
"""
literals = []
no_of_literals = random.randint(1, 5)
base_var = "A"
i = 0
while i < no_of_literals:
var_no = random.randint(1, 5)
var_name = base_var + str(var_no)
var_complement = random.randint(0, 1)
if var_complement == 1:
var_name += "'"
if var_name in literals:
i -= 1
else:
literals.append(var_name)
i += 1
return Clause(literals)
def generate_formula() -> Formula:
"""
Randomly generate a formula.
"""
clauses: set[Clause] = set()
no_of_clauses = random.randint(1, 10)
while len(clauses) < no_of_clauses:
clauses.add(generate_clause())
return Formula(clauses)
def generate_parameters(formula: Formula) -> tuple[list[Clause], list[str]]:
"""
Return the clauses and symbols from a formula.
A symbol is the uncomplemented form of a literal.
For example,
Symbol of A3 is A3.
Symbol of A5' is A5.
>>> formula = Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])])
>>> clauses, symbols = generate_parameters(formula)
>>> clauses_list = [str(i) for i in clauses]
>>> clauses_list
["{A1 , A2' , A3}", "{A5' , A2' , A1}"]
>>> symbols
['A1', 'A2', 'A3', 'A5']
"""
clauses = formula.clauses
symbols_set = []
for clause in formula.clauses:
for literal in clause.literals:
symbol = literal[:2]
if symbol not in symbols_set:
symbols_set.append(symbol)
return clauses, symbols_set
def find_pure_symbols(
clauses: list[Clause], symbols: list[str], model: dict[str, bool | None]
) -> tuple[list[str], dict[str, bool | None]]:
"""
Return pure symbols and their values to satisfy clause.
Pure symbols are symbols in a formula that exist only
in one form, either complemented or otherwise.
For example,
{ { A4 , A3 , A5' , A1 , A3' } , { A4 } , { A3 } } has
pure symbols A4, A5' and A1.
This has the following steps:
1. Ignore clauses that have already evaluated to be True.
2. Find symbols that occur only in one form in the rest of the clauses.
3. Assign value True or False depending on whether the symbols occurs
in normal or complemented form respectively.
>>> formula = Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])])
>>> clauses, symbols = generate_parameters(formula)
>>> pure_symbols, values = find_pure_symbols(clauses, symbols, {})
>>> pure_symbols
['A1', 'A2', 'A3', 'A5']
>>> values
{'A1': True, 'A2': False, 'A3': True, 'A5': False}
"""
pure_symbols = []
assignment: dict[str, bool | None] = dict()
literals = []
for clause in clauses:
if clause.evaluate(model):
continue
for literal in clause.literals:
literals.append(literal)
for s in symbols:
sym = s + "'"
if (s in literals and sym not in literals) or (
s not in literals and sym in literals
):
pure_symbols.append(s)
for p in pure_symbols:
assignment[p] = None
for s in pure_symbols:
sym = s + "'"
if s in literals:
assignment[s] = True
elif sym in literals:
assignment[s] = False
return pure_symbols, assignment
def find_unit_clauses(
clauses: list[Clause], model: dict[str, bool | None]
) -> tuple[list[str], dict[str, bool | None]]:
"""
Returns the unit symbols and their values to satisfy clause.
Unit symbols are symbols in a formula that are:
- Either the only symbol in a clause
- Or all other literals in that clause have been assigned False
This has the following steps:
1. Find symbols that are the only occurrences in a clause.
2. Find symbols in a clause where all other literals are assigned False.
3. Assign True or False depending on whether the symbols occurs in
normal or complemented form respectively.
>>> clause1 = Clause(["A4", "A3", "A5'", "A1", "A3'"])
>>> clause2 = Clause(["A4"])
>>> clause3 = Clause(["A3"])
>>> clauses, symbols = generate_parameters(Formula([clause1, clause2, clause3]))
>>> unit_clauses, values = find_unit_clauses(clauses, {})
>>> unit_clauses
['A4', 'A3']
>>> values
{'A4': True, 'A3': True}
"""
unit_symbols = []
for clause in clauses:
if len(clause) == 1:
unit_symbols.append(list(clause.literals.keys())[0])
else:
Fcount, Ncount = 0, 0
for literal, value in clause.literals.items():
if value is False:
Fcount += 1
elif value is None:
sym = literal
Ncount += 1
if Fcount == len(clause) - 1 and Ncount == 1:
unit_symbols.append(sym)
assignment: dict[str, bool | None] = dict()
for i in unit_symbols:
symbol = i[:2]
assignment[symbol] = len(i) == 2
unit_symbols = [i[:2] for i in unit_symbols]
return unit_symbols, assignment
def dpll_algorithm(
clauses: list[Clause], symbols: list[str], model: dict[str, bool | None]
) -> tuple[bool | None, dict[str, bool | None] | None]:
"""
Returns the model if the formula is satisfiable, else None
This has the following steps:
1. If every clause in clauses is True, return True.
2. If some clause in clauses is False, return False.
3. Find pure symbols.
4. Find unit symbols.
>>> formula = Formula([Clause(["A4", "A3", "A5'", "A1", "A3'"]), Clause(["A4"])])
>>> clauses, symbols = generate_parameters(formula)
>>> soln, model = dpll_algorithm(clauses, symbols, {})
>>> soln
True
>>> model
{'A4': True}
"""
check_clause_all_true = True
for clause in clauses:
clause_check = clause.evaluate(model)
if clause_check is False:
return False, None
elif clause_check is None:
check_clause_all_true = False
continue
if check_clause_all_true:
return True, model
try:
pure_symbols, assignment = find_pure_symbols(clauses, symbols, model)
except RecursionError:
print("raises a RecursionError and is")
return None, {}
P = None
if len(pure_symbols) > 0:
P, value = pure_symbols[0], assignment[pure_symbols[0]]
if P:
tmp_model = model
tmp_model[P] = value
tmp_symbols = [i for i in symbols]
if P in tmp_symbols:
tmp_symbols.remove(P)
return dpll_algorithm(clauses, tmp_symbols, tmp_model)
unit_symbols, assignment = find_unit_clauses(clauses, model)
P = None
if len(unit_symbols) > 0:
P, value = unit_symbols[0], assignment[unit_symbols[0]]
if P:
tmp_model = model
tmp_model[P] = value
tmp_symbols = [i for i in symbols]
if P in tmp_symbols:
tmp_symbols.remove(P)
return dpll_algorithm(clauses, tmp_symbols, tmp_model)
P = symbols[0]
rest = symbols[1:]
tmp1, tmp2 = model, model
tmp1[P], tmp2[P] = True, False
return dpll_algorithm(clauses, rest, tmp1) or dpll_algorithm(clauses, rest, tmp2)
if __name__ == "__main__":
import doctest
doctest.testmod()
formula = generate_formula()
print(f"The formula {formula} is", end=" ")
clauses, symbols = generate_parameters(formula)
solution, model = dpll_algorithm(clauses, symbols, {})
if solution:
print(f"satisfiable with the assignment {model}.")
else:
print("not satisfiable.")
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
python/black : True
"""
from __future__ import annotations
def prime_factors(n: int) -> list[int]:
"""
Returns prime factors of n as a list.
>>> prime_factors(0)
[]
>>> prime_factors(100)
[2, 2, 5, 5]
>>> prime_factors(2560)
[2, 2, 2, 2, 2, 2, 2, 2, 2, 5]
>>> prime_factors(10**-2)
[]
>>> prime_factors(0.02)
[]
>>> x = prime_factors(10**241) # doctest: +NORMALIZE_WHITESPACE
>>> x == [2]*241 + [5]*241
True
>>> prime_factors(10**-354)
[]
>>> prime_factors('hello')
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'str'
>>> prime_factors([1,2,'hello'])
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'list'
"""
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
python/black : True
"""
from __future__ import annotations
def prime_factors(n: int) -> list[int]:
"""
Returns prime factors of n as a list.
>>> prime_factors(0)
[]
>>> prime_factors(100)
[2, 2, 5, 5]
>>> prime_factors(2560)
[2, 2, 2, 2, 2, 2, 2, 2, 2, 5]
>>> prime_factors(10**-2)
[]
>>> prime_factors(0.02)
[]
>>> x = prime_factors(10**241) # doctest: +NORMALIZE_WHITESPACE
>>> x == [2]*241 + [5]*241
True
>>> prime_factors(10**-354)
[]
>>> prime_factors('hello')
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'str'
>>> prime_factors([1,2,'hello'])
Traceback (most recent call last):
...
TypeError: '<=' not supported between instances of 'int' and 'list'
"""
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from __future__ import annotations
import random
import string
class ShuffledShiftCipher:
"""
This algorithm uses the Caesar Cipher algorithm but removes the option to
use brute force to decrypt the message.
The passcode is a a random password from the selection buffer of
1. uppercase letters of the English alphabet
2. lowercase letters of the English alphabet
3. digits from 0 to 9
Using unique characters from the passcode, the normal list of characters,
that can be allowed in the plaintext, is pivoted and shuffled. Refer to docstring
of __make_key_list() to learn more about the shuffling.
Then, using the passcode, a number is calculated which is used to encrypt the
plaintext message with the normal shift cipher method, only in this case, the
reference, to look back at while decrypting, is shuffled.
Each cipher object can possess an optional argument as passcode, without which a
new passcode is generated for that object automatically.
cip1 = ShuffledShiftCipher('d4usr9TWxw9wMD')
cip2 = ShuffledShiftCipher()
"""
def __init__(self, passcode: str | None = None) -> None:
"""
Initializes a cipher object with a passcode as it's entity
Note: No new passcode is generated if user provides a passcode
while creating the object
"""
self.__passcode = passcode or self.__passcode_creator()
self.__key_list = self.__make_key_list()
self.__shift_key = self.__make_shift_key()
def __str__(self) -> str:
"""
:return: passcode of the cipher object
"""
return "Passcode is: " + "".join(self.__passcode)
def __neg_pos(self, iterlist: list[int]) -> list[int]:
"""
Mutates the list by changing the sign of each alternate element
:param iterlist: takes a list iterable
:return: the mutated list
"""
for i in range(1, len(iterlist), 2):
iterlist[i] *= -1
return iterlist
def __passcode_creator(self) -> list[str]:
"""
Creates a random password from the selection buffer of
1. uppercase letters of the English alphabet
2. lowercase letters of the English alphabet
3. digits from 0 to 9
:rtype: list
:return: a password of a random length between 10 to 20
"""
choices = string.ascii_letters + string.digits
password = [random.choice(choices) for _ in range(random.randint(10, 20))]
return password
def __make_key_list(self) -> list[str]:
"""
Shuffles the ordered character choices by pivoting at breakpoints
Breakpoints are the set of characters in the passcode
eg:
if, ABCDEFGHIJKLMNOPQRSTUVWXYZ are the possible characters
and CAMERA is the passcode
then, breakpoints = [A,C,E,M,R] # sorted set of characters from passcode
shuffled parts: [A,CB,ED,MLKJIHGF,RQPON,ZYXWVUTS]
shuffled __key_list : ACBEDMLKJIHGFRQPONZYXWVUTS
Shuffling only 26 letters of the english alphabet can generate 26!
combinations for the shuffled list. In the program we consider, a set of
97 characters (including letters, digits, punctuation and whitespaces),
thereby creating a possibility of 97! combinations (which is a 152 digit number
in itself), thus diminishing the possibility of a brute force approach.
Moreover, shift keys even introduce a multiple of 26 for a brute force approach
for each of the already 97! combinations.
"""
# key_list_options contain nearly all printable except few elements from
# string.whitespace
key_list_options = (
string.ascii_letters + string.digits + string.punctuation + " \t\n"
)
keys_l = []
# creates points known as breakpoints to break the key_list_options at those
# points and pivot each substring
breakpoints = sorted(set(self.__passcode))
temp_list: list[str] = []
# algorithm for creating a new shuffled list, keys_l, out of key_list_options
for i in key_list_options:
temp_list.extend(i)
# checking breakpoints at which to pivot temporary sublist and add it into
# keys_l
if i in breakpoints or i == key_list_options[-1]:
keys_l.extend(temp_list[::-1])
temp_list.clear()
# returning a shuffled keys_l to prevent brute force guessing of shift key
return keys_l
def __make_shift_key(self) -> int:
"""
sum() of the mutated list of ascii values of all characters where the
mutated list is the one returned by __neg_pos()
"""
num = sum(self.__neg_pos([ord(x) for x in self.__passcode]))
return num if num > 0 else len(self.__passcode)
def decrypt(self, encoded_message: str) -> str:
"""
Performs shifting of the encoded_message w.r.t. the shuffled __key_list
to create the decoded_message
>>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44')
>>> ssc.decrypt("d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#")
'Hello, this is a modified Caesar cipher'
"""
decoded_message = ""
# decoding shift like Caesar cipher algorithm implementing negative shift or
# reverse shift or left shift
for i in encoded_message:
position = self.__key_list.index(i)
decoded_message += self.__key_list[
(position - self.__shift_key) % -len(self.__key_list)
]
return decoded_message
def encrypt(self, plaintext: str) -> str:
"""
Performs shifting of the plaintext w.r.t. the shuffled __key_list
to create the encoded_message
>>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44')
>>> ssc.encrypt('Hello, this is a modified Caesar cipher')
"d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#"
"""
encoded_message = ""
# encoding shift like Caesar cipher algorithm implementing positive shift or
# forward shift or right shift
for i in plaintext:
position = self.__key_list.index(i)
encoded_message += self.__key_list[
(position + self.__shift_key) % len(self.__key_list)
]
return encoded_message
def test_end_to_end(msg: str = "Hello, this is a modified Caesar cipher") -> str:
"""
>>> test_end_to_end()
'Hello, this is a modified Caesar cipher'
"""
cip1 = ShuffledShiftCipher()
return cip1.decrypt(cip1.encrypt(msg))
if __name__ == "__main__":
import doctest
doctest.testmod()
| from __future__ import annotations
import random
import string
class ShuffledShiftCipher:
"""
This algorithm uses the Caesar Cipher algorithm but removes the option to
use brute force to decrypt the message.
The passcode is a a random password from the selection buffer of
1. uppercase letters of the English alphabet
2. lowercase letters of the English alphabet
3. digits from 0 to 9
Using unique characters from the passcode, the normal list of characters,
that can be allowed in the plaintext, is pivoted and shuffled. Refer to docstring
of __make_key_list() to learn more about the shuffling.
Then, using the passcode, a number is calculated which is used to encrypt the
plaintext message with the normal shift cipher method, only in this case, the
reference, to look back at while decrypting, is shuffled.
Each cipher object can possess an optional argument as passcode, without which a
new passcode is generated for that object automatically.
cip1 = ShuffledShiftCipher('d4usr9TWxw9wMD')
cip2 = ShuffledShiftCipher()
"""
def __init__(self, passcode: str | None = None) -> None:
"""
Initializes a cipher object with a passcode as it's entity
Note: No new passcode is generated if user provides a passcode
while creating the object
"""
self.__passcode = passcode or self.__passcode_creator()
self.__key_list = self.__make_key_list()
self.__shift_key = self.__make_shift_key()
def __str__(self) -> str:
"""
:return: passcode of the cipher object
"""
return "Passcode is: " + "".join(self.__passcode)
def __neg_pos(self, iterlist: list[int]) -> list[int]:
"""
Mutates the list by changing the sign of each alternate element
:param iterlist: takes a list iterable
:return: the mutated list
"""
for i in range(1, len(iterlist), 2):
iterlist[i] *= -1
return iterlist
def __passcode_creator(self) -> list[str]:
"""
Creates a random password from the selection buffer of
1. uppercase letters of the English alphabet
2. lowercase letters of the English alphabet
3. digits from 0 to 9
:rtype: list
:return: a password of a random length between 10 to 20
"""
choices = string.ascii_letters + string.digits
password = [random.choice(choices) for _ in range(random.randint(10, 20))]
return password
def __make_key_list(self) -> list[str]:
"""
Shuffles the ordered character choices by pivoting at breakpoints
Breakpoints are the set of characters in the passcode
eg:
if, ABCDEFGHIJKLMNOPQRSTUVWXYZ are the possible characters
and CAMERA is the passcode
then, breakpoints = [A,C,E,M,R] # sorted set of characters from passcode
shuffled parts: [A,CB,ED,MLKJIHGF,RQPON,ZYXWVUTS]
shuffled __key_list : ACBEDMLKJIHGFRQPONZYXWVUTS
Shuffling only 26 letters of the english alphabet can generate 26!
combinations for the shuffled list. In the program we consider, a set of
97 characters (including letters, digits, punctuation and whitespaces),
thereby creating a possibility of 97! combinations (which is a 152 digit number
in itself), thus diminishing the possibility of a brute force approach.
Moreover, shift keys even introduce a multiple of 26 for a brute force approach
for each of the already 97! combinations.
"""
# key_list_options contain nearly all printable except few elements from
# string.whitespace
key_list_options = (
string.ascii_letters + string.digits + string.punctuation + " \t\n"
)
keys_l = []
# creates points known as breakpoints to break the key_list_options at those
# points and pivot each substring
breakpoints = sorted(set(self.__passcode))
temp_list: list[str] = []
# algorithm for creating a new shuffled list, keys_l, out of key_list_options
for i in key_list_options:
temp_list.extend(i)
# checking breakpoints at which to pivot temporary sublist and add it into
# keys_l
if i in breakpoints or i == key_list_options[-1]:
keys_l.extend(temp_list[::-1])
temp_list.clear()
# returning a shuffled keys_l to prevent brute force guessing of shift key
return keys_l
def __make_shift_key(self) -> int:
"""
sum() of the mutated list of ascii values of all characters where the
mutated list is the one returned by __neg_pos()
"""
num = sum(self.__neg_pos([ord(x) for x in self.__passcode]))
return num if num > 0 else len(self.__passcode)
def decrypt(self, encoded_message: str) -> str:
"""
Performs shifting of the encoded_message w.r.t. the shuffled __key_list
to create the decoded_message
>>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44')
>>> ssc.decrypt("d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#")
'Hello, this is a modified Caesar cipher'
"""
decoded_message = ""
# decoding shift like Caesar cipher algorithm implementing negative shift or
# reverse shift or left shift
for i in encoded_message:
position = self.__key_list.index(i)
decoded_message += self.__key_list[
(position - self.__shift_key) % -len(self.__key_list)
]
return decoded_message
def encrypt(self, plaintext: str) -> str:
"""
Performs shifting of the plaintext w.r.t. the shuffled __key_list
to create the encoded_message
>>> ssc = ShuffledShiftCipher('4PYIXyqeQZr44')
>>> ssc.encrypt('Hello, this is a modified Caesar cipher')
"d>**-1z6&'5z'5z:z+-='$'>=zp:>5:#z<'.&>#"
"""
encoded_message = ""
# encoding shift like Caesar cipher algorithm implementing positive shift or
# forward shift or right shift
for i in plaintext:
position = self.__key_list.index(i)
encoded_message += self.__key_list[
(position + self.__shift_key) % len(self.__key_list)
]
return encoded_message
def test_end_to_end(msg: str = "Hello, this is a modified Caesar cipher") -> str:
"""
>>> test_end_to_end()
'Hello, this is a modified Caesar cipher'
"""
cip1 = ShuffledShiftCipher()
return cip1.decrypt(cip1.encrypt(msg))
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 5,808 | [mypy] Fix `matrix_operation.py` | ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| Rohanrbharadwaj | "2021-11-10T14:32:23Z" | "2021-11-10T15:22:52Z" | d6a1623448f2494fbb21116b6bc699dccb0401b2 | e9882e41ba7a1d1fbdc12362a522a1b646497192 | [mypy] Fix `matrix_operation.py`. ### Describe your change:
Related to #4052
Replacement for #5806
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| PNG
IHDR ʮ sRGB gAMA a pHYs t tfx IDATx^דfו _3c46=cfSU% B{pwZkZkIA2H A2sosGXcnUߕgu9b d+dɋ\.p\./O.p\.p\_.Ȃ\.p\.
.Ȃ\.p\.
.Ȃ\.p\.
.Ȃ\.p\.
j@/p_2q!L\./'BYGmںeim¦emX~ӹeٝlز
[\ڲ?
+rm[ОՌZK<ybV?guftߪGjd*8|0JvPl;V wo[.ӱiYྲt,gqYcъ6e7GyfaR6,唦uKi\5~qܫ_;u,Fy~ŷݪ]qh=pcuzySΟܰi~/9gv,,]2[}ߓEujY5vzٮW-KvrѮT,صyZfr*>[^Zvj([7JRɬU:koXD%[%|3QsoUj[7JJ;ǹ8JZ(ٯeR¾}.a[?=
oƿ~ӶuᲶimW(.eh]U֯vw|bޮڮw^hI7(Wq#_۩Lw쏏 x9oTߧo;_D=~FP$iM+.+{5F,empv~ǿؗںmJWJGbU?ܚ'ip|&r*|uʒ+8=G~_}G^߾euYF=ضSHO ڮ]^f 3~ۼeZNSl>K8<BYqϬ=lB6[Na.a#o=l6Ǹm
nm
կYG
)W6,Yj#
\oYj3xL=G9[7v:vv$լ9W8U.Rh+IUmJZv%OؽIЮVd<\*_:t^#yf1[<kW~{$uEɴҙS\r]yW5tuwdS~ٿ wW]G3v|L9|zT#$]k {ķΓ,l~2E]l\D.+Ѳj]ۖ _ٗ_~iVұf%]V30mG+w<j6zb5CV=xpdC d.p gZ?>lHf-ruYv4:ƾ+~gwL#Ct6r){#cBlﹽ: K|>6<'[<hXqOK_D~!isp;-U[k6}=r
{J]B˖Rђ]A
Ec\kwKzxX5`͜fdhƮLi1Xv$s@
=u{QϿWX`xΐKl9-v$Dw߆DyOs _
zLZ{QA~^u5֯nGٖ'!I蓛svb}<m7$Ӿ_z@1߆ׯ8d~ifMQ'׃
m&g~篬axr[~pZ}'6j{MZzbuvUooӍoϟK,;oeop?r1Fc[߮;U
wcJ^9:cnӂo}yɒq)
ɭZľeKi~ {yя}2of}CM1}ŏIiys.*[uܒws2{ó9:9t\r21
~>uoS'#e[`ۮSbWkPgwnـt։%eWb_)CS7;vF8G=TMɾ2]ge[]K!vblإװVjFxƿ~}%\JI>gHYѡ2'UvBEG/8nT
9W`qfmmmqsԡj&'|wWL8|bcٯ(G8?RWd?3YEpkӊh0(x/&p߶M[Yݶ/~jVѷe;8;V3g5c(9{uY5D"TIyPN8)" "'2\ɑ e?
dm>q1 qUv.Z~x6oZ9WD$<;r
+(]B7 o@zNj@]>:GL,'ï9!"
Psқý|$(0a(_ȽJu+ǃSVP?h+(E*M[l Czg:,r$p2cD|0S~vlx]玃w9*϶:zH7A#o¹|_TٮR?8 s_Nئeޡ_Ժ@ H r4$81!AI lGIyLpHDhf5r/i[e?@r-b yxܽK m{^Xeak[zojgl_Xym}ϭmjD`E#V
d?_NB^GvEJ"G2NS8]"p0XY=WbpKq$?8 Gܻv^idn58]۲o1^HoT<(ˁԷwqT8ACu_B "D<QSL3SjӽIzתGP@)odfՆAp~紬nڝap|ƶ?hꫜ8o~"b@Ya^r@.?bZ" tee ~u=zNԈwt5^$h yw8NG}v;/IyPj#*þew!7yc-O9'`/-!1n3/`68hUj XxjOڧ7odJ%=;V@ sfC/H$k
Yv-aۥ;ێjClXI2H|DȂpjpFHoI鄪'[m{8wuJ
}8HKSOk]pzsL_#0Z٫t&(Ul}X.n)6C?Fɴ]E>i.o YYsJɲJUp! tΫl; :.sy8_w.!QsJ!&<
,djpI;'TW7˦úە3ٺ
^G%x<ԃT.[в({-@{jfljy~?oO-[Ekx:[Ȟ5Zc}|kXck{۪|tl#*_|5bunl~ut.ۯ"O\GA28}UeW۴n[~HC|v.T0@0nf>}N ugIS|k])!țq|F:zpc"A)m>3qbkŤP@ DVS#Jn-9.!+fc{P>hKmbΫ\+fNzD Ɂ0سe`_$-tD=/)W h]d6f ǔ7-a#|7.Z'N(m*'
A$& /TG+7jܨfǸVR$_10~nPgDODN"p%ݡſ?}|w_V֭~xǪA6U<l`8" pDDc !$IKdž:w-B&FWFVY1݂6l q(d) 0rDA G]p2@ BB
)Tvd(ȿx{H
,P2 DP-Rx ΟTA`H-^VP-{}V^aphnFd*N_[piz8oL>F 8Y!s#\_PpvJ<Sb[Ur#g!\}@LH6N R@*Ck!z "[ݱu^:@yԩu92JtRΆ!QIJ]NtQA-~%n2`[
EC[zU4?-Xmش"t@ F!K/u
ɸֶ
8eɽZ۽G`imsȹrtE>wv&g90ܪG6]I D v^Dp^۱hw) N -zMϺoE^^&"&ܡo+0쭊IK}ʨIzϮTٍ3
eb߆ ɷ2
E.y.XE^8!Ő.<rCACؗBu|YDG!B= |$4sA7_qF頎\( w"qPcs9X"\u<=FYb*EZ+?a_}GmYȢgTM'Y]pe
)s@Ego@6rEuo?19eZ%()[9KU!ܸgTn؍mtݪ5~fZ: [(B$ʠW^,)8N U_ci!{ArF,S_%85pY,! e
V:kUC~%WyfF+%v
qUrɺˁp 4{9D?3;Oc$Dk?qߵ211" i!"C9+ 6"5P-'"D<$`;L=V{d='C+=C h^Cw~:ߵ6ʆk_!{O{n{בu+ /B_!ʜFv ؓ ,8Qp[?@P;?l_-dJ
P{vmH>G.bٚ
=8oB~C\'!7k[v f픗
T=MȆ;:G }ݏȈB ><;7e3'ɕz=1lfɂ5,sm.f-/?[f]eOۭ>{PfOV~%3v`LY3NI;vM@vmS!&
_ޮr ڎuNy>^'+q_goCϗoΈ@z#9v?7*DOS):qge B2]T ADR>gD]7K=}E;j&8ȓqV&/`/U#[co_Yu?ضmāڳU{vrhk'unj[`AAZEx'Xv7J;KVmmWJ!7aD.@
OIIIq"vɀ$7QNjArGh3P:N獳{][<N绁c
t>/B ҝN(KvtJL!`U,p p7p,4,ྫ&D[`8g< v"BD" ݇qu "& |
u ` ?8pD?8%lppk,h_'H3_=zV'&B
<@yBbwSr 'ADr=`6;߃p:0FP˵zOj;KN h6BBD=˾Z;ozbM *AYмM/o/_̒
n0l"sV:[Yà=Omlت:ss{g̡3?h߶]G8'Z?
SW,iβRDoVoyuNC5ʽfܣMBNpmq@7J9zk'}J 9v'ٽ8/&.EI5r/sZu=1Yo#$gWKU#_RKG?
:-C6]ϩ);Pq䊺0,pb́\*XGt?D+Fpy;<&Tqp_"{93(V(HQYY ,-7{}sQTc`A+h 8OE(p/{@v?_߇M#0X^X?kӟlVl¡-ҡ]}b%lrUw/! DrujAb{o6a_?Bk}\O@P?iM{Pku蚖%GGy\ry6T> X߅euSﷆ@([~$N<=Q$Upr '50x~_zjW8ROg{xݢx&ŎwUomj[,^Jg|G8͔
7A芠e +l群$sȩr6'JA쟇^D5!]xݫ<Ca H-zK~cRPb"O)Q]^pqf
֩Kw7"V7
IGq<9=]+ڷ'Vpp?ݴE[Z?ZCyf]{ >kUu6?*6 ,w [ۅгC|M~@}{AHiQvoEf-@=^?~79:xύ3ھ0{[gG,+b t{|:ȂߨD'9uEA
SoAnVcw+w1 '18{nڮF&e ^ J$QG fOzuCYok]F&Ԟ}c鮽b[mt_A]+Ue%
ïkn n@Lе5~W8~
[¶#IeR
^%N# *um[ 0y彇w/>!s8Q5J|ALj
1Je{0u>M'&rk0$C tJDz dANW"@ 7<@(5T-[]۵~K'p$6pvP6VJQݻl6Ċp:9XlVE jIZNơxCp(ؿs$aw8roS>aݬ̺2wgg0`9!]@pܴ=
R ¨
ANRB3:GܗX+22r O+V)#crՏѾ H'XVmm~`]okDcxYq-/QVvEIq]??vp$XIS__CbPDpGc
`^Z3EeA
Nzt-/zh½N&7b+@qxj2b}-
ۘL%XAH wU+c.P⠦D=eoslNABuPq:Vܳ>XkU`_mhzCnp֊TXIÈg{/VL0@5C@P
}Mpd]
UKQyp旑
?Niu,el^Ze5
Y;D`!&x=qK[r9XV?cI灂F8iLA^bI}K[YC-yCffϬ#R1Lptk@zmge,KOHցjԚ(Vh@g7qg{σ@ĤM0A(L:_UpJ,~K}ɂDu=F"g̻K^y߹ش"8C
nY``ŚUCSV?m;8UYA͠gso[YnIkw&.Q@Y-t*M$r@Ǚ8xθ[MP=jȳշy uۜw30b<ˋoR6a3DQ9o@ى"'}2 y ɳdߡ刄d_Agy%t[oPJXw{|;+8Wpx/gwٓmeاzKYu^?T/,(
2/Qg7d_r2uɽH
p>dc:.qgI{Wѽz-~l)PWT@v2^o"[M[P{vȂc#CzZ^/B`:flf~?_}tksBqtr
lnݿnnIU}A?Av=_]ND "YJܪI˪[LΛs{Ku|w1&?SkYP 檐QYJW˱ĝ3himPր:R7'!5UY֩+kѱKhp,;IDAhTI߲5f^_Y䕜._nCkGvQ]Y' uScg:
E\ "ے\@n3Ds }d&
1|WH'1yc9\2B|Ui,)ޝ)K>zճGx\i&Μ2@y:^I"b=}gG?|eT
Zؾmڎ}/7M.oZWPڷM`Ǘ->@Bvf @#u1 ;%NmDI:)`?&n~K};4ZW@qp^$/[:,@"-8Ae?r4Hc=AIQS7=)B?L`l~9
7pA?"$LڔnUF) K~B餁m(8<PGG8v1V㴸`ˇ1VJsQ)7CBSƃZd%4n8uLT^At@(`ZΒA1"jqpen;&!35C"%>k^=-\C vpbg ckǞ,A̶]"D(<28juRK G5",rD kY-]AU#V;ku{U+ZCz`sxf/Y_5+¾U+SwI_9ZI뜕!9pb {2:<8xԱB{r}ɩ:e(
(%A`vAy(֑){1^]iw+t9tȇ.AK.2#}g<$0:B48Y`AjeI{w]TC=Q+62%uBmqezv͖JpJÿҝ+5ɂ;8dSDYCXi}"g'
( SϜpy8o"_w=sG=7}'\'Qwx}ƁZ%b &b86Q
e˔e\"+تBlr?z`kزU+سkܱ[Tf'Ma'*i&V"ٟmG@$arH^P4x(LIn%3i9~f_O[Vˬ7:`tt¦!!Av=yݖζvɷ; r=ux.=S&-qiߔ_[N7)&WàW|`o/}Zg++n[Nzi72ݖhk%3.^9qduVvy܇6<߷Ⱦh9Ƨupd|
g2*lcqZֶWPwJ1dnUW˂weM, yy,JdJ|lpgXȞu/}gA}YWg-/
ز|lb
Nޅ܆6) ]
br@˩x]RC i9M"35NY
2ٰhY"{ns=Twyδ=d{jǒ%wqA
7c/ftksSu[xu4( :|akvH r1u[ʱ"kJW{qK"wcdՒ:Oe7N\=(#ĻRVO@ם¸dpT=ODXLzYr]B^5;xGj/UYAu15@O=lcHy
7$ĠЕ1C>n2OjeSG[i[ae҄10ɖH2}ZNDz dk|AP3バ)Я&hݳ}ޱ]CD-X;RJ9ǃԌm?23uEYJ?Vd9aнr` ) *;(GV\%˨tgBDA@ h},D=8ޕ,P6ߠ0AXv)6jD
3il
$"DȰ^(P-
ߔ د}Zq2{7H;R`w'䬲||wX1e6?,H#k:d0r$m~mr/'
xFKABvΠG-j)N+%.g;&8l=si99<R;Fh y_0u}k?~K뺆9
㝈Hg}dCM{qD9J[{78yz%re_W"m+X57Z
N-ں/筶oɪ֭xpъ;Vٹd}{ZnV%Ҡ3۶!ْ|IgH6+nYyq+Lus|ЁJ
"\X6DaǸ=_$Yrw My8'V;
u8!XY\ۮi^]o@/ٕj:$'Ou+ۃxPuٕj{dVXRV<c7*bbn,PJyO; 'PKVmyLgThd4eY?|O>StD"tAoq:&>i21P<}c%$fF$ctU+=d<gdJ"3=*̯1d
8Ob`ߪf&OoZؑՎ[u/֮/?zkj#Kmz6l:QX}`y={#ѾA(Y|/٧8Qxγy(M$jT@![n"N?ca8cYѸ~=w?"7V& ,صGEӳcYCE$H2d ~"
rOze}۟~M?*Hֻ^;]a`N^4%W=g=d`sQ;HTau-qA#we=p*&~[Cpd>sJn׃\:G%Y
`'yWϒYsgR$ ή=/sC AA4;
1IQc"</ٵAd~~`ݴM}k;CX͍]?zwujͰ`zm[a<?{`2)ҁ?q ږ쳂S(؈]?@b$h9 @$"mmF=R=su]F^,wRpW#(}U
ּԶ0 !!fHi
=9Oݻ' %]W}yHW1 fZ+(o!־%zY8G@b{ͫر\ľW.mrЏ-ӆVZvn$ލz|x3*4xaLl"-5ʟ_@BLV|qMF5&Zhޛc͡
'
BUqzAzrWP|5]k#$Vݍen`SXC)S'OUq²weBECѲȗp/} Y%S%@]dXJ2Xߙ,i4k5uڑ}ka<0vd=?~mdiךah1,%P精
ͽ+!ȊG9V;n8
b,hPAja$;"{
uQ8_F 4cMTR'Bg cVewt#AJJ'ҹ=%Rc_QA z( b}pue 2 6lNDp"`;/cTzrD68@I7!& shwJmCBY>emv%]g)a
c0OwS"^.8h{mWݟ;R^7p@J ů\_eQz'8j}b,P
M!' @Cۥ"A@'B8u?ίgZѳ0{Ai:S,FfpۚG4OZ܉5
.ƾx_6SUoZ:AêU
l8ZIۢ5k2
D(Uϝ4N-aw1w4ry~=ƷAr1Ar9arkf~{D VK CrZJʿ&ϝY'Cd7TJmSp. i<_?Rk)zMz&
Ξz*C?o$BHD:I,+U=a#6rd7KyiA1M\ !FHC<}{k8p
%z ͳOu;mζSmAN
5dη3q@kpBS}0mt81oo
6prn]0@j,Ne[;+^' !qޅd?!^d_/GNTb㇞]PNhyfM3'2as['/g_O68j%8Jv5mO>5ZQׁ$]""1l~Țg x+("KGkRޓngnYe8^\=|ӼOu
HPz
8ܸl-+5~_&r%(<Wy@oAaH\S`[B]#@d>5ਣRKZljjy RxOrEr$J(߯#nw;aL3r;
>vb]HNx&(',:{P,+h,k_2~}NJ~7rZ.y
𮧽ԱaHڇD=߷QoaEx?/& b-&_'u#G0r`Mz66~s:Vmzyy]×_uBr`*z=qlU}31e" 7,"pCCp0FAh{HN"5[V'qϒ2Qq0CvB8Wk4Wvqʒ]r۴=hrH u;o"~V@@[dG}CLĭ"c莬:=GNUv!:Ԯ
٥Zu h=
u@:5pK܋3 h\k"d}<@.n.tP"-e4N댃 0~*CȏpyED><w~Bl/r({Z^} Z,&tv:5uO3!oIUF%:I$yމ !tq]2z"aMsxXY0A='"De?3YP1D?gC;0kc }P,}j/_~nsK0[>%RQϦMqn
f)8RbQGD0vqD$B
,@:Yoݷ)Gaf5ڣf2dPпf#VYaQd1Pr`#RXAVR{PKe-8K %by_6oA`97XV-0k$X9b:DYP;`3v3Ӆ.
H'!ڞ?g<>jUaEpACZAN[lW 8q /E ;<p*={96JOE)草8?Nd;btDT$hM8
'@
ý+sÉ
T7EHWkڈ,h۳#Gԉu[}ߜm>?ȝ܊Uu\l[¼uZy:#+"xy`:@${1W'{Z qo"S.Pp,+p}";+0g)=GvP-B h{P5jŝc|O:~e4 J>2n I(ɉw`MjɿB'gWax!?pT [1fJZymU6`+Vr`gZբF:&T(,$u3wCqJN$C~.4ITٿz"r6r84 E.R!2f y}[T;Ɍ2${4H~T<*W@)/CY,"D$ɨ/"q_<ڮƺL~1bbub O+&,[xk
4uG4YТmk}}? -XV4e+Vڹfe5s[q#DYͲv~dNY2.Y,+hĠ'*O}ݟweZ<ܳ
"k|?kbЪ'L `'D +;Mx7:GP\mOA;.2/ϐ|6 P"S4H1MA}eKmf_2yn 㑓G vhk3r?A8цJEH} Sv}n";
Tw#'äW}e>XȔGtO-097or6EBzWr5.;3ܠO\ aH_qoiVWвqo&3
,1@ZCL:@d~x%C2,huk6t͟X̞w?jFDwlXE!e3v#dw4va:.\@c2zZubwe
h_h_0ΙGFiKo%-! пS>aq_t^-+Ai(<A9I*p&M "WB ^~d26VŁ])S<gm]6|`n]+
zg½'>DqT&QP :r{[-0I9F~}5o7
>yghMSv(Eؕi==FvS\l+%Wk5lX%22K~uSzP&7ZT ޔz "yF'I="!O{r%U
e\)Q tUQƄ2a(]e<8[3M}W2oBf
I0!jMٵ&'&cڧ|۳'/O7>ܶUY#9#(0t )L
N8G?N_P@-+@)A"
Q]Ȃ@PG*op;(J
BY U*dxf#%0g@XmT.PQ|h= GAe8^j?vOc!-VBx+S
1!)ecF §8eާ2
4Zè2w(pO ωzZ;BpT>rqW 1Qp:258e`;xHЛ576Q.Tp~{F)pp_J!Xw :p. O9w&X5AiU,>U0~dm'ֆWtL؋?g/^دwo-V6,!咎E+e{'VҾ`Y> Xj&rc8Y:f;仉`>Bb+p6$aqz~/ Dj ƥfoO0 EA>C$wx@FYؐ@f<曫uGR", m8]pjnڋ|f
8Mv?ƖvNާ\/:Y>9Kx~\SgP9]0rlKn8쁲0yY
Ğtu ӌ.M7܃6u93ĺMݮM%Bϫ{}k\)<.4h [O!:ؖ">^)upX]؇yq"?8ʹGt;:>Z~7sV se_nzw]k+ɂJP1fv7_;}:G
'w
F-cJ;Wcj)D}z[=MӚdREgd-%@A|(|%!@ї7nZ56,{.8%6wG$) DSD&L7Nf^ELv}ݏZHk|"u%JH%BH$"]eى%"p6Kq$:a
]=bXܵM]7R?eñȏ \} g]Qzn'ʽd*o?'[)d;@.PǃK#٧NS*m>EGƳ_/#M[óawx9W2:>[
<KSsJ|4G^d>D.OM $#@=boCFZ#DŽz/K.Γn5E}l6,+i?N=_g?UhI+zewV=aTM6?K#@w )2Db@]
zOȩXٕIK!w&۶fddJ&ruY#Ϡe!ܿOi !M(Pn,></@Aud@LD?GJK>XrA7F¨k2:JO%3P'_`\Gd^c _"egnk|5ťv$>hCwPn]i(9gtݫRciHF~ʌ]*^U|G)a?ſWRԹdaAUrM(c=ɢtkڮtS_:R;&;
Y
e]b8EF*4s YBW0(h'"w&4GT,N[>}kbeby};>:C;:¹aذE+ [Gҿ@Pzd
2-L˨Y5Ub
4~C$+)U/ J'@6P";Bͬe(p] I.d#NU|MSmWQ , H9/bLPI<sA6b
Ȃh92@!_0rB)(~9
*|]]
RFmĚzK+lru3<8y=u
OQYE1LƲ`pSލ9x~1Il"piFhQ?S<S)N:oBW*c=К>vMe @ν GO_nvlS)çʔs E';*\KNjQS p<7w|9"S!ܿee[ lyף}k1xh
6r*:'G?-./nXU AuZY)
_#/ڋ>AMgY=[>
",kKu<ww{qj8p<طΕܶ14~@D,,q$R~
Tmλ#wJg:12W>u#}c@)q 2o厪DD(*,BvA1bBF6FH)o/c&8d`53V"ApDvŸ;
\H!#z g:K"'c+h-˦~]F8acy
'"PeԧhxH=D<oTp畒:,ޗ|;*Y9L㜏)L^&m3 462MYx@sgElJyg
*(Tzxx8!HqZJC[Kz}`jG2 JF_wwcj:,ڱ\Ntwɞ#t вw-'Ucdt_N5ifׁe"v50ȑށh۳!8Aj55zA)I_MoTm])\A%W6Mvh3@Nuz%@v"D+VНh,]p?v|\*Hwⷷ9)ɂ*m{Yybo}66B,y`=s0Bb 9{E|ݓ!_uK.nKcǾK%;#on Ʊ|;RɢR}>wG:)/ݬ _>Sw8wW ڗyu>/MiWz;z{t;54P6(f{sꙥKDrܞ)Ż3dO""L/O$cD2uw8vGD$FwXz]
8m5{bݳGV5e?Wj_|on[Qs7ZQϔ.X~ۚ[qXМeY~ߑel{5Ee<0} , @a0t58j=t!+(v@OA1BёAIdC
f]Șgw`JϪv -S ^토"
ˣ |,X譊mZ<ceǟY/pdV-ڛ}Ys)et6"/
AuM-Y3v4n{<gM%6$fC&XڞJ8!UY$[TcYwGiJMoJFo&xV:۳XgẦfg/t&:@F7YQρW95A[sY\>*9Э1} 4Z<զ1>KSr
^L,PFL'"_5fA͐f<lVeX#-ݵ={;gS{``
eU=8N<ڴ<E{rtls>uc0@Qe @"d{PyE(PFJ#US PG
^xC<UX>_aX)NLĵ0Pd>ܞb tmWs#vpJH$lZp."b ˰x! hRЊ&oF>ց%KYͼ/YWGT-0-)oDVU* Q|zspC-=ehh=c4DIe^O9F\a>9m"=kiJ]#
õ9GB2 xΧ:
!5]^vawnZY]Ses-!XU+M"DLPKQp "A ""& |