repo_name
stringclasses
1 value
pr_number
int64
4.12k
11.2k
pr_title
stringlengths
9
107
pr_description
stringlengths
107
5.48k
author
stringlengths
4
18
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
118
5.52k
before_content
stringlengths
0
7.93M
after_content
stringlengths
0
7.93M
label
int64
-1
1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Problem 16: https://projecteuler.net/problem=16 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ def solution(power: int = 1000) -> int: """Returns the sum of the digits of the number 2^power. >>> solution(1000) 1366 >>> solution(50) 76 >>> solution(20) 31 >>> solution(15) 26 """ n = 2**power r = 0 while n: r, n = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
""" Problem 16: https://projecteuler.net/problem=16 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2^1000? """ def solution(power: int = 1000) -> int: """Returns the sum of the digits of the number 2^power. >>> solution(1000) 1366 >>> solution(50) 76 >>> solution(20) 31 >>> solution(15) 26 """ n = 2**power r = 0 while n: r, n = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
def stooge_sort(arr): """ Examples: >>> stooge_sort([18.1, 0, -7.1, -1, 2, 2]) [-7.1, -1, 0, 2, 2, 18.1] >>> stooge_sort([]) [] """ stooge(arr, 0, len(arr) - 1) return arr def stooge(arr, i, h): if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: arr[i], arr[h] = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: t = (int)((h - i + 1) / 3) # Recursively sort first 2/3 elements stooge(arr, i, (h - t)) # Recursively sort last 2/3 elements stooge(arr, i + t, (h)) # Recursively sort first 2/3 elements stooge(arr, i, (h - t)) if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(stooge_sort(unsorted))
def stooge_sort(arr): """ Examples: >>> stooge_sort([18.1, 0, -7.1, -1, 2, 2]) [-7.1, -1, 0, 2, 2, 18.1] >>> stooge_sort([]) [] """ stooge(arr, 0, len(arr) - 1) return arr def stooge(arr, i, h): if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: arr[i], arr[h] = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: t = (int)((h - i + 1) / 3) # Recursively sort first 2/3 elements stooge(arr, i, (h - t)) # Recursively sort last 2/3 elements stooge(arr, i + t, (h)) # Recursively sort first 2/3 elements stooge(arr, i, (h - t)) if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(stooge_sort(unsorted))
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Number letter counts Problem 17: https://projecteuler.net/problem=17 If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance withBritish usage. """ def solution(n: int = 1000) -> int: """Returns the number of letters used to write all numbers from 1 to n. where n is lower or equals to 1000. >>> solution(1000) 21124 >>> solution(5) 19 """ # number of letters in zero, one, two, ..., nineteen (0 for zero since it's # never said aloud) ones_counts = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8] # number of letters in twenty, thirty, ..., ninety (0 for numbers less than # 20 due to inconsistency in teens) tens_counts = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6] count = 0 for i in range(1, n + 1): if i < 1000: if i >= 100: # add number of letters for "n hundred" count += ones_counts[i // 100] + 7 if i % 100 != 0: # add number of letters for "and" if number is not multiple # of 100 count += 3 if 0 < i % 100 < 20: # add number of letters for one, two, three, ..., nineteen # (could be combined with below if not for inconsistency in # teens) count += ones_counts[i % 100] else: # add number of letters for twenty, twenty one, ..., ninety # nine count += ones_counts[i % 10] count += tens_counts[(i % 100 - i % 10) // 10] else: count += ones_counts[i // 1000] + 8 return count if __name__ == "__main__": print(solution(int(input().strip())))
""" Number letter counts Problem 17: https://projecteuler.net/problem=17 If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance withBritish usage. """ def solution(n: int = 1000) -> int: """Returns the number of letters used to write all numbers from 1 to n. where n is lower or equals to 1000. >>> solution(1000) 21124 >>> solution(5) 19 """ # number of letters in zero, one, two, ..., nineteen (0 for zero since it's # never said aloud) ones_counts = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8] # number of letters in twenty, thirty, ..., ninety (0 for numbers less than # 20 due to inconsistency in teens) tens_counts = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6] count = 0 for i in range(1, n + 1): if i < 1000: if i >= 100: # add number of letters for "n hundred" count += ones_counts[i // 100] + 7 if i % 100 != 0: # add number of letters for "and" if number is not multiple # of 100 count += 3 if 0 < i % 100 < 20: # add number of letters for one, two, three, ..., nineteen # (could be combined with below if not for inconsistency in # teens) count += ones_counts[i % 100] else: # add number of letters for twenty, twenty one, ..., ninety # nine count += ones_counts[i % 10] count += tens_counts[(i % 100 - i % 10) // 10] else: count += ones_counts[i // 1000] + 8 return count if __name__ == "__main__": print(solution(int(input().strip())))
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 187: https://projecteuler.net/problem=187 A composite is a number containing at least two prime factors. For example, 15 = 3 x 5; 9 = 3 x 3; 12 = 2 x 2 x 3. There are ten composites below thirty containing precisely two, not necessarily distinct, prime factors: 4, 6, 9, 10, 14, 15, 21, 22, 25, 26. How many composite integers, n < 10^8, have precisely two, not necessarily distinct, prime factors? """ from math import isqrt def calculate_prime_numbers(max_number: int) -> list[int]: """ Returns prime numbers below max_number >>> calculate_prime_numbers(10) [2, 3, 5, 7] """ is_prime = [True] * max_number for i in range(2, isqrt(max_number - 1) + 1): if is_prime[i]: for j in range(i**2, max_number, i): is_prime[j] = False return [i for i in range(2, max_number) if is_prime[i]] def solution(max_number: int = 10**8) -> int: """ Returns the number of composite integers below max_number have precisely two, not necessarily distinct, prime factors >>> solution(30) 10 """ prime_numbers = calculate_prime_numbers(max_number // 2) semiprimes_count = 0 left = 0 right = len(prime_numbers) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 187: https://projecteuler.net/problem=187 A composite is a number containing at least two prime factors. For example, 15 = 3 x 5; 9 = 3 x 3; 12 = 2 x 2 x 3. There are ten composites below thirty containing precisely two, not necessarily distinct, prime factors: 4, 6, 9, 10, 14, 15, 21, 22, 25, 26. How many composite integers, n < 10^8, have precisely two, not necessarily distinct, prime factors? """ from math import isqrt def calculate_prime_numbers(max_number: int) -> list[int]: """ Returns prime numbers below max_number >>> calculate_prime_numbers(10) [2, 3, 5, 7] """ is_prime = [True] * max_number for i in range(2, isqrt(max_number - 1) + 1): if is_prime[i]: for j in range(i**2, max_number, i): is_prime[j] = False return [i for i in range(2, max_number) if is_prime[i]] def solution(max_number: int = 10**8) -> int: """ Returns the number of composite integers below max_number have precisely two, not necessarily distinct, prime factors >>> solution(30) 10 """ prime_numbers = calculate_prime_numbers(max_number // 2) semiprimes_count = 0 left = 0 right = len(prime_numbers) - 1 while left <= right: while prime_numbers[left] * prime_numbers[right] >= max_number: right -= 1 semiprimes_count += right - left + 1 left += 1 return semiprimes_count if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Python3 program to evaluate a prefix expression. """ calc = { "+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y, "/": lambda x, y: x / y, } def is_operand(c): """ Return True if the given char c is an operand, e.g. it is a number >>> is_operand("1") True >>> is_operand("+") False """ return c.isdigit() def evaluate(expression): """ Evaluate a given expression in prefix notation. Asserts that the given expression is valid. >>> evaluate("+ 9 * 2 6") 21 >>> evaluate("/ * 10 2 + 4 1 ") 4.0 """ stack = [] # iterate over the string in reverse order for c in expression.split()[::-1]: # push operand to stack if is_operand(c): stack.append(int(c)) else: # pop values from stack can calculate the result # push the result onto the stack again o1 = stack.pop() o2 = stack.pop() stack.append(calc[c](o1, o2)) return stack.pop() # Driver code if __name__ == "__main__": test_expression = "+ 9 * 2 6" print(evaluate(test_expression)) test_expression = "/ * 10 2 + 4 1 " print(evaluate(test_expression))
""" Python3 program to evaluate a prefix expression. """ calc = { "+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y, "/": lambda x, y: x / y, } def is_operand(c): """ Return True if the given char c is an operand, e.g. it is a number >>> is_operand("1") True >>> is_operand("+") False """ return c.isdigit() def evaluate(expression): """ Evaluate a given expression in prefix notation. Asserts that the given expression is valid. >>> evaluate("+ 9 * 2 6") 21 >>> evaluate("/ * 10 2 + 4 1 ") 4.0 """ stack = [] # iterate over the string in reverse order for c in expression.split()[::-1]: # push operand to stack if is_operand(c): stack.append(int(c)) else: # pop values from stack can calculate the result # push the result onto the stack again o1 = stack.pop() o2 = stack.pop() stack.append(calc[c](o1, o2)) return stack.pop() # Driver code if __name__ == "__main__": test_expression = "+ 9 * 2 6" print(evaluate(test_expression)) test_expression = "/ * 10 2 + 4 1 " print(evaluate(test_expression))
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 104 : https://projecteuler.net/problem=104 The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. It turns out that F541, which contains 113 digits, is the first Fibonacci number for which the last nine digits are 1-9 pandigital (contain all the digits 1 to 9, but not necessarily in order). And F2749, which contains 575 digits, is the first Fibonacci number for which the first nine digits are 1-9 pandigital. Given that Fk is the first Fibonacci number for which the first nine digits AND the last nine digits are 1-9 pandigital, find k. """ import sys sys.set_int_max_str_digits(0) # type: ignore def check(number: int) -> bool: """ Takes a number and checks if it is pandigital both from start and end >>> check(123456789987654321) True >>> check(120000987654321) False >>> check(1234567895765677987654321) True """ check_last = [0] * 11 check_front = [0] * 11 # mark last 9 numbers for _ in range(9): check_last[int(number % 10)] = 1 number = number // 10 # flag f = True # check last 9 numbers for pandigitality for x in range(9): if not check_last[x + 1]: f = False if not f: return f # mark first 9 numbers number = int(str(number)[:9]) for _ in range(9): check_front[int(number % 10)] = 1 number = number // 10 # check first 9 numbers for pandigitality for x in range(9): if not check_front[x + 1]: f = False return f def check1(number: int) -> bool: """ Takes a number and checks if it is pandigital from END >>> check1(123456789987654321) True >>> check1(120000987654321) True >>> check1(12345678957656779870004321) False """ check_last = [0] * 11 # mark last 9 numbers for _ in range(9): check_last[int(number % 10)] = 1 number = number // 10 # flag f = True # check last 9 numbers for pandigitality for x in range(9): if not check_last[x + 1]: f = False return f def solution() -> int: """ Outputs the answer is the least Fibonacci number pandigital from both sides. >>> solution() 329468 """ a = 1 b = 1 c = 2 # temporary Fibonacci numbers a1 = 1 b1 = 1 c1 = 2 # temporary Fibonacci numbers mod 1e9 # mod m=1e9, done for fast optimisation tocheck = [0] * 1000000 m = 1000000000 for x in range(1000000): c1 = (a1 + b1) % m a1 = b1 % m b1 = c1 % m if check1(b1): tocheck[x + 3] = 1 for x in range(1000000): c = a + b a = b b = c # perform check only if in tocheck if tocheck[x + 3] and check(b): return x + 3 # first 2 already done return -1 if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 104 : https://projecteuler.net/problem=104 The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. It turns out that F541, which contains 113 digits, is the first Fibonacci number for which the last nine digits are 1-9 pandigital (contain all the digits 1 to 9, but not necessarily in order). And F2749, which contains 575 digits, is the first Fibonacci number for which the first nine digits are 1-9 pandigital. Given that Fk is the first Fibonacci number for which the first nine digits AND the last nine digits are 1-9 pandigital, find k. """ import sys sys.set_int_max_str_digits(0) # type: ignore def check(number: int) -> bool: """ Takes a number and checks if it is pandigital both from start and end >>> check(123456789987654321) True >>> check(120000987654321) False >>> check(1234567895765677987654321) True """ check_last = [0] * 11 check_front = [0] * 11 # mark last 9 numbers for _ in range(9): check_last[int(number % 10)] = 1 number = number // 10 # flag f = True # check last 9 numbers for pandigitality for x in range(9): if not check_last[x + 1]: f = False if not f: return f # mark first 9 numbers number = int(str(number)[:9]) for _ in range(9): check_front[int(number % 10)] = 1 number = number // 10 # check first 9 numbers for pandigitality for x in range(9): if not check_front[x + 1]: f = False return f def check1(number: int) -> bool: """ Takes a number and checks if it is pandigital from END >>> check1(123456789987654321) True >>> check1(120000987654321) True >>> check1(12345678957656779870004321) False """ check_last = [0] * 11 # mark last 9 numbers for _ in range(9): check_last[int(number % 10)] = 1 number = number // 10 # flag f = True # check last 9 numbers for pandigitality for x in range(9): if not check_last[x + 1]: f = False return f def solution() -> int: """ Outputs the answer is the least Fibonacci number pandigital from both sides. >>> solution() 329468 """ a = 1 b = 1 c = 2 # temporary Fibonacci numbers a1 = 1 b1 = 1 c1 = 2 # temporary Fibonacci numbers mod 1e9 # mod m=1e9, done for fast optimisation tocheck = [0] * 1000000 m = 1000000000 for x in range(1000000): c1 = (a1 + b1) % m a1 = b1 % m b1 = c1 % m if check1(b1): tocheck[x + 3] = 1 for x in range(1000000): c = a + b a = b b = c # perform check only if in tocheck if tocheck[x + 3] and check(b): return x + 3 # first 2 already done return -1 if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
import 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
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
#!/usr/bin/env python3 import os from collections.abc import Iterator def good_file_paths(top_dir: str = ".") -> Iterator[str]: for dir_path, dir_names, filenames in os.walk(top_dir): dir_names[:] = [d for d in dir_names if d != "scripts" and d[0] not in "._"] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(filename)[1] in (".py", ".ipynb"): yield os.path.join(dir_path, filename).lstrip("./") def md_prefix(i): return f"{i * ' '}*" if i else "\n##" def print_path(old_path: str, new_path: str) -> str: old_parts = old_path.split(os.sep) for i, new_part in enumerate(new_path.split(os.sep)): if (i + 1 > len(old_parts) or old_parts[i] != new_part) and new_part: print(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") return new_path def print_directory_md(top_dir: str = ".") -> None: old_path = "" for filepath in sorted(good_file_paths(top_dir)): filepath, filename = os.path.split(filepath) if filepath != old_path: old_path = print_path(old_path, filepath) indent = (filepath.count(os.sep) + 1) if filepath else 0 url = f"{filepath}/{filename}".replace(" ", "%20") filename = os.path.splitext(filename.replace("_", " ").title())[0] print(f"{md_prefix(indent)} [{filename}]({url})") if __name__ == "__main__": print_directory_md(".")
#!/usr/bin/env python3 import os from collections.abc import Iterator def good_file_paths(top_dir: str = ".") -> Iterator[str]: for dir_path, dir_names, filenames in os.walk(top_dir): dir_names[:] = [d for d in dir_names if d != "scripts" and d[0] not in "._"] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(filename)[1] in (".py", ".ipynb"): yield os.path.join(dir_path, filename).lstrip("./") def md_prefix(i): return f"{i * ' '}*" if i else "\n##" def print_path(old_path: str, new_path: str) -> str: old_parts = old_path.split(os.sep) for i, new_part in enumerate(new_path.split(os.sep)): if (i + 1 > len(old_parts) or old_parts[i] != new_part) and new_part: print(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") return new_path def print_directory_md(top_dir: str = ".") -> None: old_path = "" for filepath in sorted(good_file_paths(top_dir)): filepath, filename = os.path.split(filepath) if filepath != old_path: old_path = print_path(old_path, filepath) indent = (filepath.count(os.sep) + 1) if filepath else 0 url = f"{filepath}/{filename}".replace(" ", "%20") filename = os.path.splitext(filename.replace("_", " ").title())[0] print(f"{md_prefix(indent)} [{filename}]({url})") if __name__ == "__main__": print_directory_md(".")
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
"""Source: https://github.com/jason9075/opencv-mosaic-data-aug""" import glob import os import random from string import ascii_lowercase, digits import cv2 import numpy as np # Parrameters OUTPUT_SIZE = (720, 1280) # Height, Width SCALE_RANGE = (0.4, 0.6) # if height or width lower than this scale, drop it. FILTER_TINY_SCALE = 1 / 100 LABEL_DIR = "" IMG_DIR = "" OUTPUT_DIR = "" NUMBER_IMAGES = 250 def main() -> None: """ Get images list and annotations list from input dir. Update new images and annotations. Save images and annotations in output dir. """ img_paths, annos = get_dataset(LABEL_DIR, IMG_DIR) for index in range(NUMBER_IMAGES): idxs = random.sample(range(len(annos)), 4) new_image, new_annos, path = update_image_and_anno( img_paths, annos, idxs, OUTPUT_SIZE, SCALE_RANGE, filter_scale=FILTER_TINY_SCALE, ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' letter_code = random_chars(32) file_name = path.split(os.sep)[-1].rsplit(".", 1)[0] file_root = f"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}" cv2.imwrite(f"{file_root}.jpg", new_image, [cv2.IMWRITE_JPEG_QUALITY, 85]) print(f"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}") annos_list = [] for anno in new_annos: width = anno[3] - anno[1] height = anno[4] - anno[2] x_center = anno[1] + width / 2 y_center = anno[2] + height / 2 obj = f"{anno[0]} {x_center} {y_center} {width} {height}" annos_list.append(obj) with open(f"{file_root}.txt", "w") as outfile: outfile.write("\n".join(line for line in annos_list)) def get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]: """ - label_dir <type: str>: Path to label include annotation of images - img_dir <type: str>: Path to folder contain images Return <type: list>: List of images path and labels """ img_paths = [] labels = [] for label_file in glob.glob(os.path.join(label_dir, "*.txt")): label_name = label_file.split(os.sep)[-1].rsplit(".", 1)[0] with open(label_file) as in_file: obj_lists = in_file.readlines() img_path = os.path.join(img_dir, f"{label_name}.jpg") boxes = [] for obj_list in obj_lists: obj = obj_list.rstrip("\n").split(" ") xmin = float(obj[1]) - float(obj[3]) / 2 ymin = float(obj[2]) - float(obj[4]) / 2 xmax = float(obj[1]) + float(obj[3]) / 2 ymax = float(obj[2]) + float(obj[4]) / 2 boxes.append([int(obj[0]), xmin, ymin, xmax, ymax]) if not boxes: continue img_paths.append(img_path) labels.append(boxes) return img_paths, labels def update_image_and_anno( all_img_list: list, all_annos: list, idxs: list[int], output_size: tuple[int, int], scale_range: tuple[float, float], filter_scale: float = 0.0, ) -> tuple[list, list, str]: """ - all_img_list <type: list>: list of all images - all_annos <type: list>: list of all annotations of specific image - idxs <type: list>: index of image in list - output_size <type: tuple>: size of output image (Height, Width) - scale_range <type: tuple>: range of scale image - filter_scale <type: float>: the condition of downscale image and bounding box Return: - output_img <type: narray>: image after resize - new_anno <type: list>: list of new annotation after scale - path[0] <type: string>: get the name of image file """ output_img = np.zeros([output_size[0], output_size[1], 3], dtype=np.uint8) scale_x = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) scale_y = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) divid_point_x = int(scale_x * output_size[1]) divid_point_y = int(scale_y * output_size[0]) new_anno = [] path_list = [] for i, index in enumerate(idxs): path = all_img_list[index] path_list.append(path) img_annos = all_annos[index] img = cv2.imread(path) if i == 0: # top-left img = cv2.resize(img, (divid_point_x, divid_point_y)) output_img[:divid_point_y, :divid_point_x, :] = img for bbox in img_annos: xmin = bbox[1] * scale_x ymin = bbox[2] * scale_y xmax = bbox[3] * scale_x ymax = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) elif i == 1: # top-right img = cv2.resize(img, (output_size[1] - divid_point_x, divid_point_y)) output_img[:divid_point_y, divid_point_x : output_size[1], :] = img for bbox in img_annos: xmin = scale_x + bbox[1] * (1 - scale_x) ymin = bbox[2] * scale_y xmax = scale_x + bbox[3] * (1 - scale_x) ymax = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) elif i == 2: # bottom-left img = cv2.resize(img, (divid_point_x, output_size[0] - divid_point_y)) output_img[divid_point_y : output_size[0], :divid_point_x, :] = img for bbox in img_annos: xmin = bbox[1] * scale_x ymin = scale_y + bbox[2] * (1 - scale_y) xmax = bbox[3] * scale_x ymax = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) else: # bottom-right img = cv2.resize( img, (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) output_img[ divid_point_y : output_size[0], divid_point_x : output_size[1], : ] = img for bbox in img_annos: xmin = scale_x + bbox[1] * (1 - scale_x) ymin = scale_y + bbox[2] * (1 - scale_y) xmax = scale_x + bbox[3] * (1 - scale_x) ymax = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) # Remove bounding box small than scale of filter if filter_scale > 0: new_anno = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def random_chars(number_char: int) -> str: """ Automatic generate random 32 characters. Get random string code: '7b7ad245cdff75241935e4dd860f3bad' >>> len(random_chars(32)) 32 """ assert number_char > 1, "The number of character should greater than 1" letter_code = ascii_lowercase + digits return "".join(random.choice(letter_code) for _ in range(number_char)) if __name__ == "__main__": main() print("DONE ✅")
"""Source: https://github.com/jason9075/opencv-mosaic-data-aug""" import glob import os import random from string import ascii_lowercase, digits import cv2 import numpy as np # Parrameters OUTPUT_SIZE = (720, 1280) # Height, Width SCALE_RANGE = (0.4, 0.6) # if height or width lower than this scale, drop it. FILTER_TINY_SCALE = 1 / 100 LABEL_DIR = "" IMG_DIR = "" OUTPUT_DIR = "" NUMBER_IMAGES = 250 def main() -> None: """ Get images list and annotations list from input dir. Update new images and annotations. Save images and annotations in output dir. """ img_paths, annos = get_dataset(LABEL_DIR, IMG_DIR) for index in range(NUMBER_IMAGES): idxs = random.sample(range(len(annos)), 4) new_image, new_annos, path = update_image_and_anno( img_paths, annos, idxs, OUTPUT_SIZE, SCALE_RANGE, filter_scale=FILTER_TINY_SCALE, ) # Get random string code: '7b7ad245cdff75241935e4dd860f3bad' letter_code = random_chars(32) file_name = path.split(os.sep)[-1].rsplit(".", 1)[0] file_root = f"{OUTPUT_DIR}/{file_name}_MOSAIC_{letter_code}" cv2.imwrite(f"{file_root}.jpg", new_image, [cv2.IMWRITE_JPEG_QUALITY, 85]) print(f"Succeeded {index+1}/{NUMBER_IMAGES} with {file_name}") annos_list = [] for anno in new_annos: width = anno[3] - anno[1] height = anno[4] - anno[2] x_center = anno[1] + width / 2 y_center = anno[2] + height / 2 obj = f"{anno[0]} {x_center} {y_center} {width} {height}" annos_list.append(obj) with open(f"{file_root}.txt", "w") as outfile: outfile.write("\n".join(line for line in annos_list)) def get_dataset(label_dir: str, img_dir: str) -> tuple[list, list]: """ - label_dir <type: str>: Path to label include annotation of images - img_dir <type: str>: Path to folder contain images Return <type: list>: List of images path and labels """ img_paths = [] labels = [] for label_file in glob.glob(os.path.join(label_dir, "*.txt")): label_name = label_file.split(os.sep)[-1].rsplit(".", 1)[0] with open(label_file) as in_file: obj_lists = in_file.readlines() img_path = os.path.join(img_dir, f"{label_name}.jpg") boxes = [] for obj_list in obj_lists: obj = obj_list.rstrip("\n").split(" ") xmin = float(obj[1]) - float(obj[3]) / 2 ymin = float(obj[2]) - float(obj[4]) / 2 xmax = float(obj[1]) + float(obj[3]) / 2 ymax = float(obj[2]) + float(obj[4]) / 2 boxes.append([int(obj[0]), xmin, ymin, xmax, ymax]) if not boxes: continue img_paths.append(img_path) labels.append(boxes) return img_paths, labels def update_image_and_anno( all_img_list: list, all_annos: list, idxs: list[int], output_size: tuple[int, int], scale_range: tuple[float, float], filter_scale: float = 0.0, ) -> tuple[list, list, str]: """ - all_img_list <type: list>: list of all images - all_annos <type: list>: list of all annotations of specific image - idxs <type: list>: index of image in list - output_size <type: tuple>: size of output image (Height, Width) - scale_range <type: tuple>: range of scale image - filter_scale <type: float>: the condition of downscale image and bounding box Return: - output_img <type: narray>: image after resize - new_anno <type: list>: list of new annotation after scale - path[0] <type: string>: get the name of image file """ output_img = np.zeros([output_size[0], output_size[1], 3], dtype=np.uint8) scale_x = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) scale_y = scale_range[0] + random.random() * (scale_range[1] - scale_range[0]) divid_point_x = int(scale_x * output_size[1]) divid_point_y = int(scale_y * output_size[0]) new_anno = [] path_list = [] for i, index in enumerate(idxs): path = all_img_list[index] path_list.append(path) img_annos = all_annos[index] img = cv2.imread(path) if i == 0: # top-left img = cv2.resize(img, (divid_point_x, divid_point_y)) output_img[:divid_point_y, :divid_point_x, :] = img for bbox in img_annos: xmin = bbox[1] * scale_x ymin = bbox[2] * scale_y xmax = bbox[3] * scale_x ymax = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) elif i == 1: # top-right img = cv2.resize(img, (output_size[1] - divid_point_x, divid_point_y)) output_img[:divid_point_y, divid_point_x : output_size[1], :] = img for bbox in img_annos: xmin = scale_x + bbox[1] * (1 - scale_x) ymin = bbox[2] * scale_y xmax = scale_x + bbox[3] * (1 - scale_x) ymax = bbox[4] * scale_y new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) elif i == 2: # bottom-left img = cv2.resize(img, (divid_point_x, output_size[0] - divid_point_y)) output_img[divid_point_y : output_size[0], :divid_point_x, :] = img for bbox in img_annos: xmin = bbox[1] * scale_x ymin = scale_y + bbox[2] * (1 - scale_y) xmax = bbox[3] * scale_x ymax = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) else: # bottom-right img = cv2.resize( img, (output_size[1] - divid_point_x, output_size[0] - divid_point_y) ) output_img[ divid_point_y : output_size[0], divid_point_x : output_size[1], : ] = img for bbox in img_annos: xmin = scale_x + bbox[1] * (1 - scale_x) ymin = scale_y + bbox[2] * (1 - scale_y) xmax = scale_x + bbox[3] * (1 - scale_x) ymax = scale_y + bbox[4] * (1 - scale_y) new_anno.append([bbox[0], xmin, ymin, xmax, ymax]) # Remove bounding box small than scale of filter if filter_scale > 0: new_anno = [ anno for anno in new_anno if filter_scale < (anno[3] - anno[1]) and filter_scale < (anno[4] - anno[2]) ] return output_img, new_anno, path_list[0] def random_chars(number_char: int) -> str: """ Automatic generate random 32 characters. Get random string code: '7b7ad245cdff75241935e4dd860f3bad' >>> len(random_chars(32)) 32 """ assert number_char > 1, "The number of character should greater than 1" letter_code = ascii_lowercase + digits return "".join(random.choice(letter_code) for _ in range(number_char)) if __name__ == "__main__": main() print("DONE ✅")
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" A NAND Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are 1, and 1 (True) otherwise. It's similar to adding a NOT gate along with an AND gate. Following is the truth table of a NAND Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 1 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 0 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def nand_gate(input_1: int, input_2: int) -> int: """ Calculate NAND of the input values >>> nand_gate(0, 0) 1 >>> nand_gate(0, 1) 1 >>> nand_gate(1, 0) 1 >>> nand_gate(1, 1) 0 """ return int((input_1, input_2).count(0) != 0) def test_nand_gate() -> None: """ Tests the nand_gate function """ assert nand_gate(0, 0) == 1 assert nand_gate(0, 1) == 1 assert nand_gate(1, 0) == 1 assert nand_gate(1, 1) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
""" A NAND Gate is a logic gate in boolean algebra which results to 0 (False) if both the inputs are 1, and 1 (True) otherwise. It's similar to adding a NOT gate along with an AND gate. Following is the truth table of a NAND Gate: ------------------------------ | Input 1 | Input 2 | Output | ------------------------------ | 0 | 0 | 1 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 0 | ------------------------------ Refer - https://www.geeksforgeeks.org/logic-gates-in-python/ """ def nand_gate(input_1: int, input_2: int) -> int: """ Calculate NAND of the input values >>> nand_gate(0, 0) 1 >>> nand_gate(0, 1) 1 >>> nand_gate(1, 0) 1 >>> nand_gate(1, 1) 0 """ return int((input_1, input_2).count(0) != 0) def test_nand_gate() -> None: """ Tests the nand_gate function """ assert nand_gate(0, 0) == 1 assert nand_gate(0, 1) == 1 assert nand_gate(1, 0) == 1 assert nand_gate(1, 1) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# Created by sarathkaul on 17/11/19 # Modified by Arkadip Bhattacharya(@darkmatter18) on 20/04/2020 from collections import defaultdict def word_occurrence(sentence: str) -> dict: """ >>> from collections import Counter >>> SENTENCE = "a b A b c b d b d e f e g e h e i e j e 0" >>> occurence_dict = word_occurrence(SENTENCE) >>> all(occurence_dict[word] == count for word, count ... in Counter(SENTENCE.split()).items()) True >>> dict(word_occurrence("Two spaces")) {'Two': 1, 'spaces': 1} """ occurrence: defaultdict[str, int] = defaultdict(int) # Creating a dictionary containing count of each word for word in sentence.split(): occurrence[word] += 1 return occurrence if __name__ == "__main__": for word, count in word_occurrence("INPUT STRING").items(): print(f"{word}: {count}")
# Created by sarathkaul on 17/11/19 # Modified by Arkadip Bhattacharya(@darkmatter18) on 20/04/2020 from collections import defaultdict def word_occurrence(sentence: str) -> dict: """ >>> from collections import Counter >>> SENTENCE = "a b A b c b d b d e f e g e h e i e j e 0" >>> occurence_dict = word_occurrence(SENTENCE) >>> all(occurence_dict[word] == count for word, count ... in Counter(SENTENCE.split()).items()) True >>> dict(word_occurrence("Two spaces")) {'Two': 1, 'spaces': 1} """ occurrence: defaultdict[str, int] = defaultdict(int) # Creating a dictionary containing count of each word for word in sentence.split(): occurrence[word] += 1 return occurrence if __name__ == "__main__": for word, count in word_occurrence("INPUT STRING").items(): print(f"{word}: {count}")
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from __future__ import annotations from random import random class Node: """ Treap's node Treap is a binary tree by value and heap by priority """ def __init__(self, value: int | None = None): self.value = value self.prior = random() self.left: Node | None = None self.right: Node | None = None def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return f"'{self.value}: {self.prior:.5}'" else: return pformat( {f"{self.value}: {self.prior:.5}": (self.left, self.right)}, indent=1 ) def __str__(self) -> str: value = str(self.value) + " " left = str(self.left or "") right = str(self.right or "") return value + left + right def split(root: Node | None, value: int) -> tuple[Node | None, Node | None]: """ We split current tree into 2 trees with value: Left tree contains all values less than split value. Right tree contains all values greater or equal, than split value """ if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: """ Right tree's root will be current node. Now we split(with the same value) current node's left son Left tree: left part of that split Right tree's left son: right part of that split """ left, root.left = split(root.left, value) return left, root else: """ Just symmetric to previous case """ root.right, right = split(root.right, value) return root, right def merge(left: Node | None, right: Node | None) -> Node | None: """ We merge 2 trees into one. Note: all left tree's values must be less than all right tree's """ if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: """ Left will be root because it has more priority Now we need to merge left's right son and right tree """ left.right = merge(left.right, right) return left else: """ Symmetric as well """ right.left = merge(left, right.left) return right def insert(root: Node | None, value: int) -> Node | None: """ Insert element Split current tree with a value into left, right, Insert new node into the middle Merge left, node, right into root """ node = Node(value) left, right = split(root, value) return merge(merge(left, node), right) def erase(root: Node | None, value: int) -> Node | None: """ Erase element Split all nodes with values less into left, Split all nodes with values greater into right. Merge left, right """ left, right = split(root, value - 1) _, right = split(right, value) return merge(left, right) def inorder(root: Node | None) -> None: """ Just recursive print of a tree """ if not root: # None return else: inorder(root.left) print(root.value, end=",") inorder(root.right) def interact_treap(root: Node | None, args: str) -> Node | None: """ Commands: + value to add value into treap - value to erase all nodes with value >>> root = interact_treap(None, "+1") >>> inorder(root) 1, >>> root = interact_treap(root, "+3 +5 +17 +19 +2 +16 +4 +0") >>> inorder(root) 0,1,2,3,4,5,16,17,19, >>> root = interact_treap(root, "+4 +4 +4") >>> inorder(root) 0,1,2,3,4,4,4,4,5,16,17,19, >>> root = interact_treap(root, "-0") >>> inorder(root) 1,2,3,4,4,4,4,5,16,17,19, >>> root = interact_treap(root, "-4") >>> inorder(root) 1,2,3,5,16,17,19, >>> root = interact_treap(root, "=0") Unknown command """ for arg in args.split(): if arg[0] == "+": root = insert(root, int(arg[1:])) elif arg[0] == "-": root = erase(root, int(arg[1:])) else: print("Unknown command") return root def main() -> None: """After each command, program prints treap""" root = None print( "enter numbers to create a tree, + value to add value into treap, " "- value to erase all nodes with value. 'q' to quit. " ) args = input() while args != "q": root = interact_treap(root, args) print(root) args = input() print("good by!") if __name__ == "__main__": import doctest doctest.testmod() main()
from __future__ import annotations from random import random class Node: """ Treap's node Treap is a binary tree by value and heap by priority """ def __init__(self, value: int | None = None): self.value = value self.prior = random() self.left: Node | None = None self.right: Node | None = None def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return f"'{self.value}: {self.prior:.5}'" else: return pformat( {f"{self.value}: {self.prior:.5}": (self.left, self.right)}, indent=1 ) def __str__(self) -> str: value = str(self.value) + " " left = str(self.left or "") right = str(self.right or "") return value + left + right def split(root: Node | None, value: int) -> tuple[Node | None, Node | None]: """ We split current tree into 2 trees with value: Left tree contains all values less than split value. Right tree contains all values greater or equal, than split value """ if root is None: # None tree is split into 2 Nones return None, None elif root.value is None: return None, None else: if value < root.value: """ Right tree's root will be current node. Now we split(with the same value) current node's left son Left tree: left part of that split Right tree's left son: right part of that split """ left, root.left = split(root.left, value) return left, root else: """ Just symmetric to previous case """ root.right, right = split(root.right, value) return root, right def merge(left: Node | None, right: Node | None) -> Node | None: """ We merge 2 trees into one. Note: all left tree's values must be less than all right tree's """ if (not left) or (not right): # If one node is None, return the other return left or right elif left.prior < right.prior: """ Left will be root because it has more priority Now we need to merge left's right son and right tree """ left.right = merge(left.right, right) return left else: """ Symmetric as well """ right.left = merge(left, right.left) return right def insert(root: Node | None, value: int) -> Node | None: """ Insert element Split current tree with a value into left, right, Insert new node into the middle Merge left, node, right into root """ node = Node(value) left, right = split(root, value) return merge(merge(left, node), right) def erase(root: Node | None, value: int) -> Node | None: """ Erase element Split all nodes with values less into left, Split all nodes with values greater into right. Merge left, right """ left, right = split(root, value - 1) _, right = split(right, value) return merge(left, right) def inorder(root: Node | None) -> None: """ Just recursive print of a tree """ if not root: # None return else: inorder(root.left) print(root.value, end=",") inorder(root.right) def interact_treap(root: Node | None, args: str) -> Node | None: """ Commands: + value to add value into treap - value to erase all nodes with value >>> root = interact_treap(None, "+1") >>> inorder(root) 1, >>> root = interact_treap(root, "+3 +5 +17 +19 +2 +16 +4 +0") >>> inorder(root) 0,1,2,3,4,5,16,17,19, >>> root = interact_treap(root, "+4 +4 +4") >>> inorder(root) 0,1,2,3,4,4,4,4,5,16,17,19, >>> root = interact_treap(root, "-0") >>> inorder(root) 1,2,3,4,4,4,4,5,16,17,19, >>> root = interact_treap(root, "-4") >>> inorder(root) 1,2,3,5,16,17,19, >>> root = interact_treap(root, "=0") Unknown command """ for arg in args.split(): if arg[0] == "+": root = insert(root, int(arg[1:])) elif arg[0] == "-": root = erase(root, int(arg[1:])) else: print("Unknown command") return root def main() -> None: """After each command, program prints treap""" root = None print( "enter numbers to create a tree, + value to add value into treap, " "- value to erase all nodes with value. 'q' to quit. " ) args = input() while args != "q": root = interact_treap(root, args) print(root) args = input() print("good by!") if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Python implementation of the MSD radix sort algorithm. It used the binary representation of the integers to sort them. https://en.wikipedia.org/wiki/Radix_sort """ from __future__ import annotations def msd_radix_sort(list_of_ints: list[int]) -> list[int]: """ Implementation of the MSD radix sort algorithm. Only works with positive integers :param list_of_ints: A list of integers :return: Returns the sorted list >>> msd_radix_sort([40, 12, 1, 100, 4]) [1, 4, 12, 40, 100] >>> msd_radix_sort([]) [] >>> msd_radix_sort([123, 345, 123, 80]) [80, 123, 123, 345] >>> msd_radix_sort([1209, 834598, 1, 540402, 45]) [1, 45, 1209, 540402, 834598] >>> msd_radix_sort([-1, 34, 45]) Traceback (most recent call last): ... ValueError: All numbers must be positive """ if not list_of_ints: return [] if min(list_of_ints) < 0: raise ValueError("All numbers must be positive") most_bits = max(len(bin(x)[2:]) for x in list_of_ints) return _msd_radix_sort(list_of_ints, most_bits) def _msd_radix_sort(list_of_ints: list[int], bit_position: int) -> list[int]: """ Sort the given list based on the bit at bit_position. Numbers with a 0 at that position will be at the start of the list, numbers with a 1 at the end. :param list_of_ints: A list of integers :param bit_position: the position of the bit that gets compared :return: Returns a partially sorted list >>> _msd_radix_sort([45, 2, 32], 1) [2, 32, 45] >>> _msd_radix_sort([10, 4, 12], 2) [4, 12, 10] """ if bit_position == 0 or len(list_of_ints) in [0, 1]: return list_of_ints zeros = [] ones = [] # Split numbers based on bit at bit_position from the right for number in list_of_ints: if (number >> (bit_position - 1)) & 1: # number has a one at bit bit_position ones.append(number) else: # number has a zero at bit bit_position zeros.append(number) # recursively split both lists further zeros = _msd_radix_sort(zeros, bit_position - 1) ones = _msd_radix_sort(ones, bit_position - 1) # recombine lists res = zeros res.extend(ones) return res def msd_radix_sort_inplace(list_of_ints: list[int]): """ Inplace implementation of the MSD radix sort algorithm. Sorts based on the binary representation of the integers. >>> lst = [1, 345, 23, 89, 0, 3] >>> msd_radix_sort_inplace(lst) >>> lst == sorted(lst) True >>> lst = [1, 43, 0, 0, 0, 24, 3, 3] >>> msd_radix_sort_inplace(lst) >>> lst == sorted(lst) True >>> lst = [] >>> msd_radix_sort_inplace(lst) >>> lst == [] True >>> lst = [-1, 34, 23, 4, -42] >>> msd_radix_sort_inplace(lst) Traceback (most recent call last): ... ValueError: All numbers must be positive """ length = len(list_of_ints) if not list_of_ints or length == 1: return if min(list_of_ints) < 0: raise ValueError("All numbers must be positive") most_bits = max(len(bin(x)[2:]) for x in list_of_ints) _msd_radix_sort_inplace(list_of_ints, most_bits, 0, length) def _msd_radix_sort_inplace( list_of_ints: list[int], bit_position: int, begin_index: int, end_index: int ): """ Sort the given list based on the bit at bit_position. Numbers with a 0 at that position will be at the start of the list, numbers with a 1 at the end. >>> lst = [45, 2, 32, 24, 534, 2932] >>> _msd_radix_sort_inplace(lst, 1, 0, 3) >>> lst == [32, 2, 45, 24, 534, 2932] True >>> lst = [0, 2, 1, 3, 12, 10, 4, 90, 54, 2323, 756] >>> _msd_radix_sort_inplace(lst, 2, 4, 7) >>> lst == [0, 2, 1, 3, 12, 4, 10, 90, 54, 2323, 756] True """ if bit_position == 0 or end_index - begin_index <= 1: return bit_position -= 1 i = begin_index j = end_index - 1 while i <= j: changed = False if not (list_of_ints[i] >> bit_position) & 1: # found zero at the beginning i += 1 changed = True if (list_of_ints[j] >> bit_position) & 1: # found one at the end j -= 1 changed = True if changed: continue list_of_ints[i], list_of_ints[j] = list_of_ints[j], list_of_ints[i] j -= 1 if j != i: i += 1 _msd_radix_sort_inplace(list_of_ints, bit_position, begin_index, i) _msd_radix_sort_inplace(list_of_ints, bit_position, i, end_index) if __name__ == "__main__": import doctest doctest.testmod()
""" Python implementation of the MSD radix sort algorithm. It used the binary representation of the integers to sort them. https://en.wikipedia.org/wiki/Radix_sort """ from __future__ import annotations def msd_radix_sort(list_of_ints: list[int]) -> list[int]: """ Implementation of the MSD radix sort algorithm. Only works with positive integers :param list_of_ints: A list of integers :return: Returns the sorted list >>> msd_radix_sort([40, 12, 1, 100, 4]) [1, 4, 12, 40, 100] >>> msd_radix_sort([]) [] >>> msd_radix_sort([123, 345, 123, 80]) [80, 123, 123, 345] >>> msd_radix_sort([1209, 834598, 1, 540402, 45]) [1, 45, 1209, 540402, 834598] >>> msd_radix_sort([-1, 34, 45]) Traceback (most recent call last): ... ValueError: All numbers must be positive """ if not list_of_ints: return [] if min(list_of_ints) < 0: raise ValueError("All numbers must be positive") most_bits = max(len(bin(x)[2:]) for x in list_of_ints) return _msd_radix_sort(list_of_ints, most_bits) def _msd_radix_sort(list_of_ints: list[int], bit_position: int) -> list[int]: """ Sort the given list based on the bit at bit_position. Numbers with a 0 at that position will be at the start of the list, numbers with a 1 at the end. :param list_of_ints: A list of integers :param bit_position: the position of the bit that gets compared :return: Returns a partially sorted list >>> _msd_radix_sort([45, 2, 32], 1) [2, 32, 45] >>> _msd_radix_sort([10, 4, 12], 2) [4, 12, 10] """ if bit_position == 0 or len(list_of_ints) in [0, 1]: return list_of_ints zeros = [] ones = [] # Split numbers based on bit at bit_position from the right for number in list_of_ints: if (number >> (bit_position - 1)) & 1: # number has a one at bit bit_position ones.append(number) else: # number has a zero at bit bit_position zeros.append(number) # recursively split both lists further zeros = _msd_radix_sort(zeros, bit_position - 1) ones = _msd_radix_sort(ones, bit_position - 1) # recombine lists res = zeros res.extend(ones) return res def msd_radix_sort_inplace(list_of_ints: list[int]): """ Inplace implementation of the MSD radix sort algorithm. Sorts based on the binary representation of the integers. >>> lst = [1, 345, 23, 89, 0, 3] >>> msd_radix_sort_inplace(lst) >>> lst == sorted(lst) True >>> lst = [1, 43, 0, 0, 0, 24, 3, 3] >>> msd_radix_sort_inplace(lst) >>> lst == sorted(lst) True >>> lst = [] >>> msd_radix_sort_inplace(lst) >>> lst == [] True >>> lst = [-1, 34, 23, 4, -42] >>> msd_radix_sort_inplace(lst) Traceback (most recent call last): ... ValueError: All numbers must be positive """ length = len(list_of_ints) if not list_of_ints or length == 1: return if min(list_of_ints) < 0: raise ValueError("All numbers must be positive") most_bits = max(len(bin(x)[2:]) for x in list_of_ints) _msd_radix_sort_inplace(list_of_ints, most_bits, 0, length) def _msd_radix_sort_inplace( list_of_ints: list[int], bit_position: int, begin_index: int, end_index: int ): """ Sort the given list based on the bit at bit_position. Numbers with a 0 at that position will be at the start of the list, numbers with a 1 at the end. >>> lst = [45, 2, 32, 24, 534, 2932] >>> _msd_radix_sort_inplace(lst, 1, 0, 3) >>> lst == [32, 2, 45, 24, 534, 2932] True >>> lst = [0, 2, 1, 3, 12, 10, 4, 90, 54, 2323, 756] >>> _msd_radix_sort_inplace(lst, 2, 4, 7) >>> lst == [0, 2, 1, 3, 12, 4, 10, 90, 54, 2323, 756] True """ if bit_position == 0 or end_index - begin_index <= 1: return bit_position -= 1 i = begin_index j = end_index - 1 while i <= j: changed = False if not (list_of_ints[i] >> bit_position) & 1: # found zero at the beginning i += 1 changed = True if (list_of_ints[j] >> bit_position) & 1: # found one at the end j -= 1 changed = True if changed: continue list_of_ints[i], list_of_ints[j] = list_of_ints[j], list_of_ints[i] j -= 1 if j != i: i += 1 _msd_radix_sort_inplace(list_of_ints, bit_position, begin_index, i) _msd_radix_sort_inplace(list_of_ints, bit_position, i, end_index) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from doctest import testmod from math import sqrt def factors_of_a_number(num: int) -> list: """ >>> factors_of_a_number(1) [1] >>> factors_of_a_number(5) [1, 5] >>> factors_of_a_number(24) [1, 2, 3, 4, 6, 8, 12, 24] >>> factors_of_a_number(-24) [] """ facs: list[int] = [] if num < 1: return facs facs.append(1) if num == 1: return facs facs.append(num) for i in range(2, int(sqrt(num)) + 1): if num % i == 0: # If i is a factor of num facs.append(i) d = num // i # num//i is the other factor of num if d != i: # If d and i are distinct facs.append(d) # we have found another factor facs.sort() return facs if __name__ == "__main__": testmod(name="factors_of_a_number", verbose=True)
from doctest import testmod from math import sqrt def factors_of_a_number(num: int) -> list: """ >>> factors_of_a_number(1) [1] >>> factors_of_a_number(5) [1, 5] >>> factors_of_a_number(24) [1, 2, 3, 4, 6, 8, 12, 24] >>> factors_of_a_number(-24) [] """ facs: list[int] = [] if num < 1: return facs facs.append(1) if num == 1: return facs facs.append(num) for i in range(2, int(sqrt(num)) + 1): if num % i == 0: # If i is a factor of num facs.append(i) d = num // i # num//i is the other factor of num if d != i: # If d and i are distinct facs.append(d) # we have found another factor facs.sort() return facs if __name__ == "__main__": testmod(name="factors_of_a_number", verbose=True)
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
"""Implementation of GradientBoostingRegressor in sklearn using the boston dataset which is very popular for regression problem to predict house price. """ import matplotlib.pyplot as plt import pandas as pd from sklearn.datasets import load_boston from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split def main(): # loading the dataset from the sklearn df = load_boston() print(df.keys()) # now let construct a data frame df_boston = pd.DataFrame(df.data, columns=df.feature_names) # let add the target to the dataframe df_boston["Price"] = df.target # print the first five rows using the head function print(df_boston.head()) # Summary statistics print(df_boston.describe().T) # Feature selection x = df_boston.iloc[:, :-1] y = df_boston.iloc[:, -1] # target variable # split the data with 75% train and 25% test sets. x_train, x_test, y_train, y_test = train_test_split( x, y, random_state=0, test_size=0.25 ) model = GradientBoostingRegressor( n_estimators=500, max_depth=5, min_samples_split=4, learning_rate=0.01 ) # training the model model.fit(x_train, y_train) # to see how good the model fit the data training_score = model.score(x_train, y_train).round(3) test_score = model.score(x_test, y_test).round(3) print("Training score of GradientBoosting is :", training_score) print("The test score of GradientBoosting is :", test_score) # Let us evaluation the model by finding the errors y_pred = model.predict(x_test) # The mean squared error print(f"Mean squared error: {mean_squared_error(y_test, y_pred):.2f}") # Explained variance score: 1 is perfect prediction print(f"Test Variance score: {r2_score(y_test, y_pred):.2f}") # So let's run the model against the test data fig, ax = plt.subplots() ax.scatter(y_test, y_pred, edgecolors=(0, 0, 0)) ax.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], "k--", lw=4) ax.set_xlabel("Actual") ax.set_ylabel("Predicted") ax.set_title("Truth vs Predicted") # this show function will display the plotting plt.show() if __name__ == "__main__": main()
"""Implementation of GradientBoostingRegressor in sklearn using the boston dataset which is very popular for regression problem to predict house price. """ import matplotlib.pyplot as plt import pandas as pd from sklearn.datasets import load_boston from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import train_test_split def main(): # loading the dataset from the sklearn df = load_boston() print(df.keys()) # now let construct a data frame df_boston = pd.DataFrame(df.data, columns=df.feature_names) # let add the target to the dataframe df_boston["Price"] = df.target # print the first five rows using the head function print(df_boston.head()) # Summary statistics print(df_boston.describe().T) # Feature selection x = df_boston.iloc[:, :-1] y = df_boston.iloc[:, -1] # target variable # split the data with 75% train and 25% test sets. x_train, x_test, y_train, y_test = train_test_split( x, y, random_state=0, test_size=0.25 ) model = GradientBoostingRegressor( n_estimators=500, max_depth=5, min_samples_split=4, learning_rate=0.01 ) # training the model model.fit(x_train, y_train) # to see how good the model fit the data training_score = model.score(x_train, y_train).round(3) test_score = model.score(x_test, y_test).round(3) print("Training score of GradientBoosting is :", training_score) print("The test score of GradientBoosting is :", test_score) # Let us evaluation the model by finding the errors y_pred = model.predict(x_test) # The mean squared error print(f"Mean squared error: {mean_squared_error(y_test, y_pred):.2f}") # Explained variance score: 1 is perfect prediction print(f"Test Variance score: {r2_score(y_test, y_pred):.2f}") # So let's run the model against the test data fig, ax = plt.subplots() ax.scatter(y_test, y_pred, edgecolors=(0, 0, 0)) ax.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], "k--", lw=4) ax.set_xlabel("Actual") ax.set_ylabel("Predicted") ax.set_title("Truth vs Predicted") # this show function will display the plotting plt.show() if __name__ == "__main__": main()
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Finding the peak of a unimodal list using divide and conquer. A unimodal array is defined as follows: array is increasing up to index p, then decreasing afterwards. (for p >= 1) An obvious solution can be performed in O(n), to find the maximum of the array. (From Kleinberg and Tardos. Algorithm Design. Addison Wesley 2006: Chapter 5 Solved Exercise 1) """ from __future__ import annotations def peak(lst: list[int]) -> int: """ Return the peak value of `lst`. >>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1]) 5 >>> peak([1, 10, 9, 8, 7, 6, 5, 4]) 10 >>> peak([1, 9, 8, 7]) 9 >>> peak([1, 2, 3, 4, 5, 6, 7, 0]) 7 >>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2]) 4 """ # middle index m = len(lst) // 2 # choose the middle 3 elements three = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m]) == 2: m -= 1 return peak(lst[m:]) # decreasing else: if len(lst[:m]) == 2: m += 1 return peak(lst[:m]) if __name__ == "__main__": import doctest doctest.testmod()
""" Finding the peak of a unimodal list using divide and conquer. A unimodal array is defined as follows: array is increasing up to index p, then decreasing afterwards. (for p >= 1) An obvious solution can be performed in O(n), to find the maximum of the array. (From Kleinberg and Tardos. Algorithm Design. Addison Wesley 2006: Chapter 5 Solved Exercise 1) """ from __future__ import annotations def peak(lst: list[int]) -> int: """ Return the peak value of `lst`. >>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1]) 5 >>> peak([1, 10, 9, 8, 7, 6, 5, 4]) 10 >>> peak([1, 9, 8, 7]) 9 >>> peak([1, 2, 3, 4, 5, 6, 7, 0]) 7 >>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2]) 4 """ # middle index m = len(lst) // 2 # choose the middle 3 elements three = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m]) == 2: m -= 1 return peak(lst[m:]) # decreasing else: if len(lst[:m]) == 2: m += 1 return peak(lst[:m]) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
#!/usr/bin/env python3 """ Build a simple bare-minimum quantum circuit that starts with a single qubit (by default, in state 0), runs the experiment 1000 times, and finally prints the total count of the states finally observed. Qiskit Docs: https://qiskit.org/documentation/getting_started.html """ import qiskit def single_qubit_measure( qubits: int, classical_bits: int ) -> qiskit.result.counts.Counts: """ >>> single_qubit_measure(1, 1) {'0': 1000} """ # Use Aer's simulator simulator = qiskit.Aer.get_backend("aer_simulator") # Create a Quantum Circuit acting on the q register circuit = qiskit.QuantumCircuit(qubits, classical_bits) # Map the quantum measurement to the classical bits circuit.measure([0], [0]) # Execute the circuit on the simulator job = qiskit.execute(circuit, simulator, shots=1000) # Return the histogram data of the results of the experiment. return job.result().get_counts(circuit) if __name__ == "__main__": print(f"Total count for various states are: {single_qubit_measure(1, 1)}")
#!/usr/bin/env python3 """ Build a simple bare-minimum quantum circuit that starts with a single qubit (by default, in state 0), runs the experiment 1000 times, and finally prints the total count of the states finally observed. Qiskit Docs: https://qiskit.org/documentation/getting_started.html """ import qiskit def single_qubit_measure( qubits: int, classical_bits: int ) -> qiskit.result.counts.Counts: """ >>> single_qubit_measure(1, 1) {'0': 1000} """ # Use Aer's simulator simulator = qiskit.Aer.get_backend("aer_simulator") # Create a Quantum Circuit acting on the q register circuit = qiskit.QuantumCircuit(qubits, classical_bits) # Map the quantum measurement to the classical bits circuit.measure([0], [0]) # Execute the circuit on the simulator job = qiskit.execute(circuit, simulator, shots=1000) # Return the histogram data of the results of the experiment. return job.result().get_counts(circuit) if __name__ == "__main__": print(f"Total count for various states are: {single_qubit_measure(1, 1)}")
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
def split(string: str, separator: str = " ") -> list: """ Will split the string up into all the values separated by the separator (defaults to spaces) >>> split("apple#banana#cherry#orange",separator='#') ['apple', 'banana', 'cherry', 'orange'] >>> split("Hello there") ['Hello', 'there'] >>> split("11/22/63",separator = '/') ['11', '22', '63'] >>> split("12:43:39",separator = ":") ['12', '43', '39'] """ split_words = [] last_index = 0 for index, char in enumerate(string): if char == separator: split_words.append(string[last_index:index]) last_index = index + 1 elif index + 1 == len(string): split_words.append(string[last_index : index + 1]) return split_words if __name__ == "__main__": from doctest import testmod testmod()
def split(string: str, separator: str = " ") -> list: """ Will split the string up into all the values separated by the separator (defaults to spaces) >>> split("apple#banana#cherry#orange",separator='#') ['apple', 'banana', 'cherry', 'orange'] >>> split("Hello there") ['Hello', 'there'] >>> split("11/22/63",separator = '/') ['11', '22', '63'] >>> split("12:43:39",separator = ":") ['12', '43', '39'] """ split_words = [] last_index = 0 for index, char in enumerate(string): if char == separator: split_words.append(string[last_index:index]) last_index = index + 1 elif index + 1 == len(string): split_words.append(string[last_index : index + 1]) return split_words if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# Normal Distribution QuickSort QuickSort Algorithm where the pivot element is chosen randomly between first and last elements of the array, and the array elements are taken from Standard Normal Distribution. ## 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) >>> 'The array is' >>> 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() ``` ------ ![normal distribution large](https://upload.wikimedia.org/wikipedia/commons/thumb/2/25/The_Normal_Distribution.svg/1280px-The_Normal_Distribution.svg.png) ------ ## Comparing the numbers of comparisons We can plot the function for Checking 'The Number of Comparisons' taking place between Normal Distribution QuickSort and Ordinary QuickSort: ```python >>> import matplotlib.pyplot as plt # Normal Distribution 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 QuickSort Algorithm where the pivot element is chosen randomly between first and last elements of the array, and the array elements are taken from Standard Normal Distribution. ## 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) >>> 'The array is' >>> 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() ``` ------ ![normal distribution large](https://upload.wikimedia.org/wikipedia/commons/thumb/2/25/The_Normal_Distribution.svg/1280px-The_Normal_Distribution.svg.png) ------ ## Comparing the numbers of comparisons We can plot the function for Checking 'The Number of Comparisons' taking place between Normal Distribution QuickSort and Ordinary QuickSort: ```python >>> import matplotlib.pyplot as plt # Normal Distribution 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
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Program to encode and decode Baconian or Bacon's Cipher Wikipedia reference : https://en.wikipedia.org/wiki/Bacon%27s_cipher """ encode_dict = { "a": "AAAAA", "b": "AAAAB", "c": "AAABA", "d": "AAABB", "e": "AABAA", "f": "AABAB", "g": "AABBA", "h": "AABBB", "i": "ABAAA", "j": "BBBAA", "k": "ABAAB", "l": "ABABA", "m": "ABABB", "n": "ABBAA", "o": "ABBAB", "p": "ABBBA", "q": "ABBBB", "r": "BAAAA", "s": "BAAAB", "t": "BAABA", "u": "BAABB", "v": "BBBAB", "w": "BABAA", "x": "BABAB", "y": "BABBA", "z": "BABBB", " ": " ", } decode_dict = {value: key for key, value in encode_dict.items()} def encode(word: str) -> str: """ Encodes to Baconian cipher >>> encode("hello") 'AABBBAABAAABABAABABAABBAB' >>> encode("hello world") 'AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB' >>> encode("hello world!") Traceback (most recent call last): ... Exception: encode() accepts only letters of the alphabet and spaces """ encoded = "" for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception("encode() accepts only letters of the alphabet and spaces") return encoded def decode(coded: str) -> str: """ Decodes from Baconian cipher >>> decode("AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB") 'hello world' >>> decode("AABBBAABAAABABAABABAABBAB") 'hello' >>> decode("AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB!") Traceback (most recent call last): ... Exception: decode() accepts only 'A', 'B' and spaces """ if set(coded) - {"A", "B", " "} != set(): raise Exception("decode() accepts only 'A', 'B' and spaces") decoded = "" for word in coded.split(): while len(word) != 0: decoded += decode_dict[word[:5]] word = word[5:] decoded += " " return decoded.strip() if __name__ == "__main__": from doctest import testmod testmod()
""" Program to encode and decode Baconian or Bacon's Cipher Wikipedia reference : https://en.wikipedia.org/wiki/Bacon%27s_cipher """ encode_dict = { "a": "AAAAA", "b": "AAAAB", "c": "AAABA", "d": "AAABB", "e": "AABAA", "f": "AABAB", "g": "AABBA", "h": "AABBB", "i": "ABAAA", "j": "BBBAA", "k": "ABAAB", "l": "ABABA", "m": "ABABB", "n": "ABBAA", "o": "ABBAB", "p": "ABBBA", "q": "ABBBB", "r": "BAAAA", "s": "BAAAB", "t": "BAABA", "u": "BAABB", "v": "BBBAB", "w": "BABAA", "x": "BABAB", "y": "BABBA", "z": "BABBB", " ": " ", } decode_dict = {value: key for key, value in encode_dict.items()} def encode(word: str) -> str: """ Encodes to Baconian cipher >>> encode("hello") 'AABBBAABAAABABAABABAABBAB' >>> encode("hello world") 'AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB' >>> encode("hello world!") Traceback (most recent call last): ... Exception: encode() accepts only letters of the alphabet and spaces """ encoded = "" for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception("encode() accepts only letters of the alphabet and spaces") return encoded def decode(coded: str) -> str: """ Decodes from Baconian cipher >>> decode("AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB") 'hello world' >>> decode("AABBBAABAAABABAABABAABBAB") 'hello' >>> decode("AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB!") Traceback (most recent call last): ... Exception: decode() accepts only 'A', 'B' and spaces """ if set(coded) - {"A", "B", " "} != set(): raise Exception("decode() accepts only 'A', 'B' and spaces") decoded = "" for word in coded.split(): while len(word) != 0: decoded += decode_dict[word[:5]] word = word[5:] decoded += " " return decoded.strip() if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" A bag contains one red disc and one blue disc. In a game of chance a player takes a disc at random and its colour is noted. After each turn the disc is returned to the bag, an extra red disc is added, and another disc is taken at random. The player pays £1 to play and wins if they have taken more blue discs than red discs at the end of the game. If the game is played for four turns, the probability of a player winning is exactly 11/120, and so the maximum prize fund the banker should allocate for winning in this game would be £10 before they would expect to incur a loss. Note that any payout will be a whole number of pounds and also includes the original £1 paid to play the game, so in the example given the player actually wins £9. Find the maximum prize fund that should be allocated to a single game in which fifteen turns are played. Solution: For each 15-disc sequence of red and blue for which there are more red than blue, we calculate the probability of that sequence and add it to the total probability of the player winning. The inverse of this probability gives an upper bound for the prize if the banker wants to avoid an expected loss. """ from itertools import product def solution(num_turns: int = 15) -> int: """ Find the maximum prize fund that should be allocated to a single game in which fifteen turns are played. >>> solution(4) 10 >>> solution(10) 225 """ total_prob: float = 0.0 prob: float num_blue: int num_red: int ind: int col: int series: tuple[int, ...] for series in product(range(2), repeat=num_turns): num_blue = series.count(1) num_red = num_turns - num_blue if num_red >= num_blue: continue prob = 1.0 for ind, col in enumerate(series, 2): if col == 0: prob *= (ind - 1) / ind else: prob *= 1 / ind total_prob += prob return int(1 / total_prob) if __name__ == "__main__": print(f"{solution() = }")
""" A bag contains one red disc and one blue disc. In a game of chance a player takes a disc at random and its colour is noted. After each turn the disc is returned to the bag, an extra red disc is added, and another disc is taken at random. The player pays £1 to play and wins if they have taken more blue discs than red discs at the end of the game. If the game is played for four turns, the probability of a player winning is exactly 11/120, and so the maximum prize fund the banker should allocate for winning in this game would be £10 before they would expect to incur a loss. Note that any payout will be a whole number of pounds and also includes the original £1 paid to play the game, so in the example given the player actually wins £9. Find the maximum prize fund that should be allocated to a single game in which fifteen turns are played. Solution: For each 15-disc sequence of red and blue for which there are more red than blue, we calculate the probability of that sequence and add it to the total probability of the player winning. The inverse of this probability gives an upper bound for the prize if the banker wants to avoid an expected loss. """ from itertools import product def solution(num_turns: int = 15) -> int: """ Find the maximum prize fund that should be allocated to a single game in which fifteen turns are played. >>> solution(4) 10 >>> solution(10) 225 """ total_prob: float = 0.0 prob: float num_blue: int num_red: int ind: int col: int series: tuple[int, ...] for series in product(range(2), repeat=num_turns): num_blue = series.count(1) num_red = num_turns - num_blue if num_red >= num_blue: continue prob = 1.0 for ind, col in enumerate(series, 2): if col == 0: prob *= (ind - 1) / ind else: prob *= 1 / ind total_prob += prob return int(1 / total_prob) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Python implementation of a sort algorithm. Best Case Scenario : O(n) Worst Case Scenario : O(n^2) because native Python functions:min, max and remove are already O(n) """ def merge_sort(collection): """Pure implementation of the fastest merge sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: a collection ordered by ascending Examples: >>> merge_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> merge_sort([]) [] >>> merge_sort([-2, -5, -45]) [-45, -5, -2] """ start, end = [], [] while len(collection) > 1: min_one, max_one = min(collection), max(collection) start.append(min_one) end.append(max_one) collection.remove(min_one) collection.remove(max_one) end.reverse() return start + collection + end if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(*merge_sort(unsorted), sep=",")
""" Python implementation of a sort algorithm. Best Case Scenario : O(n) Worst Case Scenario : O(n^2) because native Python functions:min, max and remove are already O(n) """ def merge_sort(collection): """Pure implementation of the fastest merge sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: a collection ordered by ascending Examples: >>> merge_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> merge_sort([]) [] >>> merge_sort([-2, -5, -45]) [-45, -5, -2] """ start, end = [], [] while len(collection) > 1: min_one, max_one = min(collection), max(collection) start.append(min_one) end.append(max_one) collection.remove(min_one) collection.remove(max_one) end.reverse() return start + collection + end if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(*merge_sort(unsorted), sep=",")
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 1: https://projecteuler.net/problem=1 Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def solution(n: int = 1000) -> int: """ Returns the sum of all the multiples of 3 or 5 below n. A straightforward pythonic solution using list comprehension. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ return sum(i for i in range(n) if i % 3 == 0 or i % 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. A straightforward pythonic solution using list comprehension. >>> solution(3) 0 >>> solution(4) 3 >>> solution(10) 23 >>> solution(600) 83700 """ return sum(i for i in range(n) if i % 3 == 0 or i % 5 == 0) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Illustrate how to add the integer without arithmetic operation Author: suraj Kumar Time Complexity: 1 https://en.wikipedia.org/wiki/Bitwise_operation """ def add(first: int, second: int) -> int: """ Implementation of addition of integer Examples: >>> add(3, 5) 8 >>> add(13, 5) 18 >>> add(-7, 2) -5 >>> add(0, -7) -7 >>> add(-321, 0) -321 """ while second != 0: c = first & second first ^= second second = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() first = int(input("Enter the first number: ").strip()) second = int(input("Enter the second number: ").strip()) print(f"{add(first, second) = }")
""" Illustrate how to add the integer without arithmetic operation Author: suraj Kumar Time Complexity: 1 https://en.wikipedia.org/wiki/Bitwise_operation """ def add(first: int, second: int) -> int: """ Implementation of addition of integer Examples: >>> add(3, 5) 8 >>> add(13, 5) 18 >>> add(-7, 2) -5 >>> add(0, -7) -7 >>> add(-321, 0) -321 """ while second != 0: c = first & second first ^= second second = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() first = int(input("Enter the first number: ").strip()) second = int(input("Enter the second number: ").strip()) print(f"{add(first, second) = }")
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
import argparse import datetime def zeller(date_input: str) -> str: """ Zellers Congruence Algorithm Find the day of the week for nearly any Gregorian or Julian calendar date >>> zeller('01-31-2010') 'Your date 01-31-2010, is a Sunday!' Validate out of range month >>> zeller('13-31-2010') Traceback (most recent call last): ... ValueError: Month must be between 1 - 12 >>> zeller('.2-31-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.2' Validate out of range date: >>> zeller('01-33-2010') Traceback (most recent call last): ... ValueError: Date must be between 1 - 31 >>> zeller('01-.4-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.4' Validate second separator: >>> zeller('01-31*2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate first separator: >>> zeller('01^31-2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate out of range year: >>> zeller('01-31-8999') Traceback (most recent call last): ... ValueError: Year out of range. There has to be some sort of limit...right? Test null input: >>> zeller() Traceback (most recent call last): ... TypeError: zeller() missing 1 required positional argument: 'date_input' Test length of date_input: >>> zeller('') Traceback (most recent call last): ... ValueError: Must be 10 characters long >>> zeller('01-31-19082939') Traceback (most recent call last): ... ValueError: Must be 10 characters long""" # Days of the week for response days = { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday", } convert_datetime_days = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(date_input) < 11: raise ValueError("Must be 10 characters long") # Get month m: int = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError("Month must be between 1 - 12") sep_1: str = date_input[2] # Validate if sep_1 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get day d: int = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError("Date must be between 1 - 31") # Get second separator sep_2: str = date_input[5] # Validate if sep_2 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get year y: int = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( "Year out of range. There has to be some sort of limit...right?" ) # Get datetime obj for validation dt_ck = datetime.date(int(y), int(m), int(d)) # Start math if m <= 2: y = y - 1 m = m + 12 # maths var c: int = int(str(y)[:2]) k: int = int(str(y)[2:]) t: int = int(2.6 * m - 5.39) u: int = int(c / 4) v: int = int(k / 4) x: int = int(d + k) z: int = int(t + u + v + x) w: int = int(z - (2 * c)) f: int = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("The date was evaluated incorrectly. Contact developer.") # Response response: str = f"Your date {date_input}, is a {days[str(f)]}!" return response if __name__ == "__main__": import doctest doctest.testmod() parser = argparse.ArgumentParser( description=( "Find out what day of the week nearly any date is or was. Enter " "date as a string in the mm-dd-yyyy or mm/dd/yyyy format" ) ) parser.add_argument( "date_input", type=str, help="Date as a string (mm-dd-yyyy or mm/dd/yyyy)" ) args = parser.parse_args() zeller(args.date_input)
import argparse import datetime def zeller(date_input: str) -> str: """ Zellers Congruence Algorithm Find the day of the week for nearly any Gregorian or Julian calendar date >>> zeller('01-31-2010') 'Your date 01-31-2010, is a Sunday!' Validate out of range month >>> zeller('13-31-2010') Traceback (most recent call last): ... ValueError: Month must be between 1 - 12 >>> zeller('.2-31-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.2' Validate out of range date: >>> zeller('01-33-2010') Traceback (most recent call last): ... ValueError: Date must be between 1 - 31 >>> zeller('01-.4-2010') Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '.4' Validate second separator: >>> zeller('01-31*2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate first separator: >>> zeller('01^31-2010') Traceback (most recent call last): ... ValueError: Date separator must be '-' or '/' Validate out of range year: >>> zeller('01-31-8999') Traceback (most recent call last): ... ValueError: Year out of range. There has to be some sort of limit...right? Test null input: >>> zeller() Traceback (most recent call last): ... TypeError: zeller() missing 1 required positional argument: 'date_input' Test length of date_input: >>> zeller('') Traceback (most recent call last): ... ValueError: Must be 10 characters long >>> zeller('01-31-19082939') Traceback (most recent call last): ... ValueError: Must be 10 characters long""" # Days of the week for response days = { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday", } convert_datetime_days = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(date_input) < 11: raise ValueError("Must be 10 characters long") # Get month m: int = int(date_input[0] + date_input[1]) # Validate if not 0 < m < 13: raise ValueError("Month must be between 1 - 12") sep_1: str = date_input[2] # Validate if sep_1 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get day d: int = int(date_input[3] + date_input[4]) # Validate if not 0 < d < 32: raise ValueError("Date must be between 1 - 31") # Get second separator sep_2: str = date_input[5] # Validate if sep_2 not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'") # Get year y: int = int(date_input[6] + date_input[7] + date_input[8] + date_input[9]) # Arbitrary year range if not 45 < y < 8500: raise ValueError( "Year out of range. There has to be some sort of limit...right?" ) # Get datetime obj for validation dt_ck = datetime.date(int(y), int(m), int(d)) # Start math if m <= 2: y = y - 1 m = m + 12 # maths var c: int = int(str(y)[:2]) k: int = int(str(y)[2:]) t: int = int(2.6 * m - 5.39) u: int = int(c / 4) v: int = int(k / 4) x: int = int(d + k) z: int = int(t + u + v + x) w: int = int(z - (2 * c)) f: int = round(w % 7) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("The date was evaluated incorrectly. Contact developer.") # Response response: str = f"Your date {date_input}, is a {days[str(f)]}!" return response if __name__ == "__main__": import doctest doctest.testmod() parser = argparse.ArgumentParser( description=( "Find out what day of the week nearly any date is or was. Enter " "date as a string in the mm-dd-yyyy or mm/dd/yyyy format" ) ) parser.add_argument( "date_input", type=str, help="Date as a string (mm-dd-yyyy or mm/dd/yyyy)" ) args = parser.parse_args() zeller(args.date_input)
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Illustrate how to implement inorder traversal in binary search tree. Author: Gurneet Singh https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/ """ class BinaryTreeNode: """Defining the structure of BinaryTreeNode""" def __init__(self, data: int) -> None: self.data = data self.left_child: BinaryTreeNode | None = None self.right_child: BinaryTreeNode | None = None def insert(node: BinaryTreeNode | None, new_value: int) -> BinaryTreeNode | None: """ If the binary search tree is empty, make a new node and declare it as root. >>> node_a = BinaryTreeNode(12345) >>> node_b = insert(node_a, 67890) >>> node_a.left_child == node_b.left_child True >>> node_a.right_child == node_b.right_child True >>> node_a.data == node_b.data True """ if node is None: node = BinaryTreeNode(new_value) return node # binary search tree is not empty, # so we will insert it into the tree # if new_value is less than value of data in node, # add it to left subtree and proceed recursively if new_value < node.data: node.left_child = insert(node.left_child, new_value) else: # if new_value is greater than value of data in node, # add it to right subtree and proceed recursively node.right_child = insert(node.right_child, new_value) return node def inorder(node: None | BinaryTreeNode) -> list[int]: # if node is None,return """ >>> inorder(make_tree()) [6, 10, 14, 15, 20, 25, 60] """ if node: inorder_array = inorder(node.left_child) inorder_array = [*inorder_array, node.data] inorder_array = inorder_array + inorder(node.right_child) else: inorder_array = [] return inorder_array def make_tree() -> BinaryTreeNode | None: root = insert(None, 15) insert(root, 10) insert(root, 25) insert(root, 6) insert(root, 14) insert(root, 20) insert(root, 60) return root def main() -> None: # main function root = make_tree() print("Printing values of binary search tree in Inorder Traversal.") inorder(root) if __name__ == "__main__": import doctest doctest.testmod() main()
""" Illustrate how to implement inorder traversal in binary search tree. Author: Gurneet Singh https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/ """ class BinaryTreeNode: """Defining the structure of BinaryTreeNode""" def __init__(self, data: int) -> None: self.data = data self.left_child: BinaryTreeNode | None = None self.right_child: BinaryTreeNode | None = None def insert(node: BinaryTreeNode | None, new_value: int) -> BinaryTreeNode | None: """ If the binary search tree is empty, make a new node and declare it as root. >>> node_a = BinaryTreeNode(12345) >>> node_b = insert(node_a, 67890) >>> node_a.left_child == node_b.left_child True >>> node_a.right_child == node_b.right_child True >>> node_a.data == node_b.data True """ if node is None: node = BinaryTreeNode(new_value) return node # binary search tree is not empty, # so we will insert it into the tree # if new_value is less than value of data in node, # add it to left subtree and proceed recursively if new_value < node.data: node.left_child = insert(node.left_child, new_value) else: # if new_value is greater than value of data in node, # add it to right subtree and proceed recursively node.right_child = insert(node.right_child, new_value) return node def inorder(node: None | BinaryTreeNode) -> list[int]: # if node is None,return """ >>> inorder(make_tree()) [6, 10, 14, 15, 20, 25, 60] """ if node: inorder_array = inorder(node.left_child) inorder_array = [*inorder_array, node.data] inorder_array = inorder_array + inorder(node.right_child) else: inorder_array = [] return inorder_array def make_tree() -> BinaryTreeNode | None: root = insert(None, 15) insert(root, 10) insert(root, 25) insert(root, 6) insert(root, 14) insert(root, 20) insert(root, 60) return root def main() -> None: # main function root = make_tree() print("Printing values of binary search tree in Inorder Traversal.") inorder(root) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
import math from collections.abc import Callable def intersection(function: Callable[[float], float], x0: float, x1: float) -> float: """ function is the f we want to find its root x0 and x1 are two random starting points >>> intersection(lambda x: x ** 3 - 1, -5, 5) 0.9999999999954654 >>> intersection(lambda x: x ** 3 - 1, 5, 5) Traceback (most recent call last): ... ZeroDivisionError: float division by zero, could not find root >>> intersection(lambda x: x ** 3 - 1, 100, 200) 1.0000000000003888 >>> intersection(lambda x: x ** 2 - 4 * x + 3, 0, 2) 0.9999999998088019 >>> intersection(lambda x: x ** 2 - 4 * x + 3, 2, 4) 2.9999999998088023 >>> intersection(lambda x: x ** 2 - 4 * x + 3, 4, 1000) 3.0000000001786042 >>> intersection(math.sin, -math.pi, math.pi) 0.0 >>> intersection(math.cos, -math.pi, math.pi) Traceback (most recent call last): ... ZeroDivisionError: float division by zero, could not find root """ x_n: float = x0 x_n1: float = x1 while True: if x_n == x_n1 or function(x_n1) == function(x_n): raise ZeroDivisionError("float division by zero, could not find root") x_n2: float = x_n1 - ( function(x_n1) / ((function(x_n1) - function(x_n)) / (x_n1 - x_n)) ) if abs(x_n2 - x_n1) < 10**-5: return x_n2 x_n = x_n1 x_n1 = x_n2 def f(x: float) -> float: return math.pow(x, 3) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
import math from collections.abc import Callable def intersection(function: Callable[[float], float], x0: float, x1: float) -> float: """ function is the f we want to find its root x0 and x1 are two random starting points >>> intersection(lambda x: x ** 3 - 1, -5, 5) 0.9999999999954654 >>> intersection(lambda x: x ** 3 - 1, 5, 5) Traceback (most recent call last): ... ZeroDivisionError: float division by zero, could not find root >>> intersection(lambda x: x ** 3 - 1, 100, 200) 1.0000000000003888 >>> intersection(lambda x: x ** 2 - 4 * x + 3, 0, 2) 0.9999999998088019 >>> intersection(lambda x: x ** 2 - 4 * x + 3, 2, 4) 2.9999999998088023 >>> intersection(lambda x: x ** 2 - 4 * x + 3, 4, 1000) 3.0000000001786042 >>> intersection(math.sin, -math.pi, math.pi) 0.0 >>> intersection(math.cos, -math.pi, math.pi) Traceback (most recent call last): ... ZeroDivisionError: float division by zero, could not find root """ x_n: float = x0 x_n1: float = x1 while True: if x_n == x_n1 or function(x_n1) == function(x_n): raise ZeroDivisionError("float division by zero, could not find root") x_n2: float = x_n1 - ( function(x_n1) / ((function(x_n1) - function(x_n)) / (x_n1 - x_n)) ) if abs(x_n2 - x_n1) < 10**-5: return x_n2 x_n = x_n1 x_n1 = x_n2 def f(x: float) -> float: return math.pow(x, 3) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
#!/usr/bin/env python3 from __future__ import annotations 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 # 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 # 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
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# Contributing guidelines ## Before contributing Welcome to [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python)! Before sending your pull requests, make sure that you __read the whole guidelines__. If you have any doubt on the contributing guide, please feel free to [state it clearly in an issue](https://github.com/TheAlgorithms/Python/issues/new) or ask the community in [Gitter](https://gitter.im/TheAlgorithms/community). ## Contributing ### Contributor We are very happy that you are considering implementing algorithms and data structures for others! This repository is referenced and used by learners from all over the globe. Being one of our contributors, you agree and confirm that: - You did your work - no plagiarism allowed - Any plagiarized work will not be merged. - Your work will be distributed under [MIT License](LICENSE.md) once your pull request is merged - Your submitted work fulfils or mostly fulfils our styles and standards __New implementation__ is welcome! For example, new solutions for a problem, different representations for a graph data structure or algorithm designs with different complexity but __identical implementation__ of an existing implementation is not allowed. Please check whether the solution is already implemented or not before submitting your pull request. __Improving comments__ and __writing proper tests__ are also highly welcome. ### Contribution We appreciate any contribution, from fixing a grammar mistake in a comment to implementing complex algorithms. Please read this section if you are contributing your work. Your contribution will be tested by our [automated testing on GitHub Actions](https://github.com/TheAlgorithms/Python/actions) to save time and mental energy. After you have submitted your pull request, you should see the GitHub Actions tests start to run at the bottom of your submission page. If those tests fail, then click on the ___details___ button try to read through the GitHub Actions output to understand the failure. If you do not understand, please leave a comment on your submission page and a community member will try to help. Please help us keep our issue list small by adding `Fixes #{$ISSUE_NUMBER}` to the description of pull requests that resolve open issues. For example, if your pull request fixes issue #10, then please add the following to its description: ``` Fixes #10 ``` GitHub will use this tag to [auto-close the issue](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) if and when the PR is merged. #### What is an Algorithm? An Algorithm is one or more functions (or classes) that: * take one or more inputs, * perform some internal calculations or data manipulations, * return one or more outputs, * have minimal side effects (Ex. `print()`, `plot()`, `read()`, `write()`). Algorithms should be packaged in a way that would make it easy for readers to put them into larger programs. Algorithms should: * have intuitive class and function names that make their purpose clear to readers * use Python naming conventions and intuitive variable names to ease comprehension * be flexible to take different input values * have Python type hints for their input parameters and return values * raise Python exceptions (`ValueError`, etc.) on erroneous input values * have docstrings with clear explanations and/or URLs to source materials * contain doctests that test both valid and erroneous input values * return all calculation results instead of printing or plotting them Algorithms in this repo should not be how-to examples for existing Python packages. Instead, they should perform internal calculations or manipulations to convert input values into different output values. Those calculations or manipulations can use data types, classes, or functions of existing Python packages but each algorithm in this repo should add unique value. #### Pre-commit plugin Use [pre-commit](https://pre-commit.com/#installation) to automatically format your code to match our coding style: ```bash python3 -m pip install pre-commit # only required the first time pre-commit install ``` That's it! The plugin will run every time you commit any changes. If there are any errors found during the run, fix them and commit those changes. You can even run the plugin manually on all files: ```bash pre-commit run --all-files --show-diff-on-failure ``` #### Coding Style We want your work to be readable by others; therefore, we encourage you to note the following: - Please write in Python 3.11+. For instance: `print()` is a function in Python 3 so `print "Hello"` will *not* work but `print("Hello")` will. - Please focus hard on the naming of functions, classes, and variables. Help your reader by using __descriptive names__ that can help you to remove redundant comments. - Single letter variable names are *old school* so please avoid them unless their life only spans a few lines. - Expand acronyms because `gcd()` is hard to understand but `greatest_common_divisor()` is not. - Please follow the [Python Naming Conventions](https://pep8.org/#prescriptive-naming-conventions) so variable_names and function_names should be lower_case, CONSTANTS in UPPERCASE, ClassNames should be CamelCase, etc. - We encourage the use of Python [f-strings](https://realpython.com/python-f-strings/#f-strings-a-new-and-improved-way-to-format-strings-in-python) where they make the code easier to read. - Please consider running [__psf/black__](https://github.com/python/black) on your Python file(s) before submitting your pull request. This is not yet a requirement but it does make your code more readable and automatically aligns it with much of [PEP 8](https://www.python.org/dev/peps/pep-0008/). There are other code formatters (autopep8, yapf) but the __black__ formatter is now hosted by the Python Software Foundation. To use it, ```bash python3 -m pip install black # only required the first time black . ``` - All submissions will need to pass the test `ruff .` before they will be accepted so if possible, try this test locally on your Python file(s) before submitting your pull request. ```bash python3 -m pip install ruff # only required the first time ruff . ``` - Original code submission require docstrings or comments to describe your work. - More on docstrings and comments: If you used a Wikipedia article or some other source material to create your algorithm, please add the URL in a docstring or comment to help your reader. The following are considered to be bad and may be requested to be improved: ```python x = x + 2 # increased by 2 ``` This is too trivial. Comments are expected to be explanatory. For comments, you can write them above, on or below a line of code, as long as you are consistent within the same piece of code. We encourage you to put docstrings inside your functions but please pay attention to the indentation of docstrings. The following is a good example: ```python def sum_ab(a, b): """ Return the sum of two integers a and b. """ return a + b ``` - Write tests (especially [__doctests__](https://docs.python.org/3/library/doctest.html)) to illustrate and verify your work. We highly encourage the use of _doctests on all functions_. ```python def sum_ab(a, b): """ Return the sum of two integers a and b >>> sum_ab(2, 2) 4 >>> sum_ab(-2, 3) 1 >>> sum_ab(4.9, 5.1) 10.0 """ return a + b ``` These doctests will be run by pytest as part of our automated testing so please try to run your doctests locally and make sure that they are found and pass: ```bash python3 -m doctest -v my_submission.py ``` The use of the Python builtin `input()` function is __not__ encouraged: ```python input('Enter your input:') # Or even worse... input = eval(input("Enter your input: ")) ``` However, if your code uses `input()` then we encourage you to gracefully deal with leading and trailing whitespace in user input by adding `.strip()` as in: ```python starting_value = int(input("Please enter a starting value: ").strip()) ``` The use of [Python type hints](https://docs.python.org/3/library/typing.html) is encouraged for function parameters and return values. Our automated testing will run [mypy](http://mypy-lang.org) so run that locally before making your submission. ```python def sum_ab(a: int, b: int) -> int: return a + b ``` Instructions on how to install mypy can be found [here](https://github.com/python/mypy). Please use the command `mypy --ignore-missing-imports .` to test all files or `mypy --ignore-missing-imports path/to/file.py` to test a specific file. - [__List comprehensions and generators__](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) are preferred over the use of `lambda`, `map`, `filter`, `reduce` but the important thing is to demonstrate the power of Python in code that is easy to read and maintain. - Avoid importing external libraries for basic algorithms. Only use those libraries for complicated algorithms. - If you need a third-party module that is not in the file __requirements.txt__, please add it to that file as part of your submission. #### Other Requirements for Submissions - If you are submitting code in the `project_euler/` directory, please also read [the dedicated Guideline](https://github.com/TheAlgorithms/Python/blob/master/project_euler/README.md) before contributing to our Project Euler library. - The file extension for code files should be `.py`. Jupyter Notebooks should be submitted to [TheAlgorithms/Jupyter](https://github.com/TheAlgorithms/Jupyter). - Strictly use snake_case (underscore_separated) in your file_name, as it will be easy to parse in future using scripts. - Please avoid creating new directories if at all possible. Try to fit your work into the existing directory structure. - If possible, follow the standard *within* the folder you are submitting to. - If you have modified/added code work, make sure the code compiles before submitting. - If you have modified/added documentation work, ensure your language is concise and contains no grammar errors. - Do not update the README.md or DIRECTORY.md file which will be periodically autogenerated by our GitHub Actions processes. - Add a corresponding explanation to [Algorithms-Explanation](https://github.com/TheAlgorithms/Algorithms-Explanation) (Optional but recommended). - All submissions will be tested with [__mypy__](http://www.mypy-lang.org) so we encourage you to add [__Python type hints__](https://docs.python.org/3/library/typing.html) where it makes sense to do so. - Most importantly, - __Be consistent in the use of these guidelines when submitting.__ - __Join__ us on [Discord](https://discord.com/invite/c7MnfGFGa6) and [Gitter](https://gitter.im/TheAlgorithms/community) __now!__ - Happy coding! Writer [@poyea](https://github.com/poyea), Jun 2019.
# Contributing guidelines ## Before contributing Welcome to [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python)! Before sending your pull requests, make sure that you __read the whole guidelines__. If you have any doubt on the contributing guide, please feel free to [state it clearly in an issue](https://github.com/TheAlgorithms/Python/issues/new) or ask the community in [Gitter](https://gitter.im/TheAlgorithms/community). ## Contributing ### Contributor We are very happy that you are considering implementing algorithms and data structures for others! This repository is referenced and used by learners from all over the globe. Being one of our contributors, you agree and confirm that: - You did your work - no plagiarism allowed - Any plagiarized work will not be merged. - Your work will be distributed under [MIT License](LICENSE.md) once your pull request is merged - Your submitted work fulfils or mostly fulfils our styles and standards __New implementation__ is welcome! For example, new solutions for a problem, different representations for a graph data structure or algorithm designs with different complexity but __identical implementation__ of an existing implementation is not allowed. Please check whether the solution is already implemented or not before submitting your pull request. __Improving comments__ and __writing proper tests__ are also highly welcome. ### Contribution We appreciate any contribution, from fixing a grammar mistake in a comment to implementing complex algorithms. Please read this section if you are contributing your work. Your contribution will be tested by our [automated testing on GitHub Actions](https://github.com/TheAlgorithms/Python/actions) to save time and mental energy. After you have submitted your pull request, you should see the GitHub Actions tests start to run at the bottom of your submission page. If those tests fail, then click on the ___details___ button try to read through the GitHub Actions output to understand the failure. If you do not understand, please leave a comment on your submission page and a community member will try to help. Please help us keep our issue list small by adding `Fixes #{$ISSUE_NUMBER}` to the description of pull requests that resolve open issues. For example, if your pull request fixes issue #10, then please add the following to its description: ``` Fixes #10 ``` GitHub will use this tag to [auto-close the issue](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) if and when the PR is merged. #### What is an Algorithm? An Algorithm is one or more functions (or classes) that: * take one or more inputs, * perform some internal calculations or data manipulations, * return one or more outputs, * have minimal side effects (Ex. `print()`, `plot()`, `read()`, `write()`). Algorithms should be packaged in a way that would make it easy for readers to put them into larger programs. Algorithms should: * have intuitive class and function names that make their purpose clear to readers * use Python naming conventions and intuitive variable names to ease comprehension * be flexible to take different input values * have Python type hints for their input parameters and return values * raise Python exceptions (`ValueError`, etc.) on erroneous input values * have docstrings with clear explanations and/or URLs to source materials * contain doctests that test both valid and erroneous input values * return all calculation results instead of printing or plotting them Algorithms in this repo should not be how-to examples for existing Python packages. Instead, they should perform internal calculations or manipulations to convert input values into different output values. Those calculations or manipulations can use data types, classes, or functions of existing Python packages but each algorithm in this repo should add unique value. #### Pre-commit plugin Use [pre-commit](https://pre-commit.com/#installation) to automatically format your code to match our coding style: ```bash python3 -m pip install pre-commit # only required the first time pre-commit install ``` That's it! The plugin will run every time you commit any changes. If there are any errors found during the run, fix them and commit those changes. You can even run the plugin manually on all files: ```bash pre-commit run --all-files --show-diff-on-failure ``` #### Coding Style We want your work to be readable by others; therefore, we encourage you to note the following: - Please write in Python 3.11+. For instance: `print()` is a function in Python 3 so `print "Hello"` will *not* work but `print("Hello")` will. - Please focus hard on the naming of functions, classes, and variables. Help your reader by using __descriptive names__ that can help you to remove redundant comments. - Single letter variable names are *old school* so please avoid them unless their life only spans a few lines. - Expand acronyms because `gcd()` is hard to understand but `greatest_common_divisor()` is not. - Please follow the [Python Naming Conventions](https://pep8.org/#prescriptive-naming-conventions) so variable_names and function_names should be lower_case, CONSTANTS in UPPERCASE, ClassNames should be CamelCase, etc. - We encourage the use of Python [f-strings](https://realpython.com/python-f-strings/#f-strings-a-new-and-improved-way-to-format-strings-in-python) where they make the code easier to read. - Please consider running [__psf/black__](https://github.com/python/black) on your Python file(s) before submitting your pull request. This is not yet a requirement but it does make your code more readable and automatically aligns it with much of [PEP 8](https://www.python.org/dev/peps/pep-0008/). There are other code formatters (autopep8, yapf) but the __black__ formatter is now hosted by the Python Software Foundation. To use it, ```bash python3 -m pip install black # only required the first time black . ``` - All submissions will need to pass the test `ruff .` before they will be accepted so if possible, try this test locally on your Python file(s) before submitting your pull request. ```bash python3 -m pip install ruff # only required the first time ruff . ``` - Original code submission require docstrings or comments to describe your work. - More on docstrings and comments: If you used a Wikipedia article or some other source material to create your algorithm, please add the URL in a docstring or comment to help your reader. The following are considered to be bad and may be requested to be improved: ```python x = x + 2 # increased by 2 ``` This is too trivial. Comments are expected to be explanatory. For comments, you can write them above, on or below a line of code, as long as you are consistent within the same piece of code. We encourage you to put docstrings inside your functions but please pay attention to the indentation of docstrings. The following is a good example: ```python def sum_ab(a, b): """ Return the sum of two integers a and b. """ return a + b ``` - Write tests (especially [__doctests__](https://docs.python.org/3/library/doctest.html)) to illustrate and verify your work. We highly encourage the use of _doctests on all functions_. ```python def sum_ab(a, b): """ Return the sum of two integers a and b >>> sum_ab(2, 2) 4 >>> sum_ab(-2, 3) 1 >>> sum_ab(4.9, 5.1) 10.0 """ return a + b ``` These doctests will be run by pytest as part of our automated testing so please try to run your doctests locally and make sure that they are found and pass: ```bash python3 -m doctest -v my_submission.py ``` The use of the Python builtin `input()` function is __not__ encouraged: ```python input('Enter your input:') # Or even worse... input = eval(input("Enter your input: ")) ``` However, if your code uses `input()` then we encourage you to gracefully deal with leading and trailing whitespace in user input by adding `.strip()` as in: ```python starting_value = int(input("Please enter a starting value: ").strip()) ``` The use of [Python type hints](https://docs.python.org/3/library/typing.html) is encouraged for function parameters and return values. Our automated testing will run [mypy](http://mypy-lang.org) so run that locally before making your submission. ```python def sum_ab(a: int, b: int) -> int: return a + b ``` Instructions on how to install mypy can be found [here](https://github.com/python/mypy). Please use the command `mypy --ignore-missing-imports .` to test all files or `mypy --ignore-missing-imports path/to/file.py` to test a specific file. - [__List comprehensions and generators__](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) are preferred over the use of `lambda`, `map`, `filter`, `reduce` but the important thing is to demonstrate the power of Python in code that is easy to read and maintain. - Avoid importing external libraries for basic algorithms. Only use those libraries for complicated algorithms. - If you need a third-party module that is not in the file __requirements.txt__, please add it to that file as part of your submission. #### Other Requirements for Submissions - If you are submitting code in the `project_euler/` directory, please also read [the dedicated Guideline](https://github.com/TheAlgorithms/Python/blob/master/project_euler/README.md) before contributing to our Project Euler library. - The file extension for code files should be `.py`. Jupyter Notebooks should be submitted to [TheAlgorithms/Jupyter](https://github.com/TheAlgorithms/Jupyter). - Strictly use snake_case (underscore_separated) in your file_name, as it will be easy to parse in future using scripts. - Please avoid creating new directories if at all possible. Try to fit your work into the existing directory structure. - If possible, follow the standard *within* the folder you are submitting to. - If you have modified/added code work, make sure the code compiles before submitting. - If you have modified/added documentation work, ensure your language is concise and contains no grammar errors. - Do not update the README.md or DIRECTORY.md file which will be periodically autogenerated by our GitHub Actions processes. - Add a corresponding explanation to [Algorithms-Explanation](https://github.com/TheAlgorithms/Algorithms-Explanation) (Optional but recommended). - All submissions will be tested with [__mypy__](http://www.mypy-lang.org) so we encourage you to add [__Python type hints__](https://docs.python.org/3/library/typing.html) where it makes sense to do so. - Most importantly, - __Be consistent in the use of these guidelines when submitting.__ - __Join__ us on [Discord](https://discord.com/invite/c7MnfGFGa6) and [Gitter](https://gitter.im/TheAlgorithms/community) __now!__ - Happy coding! Writer [@poyea](https://github.com/poyea), Jun 2019.
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from collections import Counter def sock_merchant(colors: list[int]) -> int: """ >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20]) 3 >>> sock_merchant([1, 1, 3, 3]) 2 """ return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values()) if __name__ == "__main__": import doctest doctest.testmod() colors = [int(x) for x in input("Enter socks by color :").rstrip().split()] print(f"sock_merchant({colors}) = {sock_merchant(colors)}")
from collections import Counter def sock_merchant(colors: list[int]) -> int: """ >>> sock_merchant([10, 20, 20, 10, 10, 30, 50, 10, 20]) 3 >>> sock_merchant([1, 1, 3, 3]) 2 """ return sum(socks_by_color // 2 for socks_by_color in Counter(colors).values()) if __name__ == "__main__": import doctest doctest.testmod() colors = [int(x) for x in input("Enter socks by color :").rstrip().split()] print(f"sock_merchant({colors}) = {sock_merchant(colors)}")
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Problem 46: https://projecteuler.net/problem=46 It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2 × 12 15 = 7 + 2 × 22 21 = 3 + 2 × 32 25 = 7 + 2 × 32 27 = 19 + 2 × 22 33 = 31 + 2 × 12 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? """ from __future__ import annotations import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True odd_composites = [num for num in range(3, 100001, 2) if not is_prime(num)] def compute_nums(n: int) -> list[int]: """ Returns a list of first n odd composite numbers which do not follow the conjecture. >>> compute_nums(1) [5777] >>> compute_nums(2) [5777, 5993] >>> compute_nums(0) Traceback (most recent call last): ... ValueError: n must be >= 0 >>> compute_nums("a") Traceback (most recent call last): ... ValueError: n must be an integer >>> compute_nums(1.1) Traceback (most recent call last): ... ValueError: n must be an integer """ if not isinstance(n, int): raise ValueError("n must be an integer") if n <= 0: raise ValueError("n must be >= 0") list_nums = [] for num in range(len(odd_composites)): i = 0 while 2 * i * i <= odd_composites[num]: rem = odd_composites[num] - 2 * i * i if is_prime(rem): break i += 1 else: list_nums.append(odd_composites[num]) if len(list_nums) == n: return list_nums return [] def solution() -> int: """Return the solution to the problem""" return compute_nums(1)[0] if __name__ == "__main__": print(f"{solution() = }")
""" Problem 46: https://projecteuler.net/problem=46 It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2 × 12 15 = 7 + 2 × 22 21 = 3 + 2 × 32 25 = 7 + 2 × 32 27 = 19 + 2 × 22 33 = 31 + 2 × 12 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? """ from __future__ import annotations import math def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True odd_composites = [num for num in range(3, 100001, 2) if not is_prime(num)] def compute_nums(n: int) -> list[int]: """ Returns a list of first n odd composite numbers which do not follow the conjecture. >>> compute_nums(1) [5777] >>> compute_nums(2) [5777, 5993] >>> compute_nums(0) Traceback (most recent call last): ... ValueError: n must be >= 0 >>> compute_nums("a") Traceback (most recent call last): ... ValueError: n must be an integer >>> compute_nums(1.1) Traceback (most recent call last): ... ValueError: n must be an integer """ if not isinstance(n, int): raise ValueError("n must be an integer") if n <= 0: raise ValueError("n must be >= 0") list_nums = [] for num in range(len(odd_composites)): i = 0 while 2 * i * i <= odd_composites[num]: rem = odd_composites[num] - 2 * i * i if is_prime(rem): break i += 1 else: list_nums.append(odd_composites[num]) if len(list_nums) == n: return list_nums return [] def solution() -> int: """Return the solution to the problem""" return compute_nums(1)[0] if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Program to check if a cycle is present in a given graph """ def check_cycle(graph: dict) -> bool: """ Returns True if graph is cyclic else False >>> check_cycle(graph={0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]}) False >>> check_cycle(graph={0:[1, 2], 1:[2], 2:[0, 3], 3:[3]}) True """ # Keep track of visited nodes visited: set[int] = set() # To detect a back edge, keep track of vertices currently in the recursion stack rec_stk: set[int] = set() return any( node not in visited and depth_first_search(graph, node, visited, rec_stk) for node in graph ) def depth_first_search(graph: dict, vertex: int, visited: set, rec_stk: set) -> bool: """ Recur for all neighbours. If any neighbour is visited and in rec_stk then graph is cyclic. >>> graph = {0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]} >>> vertex, visited, rec_stk = 0, set(), set() >>> depth_first_search(graph, vertex, visited, rec_stk) False """ # Mark current node as visited and add to recursion stack visited.add(vertex) rec_stk.add(vertex) for node in graph[vertex]: if node not in visited: if depth_first_search(graph, node, visited, rec_stk): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(vertex) return False if __name__ == "__main__": from doctest import testmod testmod()
""" Program to check if a cycle is present in a given graph """ def check_cycle(graph: dict) -> bool: """ Returns True if graph is cyclic else False >>> check_cycle(graph={0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]}) False >>> check_cycle(graph={0:[1, 2], 1:[2], 2:[0, 3], 3:[3]}) True """ # Keep track of visited nodes visited: set[int] = set() # To detect a back edge, keep track of vertices currently in the recursion stack rec_stk: set[int] = set() return any( node not in visited and depth_first_search(graph, node, visited, rec_stk) for node in graph ) def depth_first_search(graph: dict, vertex: int, visited: set, rec_stk: set) -> bool: """ Recur for all neighbours. If any neighbour is visited and in rec_stk then graph is cyclic. >>> graph = {0:[], 1:[0, 3], 2:[0, 4], 3:[5], 4:[5], 5:[]} >>> vertex, visited, rec_stk = 0, set(), set() >>> depth_first_search(graph, vertex, visited, rec_stk) False """ # Mark current node as visited and add to recursion stack visited.add(vertex) rec_stk.add(vertex) for node in graph[vertex]: if node not in visited: if depth_first_search(graph, node, visited, rec_stk): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(vertex) return False if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" The nqueens problem is of placing N queens on a N * N chess board such that no queen can attack any other queens placed on that chess board. This means that one queen cannot have any other queen on its horizontal, vertical and diagonal lines. """ from __future__ import annotations solution = [] def is_safe(board: list[list[int]], row: int, column: int) -> bool: """ This function returns a boolean value True if it is safe to place a queen there considering the current state of the board. Parameters : board(2D matrix) : board row ,column : coordinates of the cell on a board Returns : Boolean Value """ for i in range(len(board)): if board[row][i] == 1: return False for i in range(len(board)): if board[i][column] == 1: return False for i, j in zip(range(row, -1, -1), range(column, -1, -1)): if board[i][j] == 1: return False for i, j in zip(range(row, -1, -1), range(column, len(board))): if board[i][j] == 1: return False return True def solve(board: list[list[int]], row: int) -> bool: """ It creates a state space tree and calls the safe function until it receives a False Boolean and terminates that branch and backtracks to the next possible solution branch. """ if row >= len(board): """ If the row number exceeds N we have board with a successful combination and that combination is appended to the solution list and the board is printed. """ solution.append(board) printboard(board) print() return True for i in range(len(board)): """ For every row it iterates through each column to check if it is feasible to place a queen there. If all the combinations for that particular branch are successful the board is reinitialized for the next possible combination. """ if is_safe(board, row, i): board[row][i] = 1 solve(board, row + 1) board[row][i] = 0 return False def printboard(board: list[list[int]]) -> None: """ Prints the boards that have a successful combination. """ for i in range(len(board)): for j in range(len(board)): if board[i][j] == 1: print("Q", end=" ") else: print(".", end=" ") print() # n=int(input("The no. of queens")) n = 8 board = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print("The total no. of solutions are :", len(solution))
""" The nqueens problem is of placing N queens on a N * N chess board such that no queen can attack any other queens placed on that chess board. This means that one queen cannot have any other queen on its horizontal, vertical and diagonal lines. """ from __future__ import annotations solution = [] def is_safe(board: list[list[int]], row: int, column: int) -> bool: """ This function returns a boolean value True if it is safe to place a queen there considering the current state of the board. Parameters : board(2D matrix) : board row ,column : coordinates of the cell on a board Returns : Boolean Value """ for i in range(len(board)): if board[row][i] == 1: return False for i in range(len(board)): if board[i][column] == 1: return False for i, j in zip(range(row, -1, -1), range(column, -1, -1)): if board[i][j] == 1: return False for i, j in zip(range(row, -1, -1), range(column, len(board))): if board[i][j] == 1: return False return True def solve(board: list[list[int]], row: int) -> bool: """ It creates a state space tree and calls the safe function until it receives a False Boolean and terminates that branch and backtracks to the next possible solution branch. """ if row >= len(board): """ If the row number exceeds N we have board with a successful combination and that combination is appended to the solution list and the board is printed. """ solution.append(board) printboard(board) print() return True for i in range(len(board)): """ For every row it iterates through each column to check if it is feasible to place a queen there. If all the combinations for that particular branch are successful the board is reinitialized for the next possible combination. """ if is_safe(board, row, i): board[row][i] = 1 solve(board, row + 1) board[row][i] = 0 return False def printboard(board: list[list[int]]) -> None: """ Prints the boards that have a successful combination. """ for i in range(len(board)): for j in range(len(board)): if board[i][j] == 1: print("Q", end=" ") else: print(".", end=" ") print() # n=int(input("The no. of queens")) n = 8 board = [[0 for i in range(n)] for j in range(n)] solve(board, 0) print("The total no. of solutions are :", len(solution))
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
#!/usr/bin/python # Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries """ Implementing logistic regression for classification problem Helpful resources: Coursera ML course https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac """ import numpy as np from matplotlib import pyplot as plt from sklearn import datasets # get_ipython().run_line_magic('matplotlib', 'inline') # In[67]: # sigmoid function or logistic function is used as a hypothesis function in # classification problems def sigmoid_function(z): return 1 / (1 + np.exp(-z)) def cost_function(h, y): return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean() def log_likelihood(x, y, weights): scores = np.dot(x, weights) return np.sum(y * scores - np.log(1 + np.exp(scores))) # here alpha is the learning rate, X is the feature matrix,y is the target matrix def logistic_reg(alpha, x, y, max_iterations=70000): theta = np.zeros(x.shape[1]) for iterations in range(max_iterations): z = np.dot(x, theta) h = sigmoid_function(z) gradient = np.dot(x.T, h - y) / y.size theta = theta - alpha * gradient # updating the weights z = np.dot(x, theta) h = sigmoid_function(z) j = cost_function(h, y) if iterations % 100 == 0: print(f"loss: {j} \t") # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": iris = datasets.load_iris() x = iris.data[:, :2] y = (iris.target != 0) * 1 alpha = 0.1 theta = logistic_reg(alpha, x, y, max_iterations=70000) print("theta: ", theta) # printing the theta i.e our weights vector def predict_prob(x): return sigmoid_function( np.dot(x, theta) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 6)) plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color="b", label="0") plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color="r", label="1") (x1_min, x1_max) = (x[:, 0].min(), x[:, 0].max()) (x2_min, x2_max) = (x[:, 1].min(), x[:, 1].max()) (xx1, xx2) = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max)) grid = np.c_[xx1.ravel(), xx2.ravel()] probs = predict_prob(grid).reshape(xx1.shape) plt.contour(xx1, xx2, probs, [0.5], linewidths=1, colors="black") plt.legend() plt.show()
#!/usr/bin/python # Logistic Regression from scratch # In[62]: # In[63]: # importing all the required libraries """ Implementing logistic regression for classification problem Helpful resources: Coursera ML course https://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac """ import numpy as np from matplotlib import pyplot as plt from sklearn import datasets # get_ipython().run_line_magic('matplotlib', 'inline') # In[67]: # sigmoid function or logistic function is used as a hypothesis function in # classification problems def sigmoid_function(z): return 1 / (1 + np.exp(-z)) def cost_function(h, y): return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean() def log_likelihood(x, y, weights): scores = np.dot(x, weights) return np.sum(y * scores - np.log(1 + np.exp(scores))) # here alpha is the learning rate, X is the feature matrix,y is the target matrix def logistic_reg(alpha, x, y, max_iterations=70000): theta = np.zeros(x.shape[1]) for iterations in range(max_iterations): z = np.dot(x, theta) h = sigmoid_function(z) gradient = np.dot(x.T, h - y) / y.size theta = theta - alpha * gradient # updating the weights z = np.dot(x, theta) h = sigmoid_function(z) j = cost_function(h, y) if iterations % 100 == 0: print(f"loss: {j} \t") # printing the loss after every 100 iterations return theta # In[68]: if __name__ == "__main__": iris = datasets.load_iris() x = iris.data[:, :2] y = (iris.target != 0) * 1 alpha = 0.1 theta = logistic_reg(alpha, x, y, max_iterations=70000) print("theta: ", theta) # printing the theta i.e our weights vector def predict_prob(x): return sigmoid_function( np.dot(x, theta) ) # predicting the value of probability from the logistic regression algorithm plt.figure(figsize=(10, 6)) plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color="b", label="0") plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color="r", label="1") (x1_min, x1_max) = (x[:, 0].min(), x[:, 0].max()) (x2_min, x2_max) = (x[:, 1].min(), x[:, 1].max()) (xx1, xx2) = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max)) grid = np.c_[xx1.ravel(), xx2.ravel()] probs = predict_prob(grid).reshape(xx1.shape) plt.contour(xx1, xx2, probs, [0.5], linewidths=1, colors="black") plt.legend() plt.show()
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" References: - http://neuralnetworksanddeeplearning.com/chap2.html (Backpropagation) - https://en.wikipedia.org/wiki/Sigmoid_function (Sigmoid activation function) - https://en.wikipedia.org/wiki/Feedforward_neural_network (Feedforward) """ import numpy class TwoHiddenLayerNeuralNetwork: def __init__(self, input_array: numpy.ndarray, output_array: numpy.ndarray) -> None: """ This function initializes the TwoHiddenLayerNeuralNetwork class with random weights for every layer and initializes predicted output with zeroes. input_array : input values for training the neural network (i.e training data) . output_array : expected output values of the given inputs. """ # Input values provided for training the model. self.input_array = input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. self.input_layer_and_first_hidden_layer_weights = numpy.random.rand( self.input_array.shape[1], 4 ) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. self.first_hidden_layer_and_second_hidden_layer_weights = numpy.random.rand( 4, 3 ) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. self.second_hidden_layer_and_output_layer_weights = numpy.random.rand(3, 1) # Real output values provided. self.output_array = output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. self.predicted_output = numpy.zeros(output_array.shape) def feedforward(self) -> numpy.ndarray: """ The information moves in only one direction i.e. forward from the input nodes, through the two hidden nodes and to the output nodes. There are no cycles or loops in the network. Return layer_between_second_hidden_layer_and_output (i.e the last layer of the neural network). >>> input_val = numpy.array(([0, 0, 0], [0, 0, 0], [0, 0, 0]), dtype=float) >>> output_val = numpy.array(([0], [0], [0]), dtype=float) >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val) >>> res = nn.feedforward() >>> array_sum = numpy.sum(res) >>> numpy.isnan(array_sum) False """ # Layer_between_input_and_first_hidden_layer is the layer connecting the # input nodes with the first hidden layer nodes. self.layer_between_input_and_first_hidden_layer = sigmoid( numpy.dot(self.input_array, self.input_layer_and_first_hidden_layer_weights) ) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. self.layer_between_first_hidden_layer_and_second_hidden_layer = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer, self.first_hidden_layer_and_second_hidden_layer_weights, ) ) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. self.layer_between_second_hidden_layer_and_output = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer, self.second_hidden_layer_and_output_layer_weights, ) ) return self.layer_between_second_hidden_layer_and_output def back_propagation(self) -> None: """ Function for fine-tuning the weights of the neural net based on the error rate obtained in the previous epoch (i.e., iteration). Updation is done using derivative of sogmoid activation function. >>> input_val = numpy.array(([0, 0, 0], [0, 0, 0], [0, 0, 0]), dtype=float) >>> output_val = numpy.array(([0], [0], [0]), dtype=float) >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val) >>> res = nn.feedforward() >>> nn.back_propagation() >>> updated_weights = nn.second_hidden_layer_and_output_layer_weights >>> (res == updated_weights).all() False """ updated_second_hidden_layer_and_output_layer_weights = numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T, 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output), ) updated_first_hidden_layer_and_second_hidden_layer_weights = numpy.dot( self.layer_between_input_and_first_hidden_layer.T, numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output), self.second_hidden_layer_and_output_layer_weights.T, ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ), ) updated_input_layer_and_first_hidden_layer_weights = numpy.dot( self.input_array.T, numpy.dot( numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output), self.second_hidden_layer_and_output_layer_weights.T, ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ), self.first_hidden_layer_and_second_hidden_layer_weights.T, ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer), ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def train(self, output: numpy.ndarray, iterations: int, give_loss: bool) -> None: """ Performs the feedforwarding and back propagation process for the given number of iterations. Every iteration will update the weights of neural network. output : real output values,required for calculating loss. iterations : number of times the weights are to be updated. give_loss : boolean value, If True then prints loss for each iteration, If False then nothing is printed >>> input_val = numpy.array(([0, 0, 0], [0, 1, 0], [0, 0, 1]), dtype=float) >>> output_val = numpy.array(([0], [1], [1]), dtype=float) >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val) >>> first_iteration_weights = nn.feedforward() >>> nn.back_propagation() >>> updated_weights = nn.second_hidden_layer_and_output_layer_weights >>> (first_iteration_weights == updated_weights).all() False """ for iteration in range(1, iterations + 1): self.output = self.feedforward() self.back_propagation() if give_loss: loss = numpy.mean(numpy.square(output - self.feedforward())) print(f"Iteration {iteration} Loss: {loss}") def predict(self, input_arr: numpy.ndarray) -> int: """ Predict's the output for the given input values using the trained neural network. The output value given by the model ranges in-between 0 and 1. The predict function returns 1 if the model value is greater than the threshold value else returns 0, as the real output values are in binary. >>> input_val = numpy.array(([0, 0, 0], [0, 1, 0], [0, 0, 1]), dtype=float) >>> output_val = numpy.array(([0], [1], [1]), dtype=float) >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val) >>> nn.train(output_val, 1000, False) >>> nn.predict([0,1,0]) in (0, 1) True """ # Input values for which the predictions are to be made. self.array = input_arr self.layer_between_input_and_first_hidden_layer = sigmoid( numpy.dot(self.array, self.input_layer_and_first_hidden_layer_weights) ) self.layer_between_first_hidden_layer_and_second_hidden_layer = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer, self.first_hidden_layer_and_second_hidden_layer_weights, ) ) self.layer_between_second_hidden_layer_and_output = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer, self.second_hidden_layer_and_output_layer_weights, ) ) return int(self.layer_between_second_hidden_layer_and_output > 0.6) def sigmoid(value: numpy.ndarray) -> numpy.ndarray: """ Applies sigmoid activation function. return normalized values >>> sigmoid(numpy.array(([1, 0, 2], [1, 0, 0]), dtype=numpy.float64)) array([[0.73105858, 0.5 , 0.88079708], [0.73105858, 0.5 , 0.5 ]]) """ return 1 / (1 + numpy.exp(-value)) def sigmoid_derivative(value: numpy.ndarray) -> numpy.ndarray: """ Provides the derivative value of the sigmoid function. returns derivative of the sigmoid value >>> sigmoid_derivative(numpy.array(([1, 0, 2], [1, 0, 0]), dtype=numpy.float64)) array([[ 0., 0., -2.], [ 0., 0., 0.]]) """ return (value) * (1 - (value)) def example() -> int: """ Example for "how to use the neural network class and use the respected methods for the desired output". Calls the TwoHiddenLayerNeuralNetwork class and provides the fixed input output values to the model. Model is trained for a fixed amount of iterations then the predict method is called. In this example the output is divided into 2 classes i.e. binary classification, the two classes are represented by '0' and '1'. >>> example() in (0, 1) True """ # Input values. test_input = numpy.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ), dtype=numpy.float64, ) # True output values for the given input values. output = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]), dtype=numpy.float64) # Calling neural network class. neural_network = TwoHiddenLayerNeuralNetwork( input_array=test_input, output_array=output ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=output, iterations=10, give_loss=False) return neural_network.predict(numpy.array(([1, 1, 1]), dtype=numpy.float64)) if __name__ == "__main__": example()
""" References: - http://neuralnetworksanddeeplearning.com/chap2.html (Backpropagation) - https://en.wikipedia.org/wiki/Sigmoid_function (Sigmoid activation function) - https://en.wikipedia.org/wiki/Feedforward_neural_network (Feedforward) """ import numpy class TwoHiddenLayerNeuralNetwork: def __init__(self, input_array: numpy.ndarray, output_array: numpy.ndarray) -> None: """ This function initializes the TwoHiddenLayerNeuralNetwork class with random weights for every layer and initializes predicted output with zeroes. input_array : input values for training the neural network (i.e training data) . output_array : expected output values of the given inputs. """ # Input values provided for training the model. self.input_array = input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. self.input_layer_and_first_hidden_layer_weights = numpy.random.rand( self.input_array.shape[1], 4 ) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. self.first_hidden_layer_and_second_hidden_layer_weights = numpy.random.rand( 4, 3 ) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. self.second_hidden_layer_and_output_layer_weights = numpy.random.rand(3, 1) # Real output values provided. self.output_array = output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. self.predicted_output = numpy.zeros(output_array.shape) def feedforward(self) -> numpy.ndarray: """ The information moves in only one direction i.e. forward from the input nodes, through the two hidden nodes and to the output nodes. There are no cycles or loops in the network. Return layer_between_second_hidden_layer_and_output (i.e the last layer of the neural network). >>> input_val = numpy.array(([0, 0, 0], [0, 0, 0], [0, 0, 0]), dtype=float) >>> output_val = numpy.array(([0], [0], [0]), dtype=float) >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val) >>> res = nn.feedforward() >>> array_sum = numpy.sum(res) >>> numpy.isnan(array_sum) False """ # Layer_between_input_and_first_hidden_layer is the layer connecting the # input nodes with the first hidden layer nodes. self.layer_between_input_and_first_hidden_layer = sigmoid( numpy.dot(self.input_array, self.input_layer_and_first_hidden_layer_weights) ) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. self.layer_between_first_hidden_layer_and_second_hidden_layer = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer, self.first_hidden_layer_and_second_hidden_layer_weights, ) ) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. self.layer_between_second_hidden_layer_and_output = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer, self.second_hidden_layer_and_output_layer_weights, ) ) return self.layer_between_second_hidden_layer_and_output def back_propagation(self) -> None: """ Function for fine-tuning the weights of the neural net based on the error rate obtained in the previous epoch (i.e., iteration). Updation is done using derivative of sogmoid activation function. >>> input_val = numpy.array(([0, 0, 0], [0, 0, 0], [0, 0, 0]), dtype=float) >>> output_val = numpy.array(([0], [0], [0]), dtype=float) >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val) >>> res = nn.feedforward() >>> nn.back_propagation() >>> updated_weights = nn.second_hidden_layer_and_output_layer_weights >>> (res == updated_weights).all() False """ updated_second_hidden_layer_and_output_layer_weights = numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T, 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output), ) updated_first_hidden_layer_and_second_hidden_layer_weights = numpy.dot( self.layer_between_input_and_first_hidden_layer.T, numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output), self.second_hidden_layer_and_output_layer_weights.T, ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ), ) updated_input_layer_and_first_hidden_layer_weights = numpy.dot( self.input_array.T, numpy.dot( numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output), self.second_hidden_layer_and_output_layer_weights.T, ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ), self.first_hidden_layer_and_second_hidden_layer_weights.T, ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer), ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def train(self, output: numpy.ndarray, iterations: int, give_loss: bool) -> None: """ Performs the feedforwarding and back propagation process for the given number of iterations. Every iteration will update the weights of neural network. output : real output values,required for calculating loss. iterations : number of times the weights are to be updated. give_loss : boolean value, If True then prints loss for each iteration, If False then nothing is printed >>> input_val = numpy.array(([0, 0, 0], [0, 1, 0], [0, 0, 1]), dtype=float) >>> output_val = numpy.array(([0], [1], [1]), dtype=float) >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val) >>> first_iteration_weights = nn.feedforward() >>> nn.back_propagation() >>> updated_weights = nn.second_hidden_layer_and_output_layer_weights >>> (first_iteration_weights == updated_weights).all() False """ for iteration in range(1, iterations + 1): self.output = self.feedforward() self.back_propagation() if give_loss: loss = numpy.mean(numpy.square(output - self.feedforward())) print(f"Iteration {iteration} Loss: {loss}") def predict(self, input_arr: numpy.ndarray) -> int: """ Predict's the output for the given input values using the trained neural network. The output value given by the model ranges in-between 0 and 1. The predict function returns 1 if the model value is greater than the threshold value else returns 0, as the real output values are in binary. >>> input_val = numpy.array(([0, 0, 0], [0, 1, 0], [0, 0, 1]), dtype=float) >>> output_val = numpy.array(([0], [1], [1]), dtype=float) >>> nn = TwoHiddenLayerNeuralNetwork(input_val, output_val) >>> nn.train(output_val, 1000, False) >>> nn.predict([0,1,0]) in (0, 1) True """ # Input values for which the predictions are to be made. self.array = input_arr self.layer_between_input_and_first_hidden_layer = sigmoid( numpy.dot(self.array, self.input_layer_and_first_hidden_layer_weights) ) self.layer_between_first_hidden_layer_and_second_hidden_layer = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer, self.first_hidden_layer_and_second_hidden_layer_weights, ) ) self.layer_between_second_hidden_layer_and_output = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer, self.second_hidden_layer_and_output_layer_weights, ) ) return int(self.layer_between_second_hidden_layer_and_output > 0.6) def sigmoid(value: numpy.ndarray) -> numpy.ndarray: """ Applies sigmoid activation function. return normalized values >>> sigmoid(numpy.array(([1, 0, 2], [1, 0, 0]), dtype=numpy.float64)) array([[0.73105858, 0.5 , 0.88079708], [0.73105858, 0.5 , 0.5 ]]) """ return 1 / (1 + numpy.exp(-value)) def sigmoid_derivative(value: numpy.ndarray) -> numpy.ndarray: """ Provides the derivative value of the sigmoid function. returns derivative of the sigmoid value >>> sigmoid_derivative(numpy.array(([1, 0, 2], [1, 0, 0]), dtype=numpy.float64)) array([[ 0., 0., -2.], [ 0., 0., 0.]]) """ return (value) * (1 - (value)) def example() -> int: """ Example for "how to use the neural network class and use the respected methods for the desired output". Calls the TwoHiddenLayerNeuralNetwork class and provides the fixed input output values to the model. Model is trained for a fixed amount of iterations then the predict method is called. In this example the output is divided into 2 classes i.e. binary classification, the two classes are represented by '0' and '1'. >>> example() in (0, 1) True """ # Input values. test_input = numpy.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ), dtype=numpy.float64, ) # True output values for the given input values. output = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]), dtype=numpy.float64) # Calling neural network class. neural_network = TwoHiddenLayerNeuralNetwork( input_array=test_input, output_array=output ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=output, iterations=10, give_loss=False) return neural_network.predict(numpy.array(([1, 1, 1]), dtype=numpy.float64)) if __name__ == "__main__": example()
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
### Describe your change: * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Contributing guidelines ## Before contributing Welcome to [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python)! Before sending your pull requests, make sure that you __read the whole guidelines__. If you have any doubt on the contributing guide, please feel free to [state it clearly in an issue](https://github.com/TheAlgorithms/Python/issues/new) or ask the community in [Gitter](https://gitter.im/TheAlgorithms/community). ## Contributing ### Contributor We are very happy that you are considering implementing algorithms and data structures for others! This repository is referenced and used by learners from all over the globe. Being one of our contributors, you agree and confirm that: - You did your work - no plagiarism allowed - Any plagiarized work will not be merged. - Your work will be distributed under [MIT License](LICENSE.md) once your pull request is merged - Your submitted work fulfils or mostly fulfils our styles and standards __New implementation__ is welcome! For example, new solutions for a problem, different representations for a graph data structure or algorithm designs with different complexity but __identical implementation__ of an existing implementation is not allowed. Please check whether the solution is already implemented or not before submitting your pull request. __Improving comments__ and __writing proper tests__ are also highly welcome. ### Contribution We appreciate any contribution, from fixing a grammar mistake in a comment to implementing complex algorithms. Please read this section if you are contributing your work. Your contribution will be tested by our [automated testing on GitHub Actions](https://github.com/TheAlgorithms/Python/actions) to save time and mental energy. After you have submitted your pull request, you should see the GitHub Actions tests start to run at the bottom of your submission page. If those tests fail, then click on the ___details___ button try to read through the GitHub Actions output to understand the failure. If you do not understand, please leave a comment on your submission page and a community member will try to help. Please help us keep our issue list small by adding fixes: #{$ISSUE_NO} to the commit message of pull requests that resolve open issues. GitHub will use this tag to auto-close the issue when the PR is merged. #### What is an Algorithm? An Algorithm is one or more functions (or classes) that: * take one or more inputs, * perform some internal calculations or data manipulations, * return one or more outputs, * have minimal side effects (Ex. `print()`, `plot()`, `read()`, `write()`). Algorithms should be packaged in a way that would make it easy for readers to put them into larger programs. Algorithms should: * have intuitive class and function names that make their purpose clear to readers * use Python naming conventions and intuitive variable names to ease comprehension * be flexible to take different input values * have Python type hints for their input parameters and return values * raise Python exceptions (`ValueError`, etc.) on erroneous input values * have docstrings with clear explanations and/or URLs to source materials * contain doctests that test both valid and erroneous input values * return all calculation results instead of printing or plotting them Algorithms in this repo should not be how-to examples for existing Python packages. Instead, they should perform internal calculations or manipulations to convert input values into different output values. Those calculations or manipulations can use data types, classes, or functions of existing Python packages but each algorithm in this repo should add unique value. #### Pre-commit plugin Use [pre-commit](https://pre-commit.com/#installation) to automatically format your code to match our coding style: ```bash python3 -m pip install pre-commit # only required the first time pre-commit install ``` That's it! The plugin will run every time you commit any changes. If there are any errors found during the run, fix them and commit those changes. You can even run the plugin manually on all files: ```bash pre-commit run --all-files --show-diff-on-failure ``` #### Coding Style We want your work to be readable by others; therefore, we encourage you to note the following: - Please write in Python 3.11+. For instance: `print()` is a function in Python 3 so `print "Hello"` will *not* work but `print("Hello")` will. - Please focus hard on the naming of functions, classes, and variables. Help your reader by using __descriptive names__ that can help you to remove redundant comments. - Single letter variable names are *old school* so please avoid them unless their life only spans a few lines. - Expand acronyms because `gcd()` is hard to understand but `greatest_common_divisor()` is not. - Please follow the [Python Naming Conventions](https://pep8.org/#prescriptive-naming-conventions) so variable_names and function_names should be lower_case, CONSTANTS in UPPERCASE, ClassNames should be CamelCase, etc. - We encourage the use of Python [f-strings](https://realpython.com/python-f-strings/#f-strings-a-new-and-improved-way-to-format-strings-in-python) where they make the code easier to read. - Please consider running [__psf/black__](https://github.com/python/black) on your Python file(s) before submitting your pull request. This is not yet a requirement but it does make your code more readable and automatically aligns it with much of [PEP 8](https://www.python.org/dev/peps/pep-0008/). There are other code formatters (autopep8, yapf) but the __black__ formatter is now hosted by the Python Software Foundation. To use it, ```bash python3 -m pip install black # only required the first time black . ``` - All submissions will need to pass the test `ruff .` before they will be accepted so if possible, try this test locally on your Python file(s) before submitting your pull request. ```bash python3 -m pip install ruff # only required the first time ruff . ``` - Original code submission require docstrings or comments to describe your work. - More on docstrings and comments: If you used a Wikipedia article or some other source material to create your algorithm, please add the URL in a docstring or comment to help your reader. The following are considered to be bad and may be requested to be improved: ```python x = x + 2 # increased by 2 ``` This is too trivial. Comments are expected to be explanatory. For comments, you can write them above, on or below a line of code, as long as you are consistent within the same piece of code. We encourage you to put docstrings inside your functions but please pay attention to the indentation of docstrings. The following is a good example: ```python def sum_ab(a, b): """ Return the sum of two integers a and b. """ return a + b ``` - Write tests (especially [__doctests__](https://docs.python.org/3/library/doctest.html)) to illustrate and verify your work. We highly encourage the use of _doctests on all functions_. ```python def sum_ab(a, b): """ Return the sum of two integers a and b >>> sum_ab(2, 2) 4 >>> sum_ab(-2, 3) 1 >>> sum_ab(4.9, 5.1) 10.0 """ return a + b ``` These doctests will be run by pytest as part of our automated testing so please try to run your doctests locally and make sure that they are found and pass: ```bash python3 -m doctest -v my_submission.py ``` The use of the Python builtin `input()` function is __not__ encouraged: ```python input('Enter your input:') # Or even worse... input = eval(input("Enter your input: ")) ``` However, if your code uses `input()` then we encourage you to gracefully deal with leading and trailing whitespace in user input by adding `.strip()` as in: ```python starting_value = int(input("Please enter a starting value: ").strip()) ``` The use of [Python type hints](https://docs.python.org/3/library/typing.html) is encouraged for function parameters and return values. Our automated testing will run [mypy](http://mypy-lang.org) so run that locally before making your submission. ```python def sum_ab(a: int, b: int) -> int: return a + b ``` Instructions on how to install mypy can be found [here](https://github.com/python/mypy). Please use the command `mypy --ignore-missing-imports .` to test all files or `mypy --ignore-missing-imports path/to/file.py` to test a specific file. - [__List comprehensions and generators__](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) are preferred over the use of `lambda`, `map`, `filter`, `reduce` but the important thing is to demonstrate the power of Python in code that is easy to read and maintain. - Avoid importing external libraries for basic algorithms. Only use those libraries for complicated algorithms. - If you need a third-party module that is not in the file __requirements.txt__, please add it to that file as part of your submission. #### Other Requirements for Submissions - If you are submitting code in the `project_euler/` directory, please also read [the dedicated Guideline](https://github.com/TheAlgorithms/Python/blob/master/project_euler/README.md) before contributing to our Project Euler library. - The file extension for code files should be `.py`. Jupyter Notebooks should be submitted to [TheAlgorithms/Jupyter](https://github.com/TheAlgorithms/Jupyter). - Strictly use snake_case (underscore_separated) in your file_name, as it will be easy to parse in future using scripts. - Please avoid creating new directories if at all possible. Try to fit your work into the existing directory structure. - If possible, follow the standard *within* the folder you are submitting to. - If you have modified/added code work, make sure the code compiles before submitting. - If you have modified/added documentation work, ensure your language is concise and contains no grammar errors. - Do not update the README.md or DIRECTORY.md file which will be periodically autogenerated by our GitHub Actions processes. - Add a corresponding explanation to [Algorithms-Explanation](https://github.com/TheAlgorithms/Algorithms-Explanation) (Optional but recommended). - All submissions will be tested with [__mypy__](http://www.mypy-lang.org) so we encourage you to add [__Python type hints__](https://docs.python.org/3/library/typing.html) where it makes sense to do so. - Most importantly, - __Be consistent in the use of these guidelines when submitting.__ - __Join__ us on [Discord](https://discord.com/invite/c7MnfGFGa6) and [Gitter](https://gitter.im/TheAlgorithms/community) __now!__ - Happy coding! Writer [@poyea](https://github.com/poyea), Jun 2019.
# Contributing guidelines ## Before contributing Welcome to [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python)! Before sending your pull requests, make sure that you __read the whole guidelines__. If you have any doubt on the contributing guide, please feel free to [state it clearly in an issue](https://github.com/TheAlgorithms/Python/issues/new) or ask the community in [Gitter](https://gitter.im/TheAlgorithms/community). ## Contributing ### Contributor We are very happy that you are considering implementing algorithms and data structures for others! This repository is referenced and used by learners from all over the globe. Being one of our contributors, you agree and confirm that: - You did your work - no plagiarism allowed - Any plagiarized work will not be merged. - Your work will be distributed under [MIT License](LICENSE.md) once your pull request is merged - Your submitted work fulfils or mostly fulfils our styles and standards __New implementation__ is welcome! For example, new solutions for a problem, different representations for a graph data structure or algorithm designs with different complexity but __identical implementation__ of an existing implementation is not allowed. Please check whether the solution is already implemented or not before submitting your pull request. __Improving comments__ and __writing proper tests__ are also highly welcome. ### Contribution We appreciate any contribution, from fixing a grammar mistake in a comment to implementing complex algorithms. Please read this section if you are contributing your work. Your contribution will be tested by our [automated testing on GitHub Actions](https://github.com/TheAlgorithms/Python/actions) to save time and mental energy. After you have submitted your pull request, you should see the GitHub Actions tests start to run at the bottom of your submission page. If those tests fail, then click on the ___details___ button try to read through the GitHub Actions output to understand the failure. If you do not understand, please leave a comment on your submission page and a community member will try to help. Please help us keep our issue list small by adding `Fixes #{$ISSUE_NUMBER}` to the description of pull requests that resolve open issues. For example, if your pull request fixes issue #10, then please add the following to its description: ``` Fixes #10 ``` GitHub will use this tag to [auto-close the issue](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) if and when the PR is merged. #### What is an Algorithm? An Algorithm is one or more functions (or classes) that: * take one or more inputs, * perform some internal calculations or data manipulations, * return one or more outputs, * have minimal side effects (Ex. `print()`, `plot()`, `read()`, `write()`). Algorithms should be packaged in a way that would make it easy for readers to put them into larger programs. Algorithms should: * have intuitive class and function names that make their purpose clear to readers * use Python naming conventions and intuitive variable names to ease comprehension * be flexible to take different input values * have Python type hints for their input parameters and return values * raise Python exceptions (`ValueError`, etc.) on erroneous input values * have docstrings with clear explanations and/or URLs to source materials * contain doctests that test both valid and erroneous input values * return all calculation results instead of printing or plotting them Algorithms in this repo should not be how-to examples for existing Python packages. Instead, they should perform internal calculations or manipulations to convert input values into different output values. Those calculations or manipulations can use data types, classes, or functions of existing Python packages but each algorithm in this repo should add unique value. #### Pre-commit plugin Use [pre-commit](https://pre-commit.com/#installation) to automatically format your code to match our coding style: ```bash python3 -m pip install pre-commit # only required the first time pre-commit install ``` That's it! The plugin will run every time you commit any changes. If there are any errors found during the run, fix them and commit those changes. You can even run the plugin manually on all files: ```bash pre-commit run --all-files --show-diff-on-failure ``` #### Coding Style We want your work to be readable by others; therefore, we encourage you to note the following: - Please write in Python 3.11+. For instance: `print()` is a function in Python 3 so `print "Hello"` will *not* work but `print("Hello")` will. - Please focus hard on the naming of functions, classes, and variables. Help your reader by using __descriptive names__ that can help you to remove redundant comments. - Single letter variable names are *old school* so please avoid them unless their life only spans a few lines. - Expand acronyms because `gcd()` is hard to understand but `greatest_common_divisor()` is not. - Please follow the [Python Naming Conventions](https://pep8.org/#prescriptive-naming-conventions) so variable_names and function_names should be lower_case, CONSTANTS in UPPERCASE, ClassNames should be CamelCase, etc. - We encourage the use of Python [f-strings](https://realpython.com/python-f-strings/#f-strings-a-new-and-improved-way-to-format-strings-in-python) where they make the code easier to read. - Please consider running [__psf/black__](https://github.com/python/black) on your Python file(s) before submitting your pull request. This is not yet a requirement but it does make your code more readable and automatically aligns it with much of [PEP 8](https://www.python.org/dev/peps/pep-0008/). There are other code formatters (autopep8, yapf) but the __black__ formatter is now hosted by the Python Software Foundation. To use it, ```bash python3 -m pip install black # only required the first time black . ``` - All submissions will need to pass the test `ruff .` before they will be accepted so if possible, try this test locally on your Python file(s) before submitting your pull request. ```bash python3 -m pip install ruff # only required the first time ruff . ``` - Original code submission require docstrings or comments to describe your work. - More on docstrings and comments: If you used a Wikipedia article or some other source material to create your algorithm, please add the URL in a docstring or comment to help your reader. The following are considered to be bad and may be requested to be improved: ```python x = x + 2 # increased by 2 ``` This is too trivial. Comments are expected to be explanatory. For comments, you can write them above, on or below a line of code, as long as you are consistent within the same piece of code. We encourage you to put docstrings inside your functions but please pay attention to the indentation of docstrings. The following is a good example: ```python def sum_ab(a, b): """ Return the sum of two integers a and b. """ return a + b ``` - Write tests (especially [__doctests__](https://docs.python.org/3/library/doctest.html)) to illustrate and verify your work. We highly encourage the use of _doctests on all functions_. ```python def sum_ab(a, b): """ Return the sum of two integers a and b >>> sum_ab(2, 2) 4 >>> sum_ab(-2, 3) 1 >>> sum_ab(4.9, 5.1) 10.0 """ return a + b ``` These doctests will be run by pytest as part of our automated testing so please try to run your doctests locally and make sure that they are found and pass: ```bash python3 -m doctest -v my_submission.py ``` The use of the Python builtin `input()` function is __not__ encouraged: ```python input('Enter your input:') # Or even worse... input = eval(input("Enter your input: ")) ``` However, if your code uses `input()` then we encourage you to gracefully deal with leading and trailing whitespace in user input by adding `.strip()` as in: ```python starting_value = int(input("Please enter a starting value: ").strip()) ``` The use of [Python type hints](https://docs.python.org/3/library/typing.html) is encouraged for function parameters and return values. Our automated testing will run [mypy](http://mypy-lang.org) so run that locally before making your submission. ```python def sum_ab(a: int, b: int) -> int: return a + b ``` Instructions on how to install mypy can be found [here](https://github.com/python/mypy). Please use the command `mypy --ignore-missing-imports .` to test all files or `mypy --ignore-missing-imports path/to/file.py` to test a specific file. - [__List comprehensions and generators__](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) are preferred over the use of `lambda`, `map`, `filter`, `reduce` but the important thing is to demonstrate the power of Python in code that is easy to read and maintain. - Avoid importing external libraries for basic algorithms. Only use those libraries for complicated algorithms. - If you need a third-party module that is not in the file __requirements.txt__, please add it to that file as part of your submission. #### Other Requirements for Submissions - If you are submitting code in the `project_euler/` directory, please also read [the dedicated Guideline](https://github.com/TheAlgorithms/Python/blob/master/project_euler/README.md) before contributing to our Project Euler library. - The file extension for code files should be `.py`. Jupyter Notebooks should be submitted to [TheAlgorithms/Jupyter](https://github.com/TheAlgorithms/Jupyter). - Strictly use snake_case (underscore_separated) in your file_name, as it will be easy to parse in future using scripts. - Please avoid creating new directories if at all possible. Try to fit your work into the existing directory structure. - If possible, follow the standard *within* the folder you are submitting to. - If you have modified/added code work, make sure the code compiles before submitting. - If you have modified/added documentation work, ensure your language is concise and contains no grammar errors. - Do not update the README.md or DIRECTORY.md file which will be periodically autogenerated by our GitHub Actions processes. - Add a corresponding explanation to [Algorithms-Explanation](https://github.com/TheAlgorithms/Algorithms-Explanation) (Optional but recommended). - All submissions will be tested with [__mypy__](http://www.mypy-lang.org) so we encourage you to add [__Python type hints__](https://docs.python.org/3/library/typing.html) where it makes sense to do so. - Most importantly, - __Be consistent in the use of these guidelines when submitting.__ - __Join__ us on [Discord](https://discord.com/invite/c7MnfGFGa6) and [Gitter](https://gitter.im/TheAlgorithms/community) __now!__ - Happy coding! Writer [@poyea](https://github.com/poyea), Jun 2019.
1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
## Arithmetic Analysis * [Bisection](arithmetic_analysis/bisection.py) * [Gaussian Elimination](arithmetic_analysis/gaussian_elimination.py) * [In Static Equilibrium](arithmetic_analysis/in_static_equilibrium.py) * [Intersection](arithmetic_analysis/intersection.py) * [Jacobi Iteration Method](arithmetic_analysis/jacobi_iteration_method.py) * [Lu Decomposition](arithmetic_analysis/lu_decomposition.py) * [Newton Forward Interpolation](arithmetic_analysis/newton_forward_interpolation.py) * [Newton Method](arithmetic_analysis/newton_method.py) * [Newton Raphson](arithmetic_analysis/newton_raphson.py) * [Newton Raphson New](arithmetic_analysis/newton_raphson_new.py) * [Secant Method](arithmetic_analysis/secant_method.py) ## Audio Filters * [Butterworth Filter](audio_filters/butterworth_filter.py) * [Iir Filter](audio_filters/iir_filter.py) * [Show Response](audio_filters/show_response.py) ## Backtracking * [All Combinations](backtracking/all_combinations.py) * [All Permutations](backtracking/all_permutations.py) * [All Subsequences](backtracking/all_subsequences.py) * [Coloring](backtracking/coloring.py) * [Combination Sum](backtracking/combination_sum.py) * [Hamiltonian Cycle](backtracking/hamiltonian_cycle.py) * [Knight Tour](backtracking/knight_tour.py) * [Minimax](backtracking/minimax.py) * [Minmax](backtracking/minmax.py) * [N Queens](backtracking/n_queens.py) * [N Queens Math](backtracking/n_queens_math.py) * [Rat In Maze](backtracking/rat_in_maze.py) * [Sudoku](backtracking/sudoku.py) * [Sum Of Subsets](backtracking/sum_of_subsets.py) * [Word Search](backtracking/word_search.py) ## Bit Manipulation * [Binary And Operator](bit_manipulation/binary_and_operator.py) * [Binary Count Setbits](bit_manipulation/binary_count_setbits.py) * [Binary Count Trailing Zeros](bit_manipulation/binary_count_trailing_zeros.py) * [Binary Or Operator](bit_manipulation/binary_or_operator.py) * [Binary Shifts](bit_manipulation/binary_shifts.py) * [Binary Twos Complement](bit_manipulation/binary_twos_complement.py) * [Binary Xor Operator](bit_manipulation/binary_xor_operator.py) * [Count 1S Brian Kernighan Method](bit_manipulation/count_1s_brian_kernighan_method.py) * [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py) * [Gray Code Sequence](bit_manipulation/gray_code_sequence.py) * [Highest Set Bit](bit_manipulation/highest_set_bit.py) * [Index Of Rightmost Set Bit](bit_manipulation/index_of_rightmost_set_bit.py) * [Is Even](bit_manipulation/is_even.py) * [Is Power Of Two](bit_manipulation/is_power_of_two.py) * [Numbers Different Signs](bit_manipulation/numbers_different_signs.py) * [Reverse Bits](bit_manipulation/reverse_bits.py) * [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py) ## Blockchain * [Chinese Remainder Theorem](blockchain/chinese_remainder_theorem.py) * [Diophantine Equation](blockchain/diophantine_equation.py) * [Modular Division](blockchain/modular_division.py) ## Boolean Algebra * [And Gate](boolean_algebra/and_gate.py) * [Nand Gate](boolean_algebra/nand_gate.py) * [Norgate](boolean_algebra/norgate.py) * [Not Gate](boolean_algebra/not_gate.py) * [Or Gate](boolean_algebra/or_gate.py) * [Quine Mc Cluskey](boolean_algebra/quine_mc_cluskey.py) * [Xnor Gate](boolean_algebra/xnor_gate.py) * [Xor Gate](boolean_algebra/xor_gate.py) ## Cellular Automata * [Conways Game Of Life](cellular_automata/conways_game_of_life.py) * [Game Of Life](cellular_automata/game_of_life.py) * [Nagel Schrekenberg](cellular_automata/nagel_schrekenberg.py) * [One Dimensional](cellular_automata/one_dimensional.py) ## Ciphers * [A1Z26](ciphers/a1z26.py) * [Affine Cipher](ciphers/affine_cipher.py) * [Atbash](ciphers/atbash.py) * [Autokey](ciphers/autokey.py) * [Baconian Cipher](ciphers/baconian_cipher.py) * [Base16](ciphers/base16.py) * [Base32](ciphers/base32.py) * [Base64](ciphers/base64.py) * [Base85](ciphers/base85.py) * [Beaufort Cipher](ciphers/beaufort_cipher.py) * [Bifid](ciphers/bifid.py) * [Brute Force Caesar Cipher](ciphers/brute_force_caesar_cipher.py) * [Caesar Cipher](ciphers/caesar_cipher.py) * [Cryptomath Module](ciphers/cryptomath_module.py) * [Decrypt Caesar With Chi Squared](ciphers/decrypt_caesar_with_chi_squared.py) * [Deterministic Miller Rabin](ciphers/deterministic_miller_rabin.py) * [Diffie](ciphers/diffie.py) * [Diffie Hellman](ciphers/diffie_hellman.py) * [Elgamal Key Generator](ciphers/elgamal_key_generator.py) * [Enigma Machine2](ciphers/enigma_machine2.py) * [Hill Cipher](ciphers/hill_cipher.py) * [Mixed Keyword Cypher](ciphers/mixed_keyword_cypher.py) * [Mono Alphabetic Ciphers](ciphers/mono_alphabetic_ciphers.py) * [Morse Code](ciphers/morse_code.py) * [Onepad Cipher](ciphers/onepad_cipher.py) * [Playfair Cipher](ciphers/playfair_cipher.py) * [Polybius](ciphers/polybius.py) * [Porta Cipher](ciphers/porta_cipher.py) * [Rabin Miller](ciphers/rabin_miller.py) * [Rail Fence Cipher](ciphers/rail_fence_cipher.py) * [Rot13](ciphers/rot13.py) * [Rsa Cipher](ciphers/rsa_cipher.py) * [Rsa Factorization](ciphers/rsa_factorization.py) * [Rsa Key Generator](ciphers/rsa_key_generator.py) * [Shuffled Shift Cipher](ciphers/shuffled_shift_cipher.py) * [Simple Keyword Cypher](ciphers/simple_keyword_cypher.py) * [Simple Substitution Cipher](ciphers/simple_substitution_cipher.py) * [Trafid Cipher](ciphers/trafid_cipher.py) * [Transposition Cipher](ciphers/transposition_cipher.py) * [Transposition Cipher Encrypt Decrypt File](ciphers/transposition_cipher_encrypt_decrypt_file.py) * [Vigenere Cipher](ciphers/vigenere_cipher.py) * [Xor Cipher](ciphers/xor_cipher.py) ## Compression * [Burrows Wheeler](compression/burrows_wheeler.py) * [Huffman](compression/huffman.py) * [Lempel Ziv](compression/lempel_ziv.py) * [Lempel Ziv Decompress](compression/lempel_ziv_decompress.py) * [Lz77](compression/lz77.py) * [Peak Signal To Noise Ratio](compression/peak_signal_to_noise_ratio.py) * [Run Length Encoding](compression/run_length_encoding.py) ## Computer Vision * [Cnn Classification](computer_vision/cnn_classification.py) * [Flip Augmentation](computer_vision/flip_augmentation.py) * [Harris Corner](computer_vision/harris_corner.py) * [Horn Schunck](computer_vision/horn_schunck.py) * [Mean Threshold](computer_vision/mean_threshold.py) * [Mosaic Augmentation](computer_vision/mosaic_augmentation.py) * [Pooling Functions](computer_vision/pooling_functions.py) ## Conversions * [Astronomical Length Scale Conversion](conversions/astronomical_length_scale_conversion.py) * [Binary To Decimal](conversions/binary_to_decimal.py) * [Binary To Hexadecimal](conversions/binary_to_hexadecimal.py) * [Binary To Octal](conversions/binary_to_octal.py) * [Decimal To Any](conversions/decimal_to_any.py) * [Decimal To Binary](conversions/decimal_to_binary.py) * [Decimal To Binary Recursion](conversions/decimal_to_binary_recursion.py) * [Decimal To Hexadecimal](conversions/decimal_to_hexadecimal.py) * [Decimal To Octal](conversions/decimal_to_octal.py) * [Excel Title To Column](conversions/excel_title_to_column.py) * [Hex To Bin](conversions/hex_to_bin.py) * [Hexadecimal To Decimal](conversions/hexadecimal_to_decimal.py) * [Length Conversion](conversions/length_conversion.py) * [Molecular Chemistry](conversions/molecular_chemistry.py) * [Octal To Decimal](conversions/octal_to_decimal.py) * [Prefix Conversions](conversions/prefix_conversions.py) * [Prefix Conversions String](conversions/prefix_conversions_string.py) * [Pressure Conversions](conversions/pressure_conversions.py) * [Rgb Hsv Conversion](conversions/rgb_hsv_conversion.py) * [Roman Numerals](conversions/roman_numerals.py) * [Speed Conversions](conversions/speed_conversions.py) * [Temperature Conversions](conversions/temperature_conversions.py) * [Volume Conversions](conversions/volume_conversions.py) * [Weight Conversion](conversions/weight_conversion.py) ## Data Structures * Arrays * [Permutations](data_structures/arrays/permutations.py) * [Prefix Sum](data_structures/arrays/prefix_sum.py) * [Product Sum Array](data_structures/arrays/product_sum.py) * Binary Tree * [Avl Tree](data_structures/binary_tree/avl_tree.py) * [Basic Binary Tree](data_structures/binary_tree/basic_binary_tree.py) * [Binary Search Tree](data_structures/binary_tree/binary_search_tree.py) * [Binary Search Tree Recursive](data_structures/binary_tree/binary_search_tree_recursive.py) * [Binary Tree Mirror](data_structures/binary_tree/binary_tree_mirror.py) * [Binary Tree Node Sum](data_structures/binary_tree/binary_tree_node_sum.py) * [Binary Tree Path Sum](data_structures/binary_tree/binary_tree_path_sum.py) * [Binary Tree Traversals](data_structures/binary_tree/binary_tree_traversals.py) * [Diff Views Of Binary Tree](data_structures/binary_tree/diff_views_of_binary_tree.py) * [Distribute Coins](data_structures/binary_tree/distribute_coins.py) * [Fenwick Tree](data_structures/binary_tree/fenwick_tree.py) * [Inorder Tree Traversal 2022](data_structures/binary_tree/inorder_tree_traversal_2022.py) * [Is Bst](data_structures/binary_tree/is_bst.py) * [Lazy Segment Tree](data_structures/binary_tree/lazy_segment_tree.py) * [Lowest Common Ancestor](data_structures/binary_tree/lowest_common_ancestor.py) * [Maximum Fenwick Tree](data_structures/binary_tree/maximum_fenwick_tree.py) * [Merge Two Binary Trees](data_structures/binary_tree/merge_two_binary_trees.py) * [Non Recursive Segment Tree](data_structures/binary_tree/non_recursive_segment_tree.py) * [Number Of Possible Binary Trees](data_structures/binary_tree/number_of_possible_binary_trees.py) * [Red Black Tree](data_structures/binary_tree/red_black_tree.py) * [Segment Tree](data_structures/binary_tree/segment_tree.py) * [Segment Tree Other](data_structures/binary_tree/segment_tree_other.py) * [Treap](data_structures/binary_tree/treap.py) * [Wavelet Tree](data_structures/binary_tree/wavelet_tree.py) * Disjoint Set * [Alternate Disjoint Set](data_structures/disjoint_set/alternate_disjoint_set.py) * [Disjoint Set](data_structures/disjoint_set/disjoint_set.py) * Hashing * [Bloom Filter](data_structures/hashing/bloom_filter.py) * [Double Hash](data_structures/hashing/double_hash.py) * [Hash Map](data_structures/hashing/hash_map.py) * [Hash Table](data_structures/hashing/hash_table.py) * [Hash Table With Linked List](data_structures/hashing/hash_table_with_linked_list.py) * Number Theory * [Prime Numbers](data_structures/hashing/number_theory/prime_numbers.py) * [Quadratic Probing](data_structures/hashing/quadratic_probing.py) * Tests * [Test Hash Map](data_structures/hashing/tests/test_hash_map.py) * Heap * [Binomial Heap](data_structures/heap/binomial_heap.py) * [Heap](data_structures/heap/heap.py) * [Heap Generic](data_structures/heap/heap_generic.py) * [Max Heap](data_structures/heap/max_heap.py) * [Min Heap](data_structures/heap/min_heap.py) * [Randomized Heap](data_structures/heap/randomized_heap.py) * [Skew Heap](data_structures/heap/skew_heap.py) * Linked List * [Circular Linked List](data_structures/linked_list/circular_linked_list.py) * [Deque Doubly](data_structures/linked_list/deque_doubly.py) * [Doubly Linked List](data_structures/linked_list/doubly_linked_list.py) * [Doubly Linked List Two](data_structures/linked_list/doubly_linked_list_two.py) * [From Sequence](data_structures/linked_list/from_sequence.py) * [Has Loop](data_structures/linked_list/has_loop.py) * [Is Palindrome](data_structures/linked_list/is_palindrome.py) * [Merge Two Lists](data_structures/linked_list/merge_two_lists.py) * [Middle Element Of Linked List](data_structures/linked_list/middle_element_of_linked_list.py) * [Print Reverse](data_structures/linked_list/print_reverse.py) * [Singly Linked List](data_structures/linked_list/singly_linked_list.py) * [Skip List](data_structures/linked_list/skip_list.py) * [Swap Nodes](data_structures/linked_list/swap_nodes.py) * Queue * [Circular Queue](data_structures/queue/circular_queue.py) * [Circular Queue Linked List](data_structures/queue/circular_queue_linked_list.py) * [Double Ended Queue](data_structures/queue/double_ended_queue.py) * [Linked Queue](data_structures/queue/linked_queue.py) * [Priority Queue Using List](data_structures/queue/priority_queue_using_list.py) * [Queue By Two Stacks](data_structures/queue/queue_by_two_stacks.py) * [Queue On List](data_structures/queue/queue_on_list.py) * [Queue On Pseudo Stack](data_structures/queue/queue_on_pseudo_stack.py) * Stacks * [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py) * [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py) * [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py) * [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py) * [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py) * [Next Greater Element](data_structures/stacks/next_greater_element.py) * [Postfix Evaluation](data_structures/stacks/postfix_evaluation.py) * [Prefix Evaluation](data_structures/stacks/prefix_evaluation.py) * [Stack](data_structures/stacks/stack.py) * [Stack With Doubly Linked List](data_structures/stacks/stack_with_doubly_linked_list.py) * [Stack With Singly Linked List](data_structures/stacks/stack_with_singly_linked_list.py) * [Stock Span Problem](data_structures/stacks/stock_span_problem.py) * Trie * [Radix Tree](data_structures/trie/radix_tree.py) * [Trie](data_structures/trie/trie.py) ## Digital Image Processing * [Change Brightness](digital_image_processing/change_brightness.py) * [Change Contrast](digital_image_processing/change_contrast.py) * [Convert To Negative](digital_image_processing/convert_to_negative.py) * Dithering * [Burkes](digital_image_processing/dithering/burkes.py) * Edge Detection * [Canny](digital_image_processing/edge_detection/canny.py) * Filters * [Bilateral Filter](digital_image_processing/filters/bilateral_filter.py) * [Convolve](digital_image_processing/filters/convolve.py) * [Gabor Filter](digital_image_processing/filters/gabor_filter.py) * [Gaussian Filter](digital_image_processing/filters/gaussian_filter.py) * [Local Binary Pattern](digital_image_processing/filters/local_binary_pattern.py) * [Median Filter](digital_image_processing/filters/median_filter.py) * [Sobel Filter](digital_image_processing/filters/sobel_filter.py) * Histogram Equalization * [Histogram Stretch](digital_image_processing/histogram_equalization/histogram_stretch.py) * [Index Calculation](digital_image_processing/index_calculation.py) * Morphological Operations * [Dilation Operation](digital_image_processing/morphological_operations/dilation_operation.py) * [Erosion Operation](digital_image_processing/morphological_operations/erosion_operation.py) * Resize * [Resize](digital_image_processing/resize/resize.py) * Rotation * [Rotation](digital_image_processing/rotation/rotation.py) * [Sepia](digital_image_processing/sepia.py) * [Test Digital Image Processing](digital_image_processing/test_digital_image_processing.py) ## Divide And Conquer * [Closest Pair Of Points](divide_and_conquer/closest_pair_of_points.py) * [Convex Hull](divide_and_conquer/convex_hull.py) * [Heaps Algorithm](divide_and_conquer/heaps_algorithm.py) * [Heaps Algorithm Iterative](divide_and_conquer/heaps_algorithm_iterative.py) * [Inversions](divide_and_conquer/inversions.py) * [Kth Order Statistic](divide_and_conquer/kth_order_statistic.py) * [Max Difference Pair](divide_and_conquer/max_difference_pair.py) * [Max Subarray Sum](divide_and_conquer/max_subarray_sum.py) * [Mergesort](divide_and_conquer/mergesort.py) * [Peak](divide_and_conquer/peak.py) * [Power](divide_and_conquer/power.py) * [Strassen Matrix Multiplication](divide_and_conquer/strassen_matrix_multiplication.py) ## Dynamic Programming * [Abbreviation](dynamic_programming/abbreviation.py) * [All Construct](dynamic_programming/all_construct.py) * [Bitmask](dynamic_programming/bitmask.py) * [Catalan Numbers](dynamic_programming/catalan_numbers.py) * [Climbing Stairs](dynamic_programming/climbing_stairs.py) * [Combination Sum Iv](dynamic_programming/combination_sum_iv.py) * [Edit Distance](dynamic_programming/edit_distance.py) * [Factorial](dynamic_programming/factorial.py) * [Fast Fibonacci](dynamic_programming/fast_fibonacci.py) * [Fibonacci](dynamic_programming/fibonacci.py) * [Fizz Buzz](dynamic_programming/fizz_buzz.py) * [Floyd Warshall](dynamic_programming/floyd_warshall.py) * [Integer Partition](dynamic_programming/integer_partition.py) * [Iterating Through Submasks](dynamic_programming/iterating_through_submasks.py) * [K Means Clustering Tensorflow](dynamic_programming/k_means_clustering_tensorflow.py) * [Knapsack](dynamic_programming/knapsack.py) * [Longest Common Subsequence](dynamic_programming/longest_common_subsequence.py) * [Longest Common Substring](dynamic_programming/longest_common_substring.py) * [Longest Increasing Subsequence](dynamic_programming/longest_increasing_subsequence.py) * [Longest Increasing Subsequence O(Nlogn)](dynamic_programming/longest_increasing_subsequence_o(nlogn).py) * [Longest Sub Array](dynamic_programming/longest_sub_array.py) * [Matrix Chain Order](dynamic_programming/matrix_chain_order.py) * [Max Non Adjacent Sum](dynamic_programming/max_non_adjacent_sum.py) * [Max Product Subarray](dynamic_programming/max_product_subarray.py) * [Max Sub Array](dynamic_programming/max_sub_array.py) * [Max Sum Contiguous Subsequence](dynamic_programming/max_sum_contiguous_subsequence.py) * [Min Distance Up Bottom](dynamic_programming/min_distance_up_bottom.py) * [Minimum Coin Change](dynamic_programming/minimum_coin_change.py) * [Minimum Cost Path](dynamic_programming/minimum_cost_path.py) * [Minimum Partition](dynamic_programming/minimum_partition.py) * [Minimum Size Subarray Sum](dynamic_programming/minimum_size_subarray_sum.py) * [Minimum Squares To Represent A Number](dynamic_programming/minimum_squares_to_represent_a_number.py) * [Minimum Steps To One](dynamic_programming/minimum_steps_to_one.py) * [Minimum Tickets Cost](dynamic_programming/minimum_tickets_cost.py) * [Optimal Binary Search Tree](dynamic_programming/optimal_binary_search_tree.py) * [Palindrome Partitioning](dynamic_programming/palindrome_partitioning.py) * [Rod Cutting](dynamic_programming/rod_cutting.py) * [Subset Generation](dynamic_programming/subset_generation.py) * [Sum Of Subset](dynamic_programming/sum_of_subset.py) * [Viterbi](dynamic_programming/viterbi.py) * [Word Break](dynamic_programming/word_break.py) ## Electronics * [Apparent Power](electronics/apparent_power.py) * [Builtin Voltage](electronics/builtin_voltage.py) * [Carrier Concentration](electronics/carrier_concentration.py) * [Circular Convolution](electronics/circular_convolution.py) * [Coulombs Law](electronics/coulombs_law.py) * [Electric Conductivity](electronics/electric_conductivity.py) * [Electric Power](electronics/electric_power.py) * [Electrical Impedance](electronics/electrical_impedance.py) * [Ind Reactance](electronics/ind_reactance.py) * [Ohms Law](electronics/ohms_law.py) * [Real And Reactive Power](electronics/real_and_reactive_power.py) * [Resistor Equivalence](electronics/resistor_equivalence.py) * [Resonant Frequency](electronics/resonant_frequency.py) ## File Transfer * [Receive File](file_transfer/receive_file.py) * [Send File](file_transfer/send_file.py) * Tests * [Test Send File](file_transfer/tests/test_send_file.py) ## Financial * [Equated Monthly Installments](financial/equated_monthly_installments.py) * [Interest](financial/interest.py) * [Present Value](financial/present_value.py) * [Price Plus Tax](financial/price_plus_tax.py) ## Fractals * [Julia Sets](fractals/julia_sets.py) * [Koch Snowflake](fractals/koch_snowflake.py) * [Mandelbrot](fractals/mandelbrot.py) * [Sierpinski Triangle](fractals/sierpinski_triangle.py) ## Fuzzy Logic * [Fuzzy Operations](fuzzy_logic/fuzzy_operations.py) ## Genetic Algorithm * [Basic String](genetic_algorithm/basic_string.py) ## Geodesy * [Haversine Distance](geodesy/haversine_distance.py) * [Lamberts Ellipsoidal Distance](geodesy/lamberts_ellipsoidal_distance.py) ## Graphics * [Bezier Curve](graphics/bezier_curve.py) * [Vector3 For 2D Rendering](graphics/vector3_for_2d_rendering.py) ## Graphs * [A Star](graphs/a_star.py) * [Articulation Points](graphs/articulation_points.py) * [Basic Graphs](graphs/basic_graphs.py) * [Bellman Ford](graphs/bellman_ford.py) * [Bi Directional Dijkstra](graphs/bi_directional_dijkstra.py) * [Bidirectional A Star](graphs/bidirectional_a_star.py) * [Bidirectional Breadth First Search](graphs/bidirectional_breadth_first_search.py) * [Boruvka](graphs/boruvka.py) * [Breadth First Search](graphs/breadth_first_search.py) * [Breadth First Search 2](graphs/breadth_first_search_2.py) * [Breadth First Search Shortest Path](graphs/breadth_first_search_shortest_path.py) * [Breadth First Search Shortest Path 2](graphs/breadth_first_search_shortest_path_2.py) * [Breadth First Search Zero One Shortest Path](graphs/breadth_first_search_zero_one_shortest_path.py) * [Check Bipartite Graph Bfs](graphs/check_bipartite_graph_bfs.py) * [Check Bipartite Graph Dfs](graphs/check_bipartite_graph_dfs.py) * [Check Cycle](graphs/check_cycle.py) * [Connected Components](graphs/connected_components.py) * [Depth First Search](graphs/depth_first_search.py) * [Depth First Search 2](graphs/depth_first_search_2.py) * [Dijkstra](graphs/dijkstra.py) * [Dijkstra 2](graphs/dijkstra_2.py) * [Dijkstra Algorithm](graphs/dijkstra_algorithm.py) * [Dijkstra Alternate](graphs/dijkstra_alternate.py) * [Dinic](graphs/dinic.py) * [Directed And Undirected (Weighted) Graph](graphs/directed_and_undirected_(weighted)_graph.py) * [Edmonds Karp Multiple Source And Sink](graphs/edmonds_karp_multiple_source_and_sink.py) * [Eulerian Path And Circuit For Undirected Graph](graphs/eulerian_path_and_circuit_for_undirected_graph.py) * [Even Tree](graphs/even_tree.py) * [Finding Bridges](graphs/finding_bridges.py) * [Frequent Pattern Graph Miner](graphs/frequent_pattern_graph_miner.py) * [G Topological Sort](graphs/g_topological_sort.py) * [Gale Shapley Bigraph](graphs/gale_shapley_bigraph.py) * [Graph Adjacency List](graphs/graph_adjacency_list.py) * [Graph Adjacency Matrix](graphs/graph_adjacency_matrix.py) * [Graph List](graphs/graph_list.py) * [Graphs Floyd Warshall](graphs/graphs_floyd_warshall.py) * [Greedy Best First](graphs/greedy_best_first.py) * [Greedy Min Vertex Cover](graphs/greedy_min_vertex_cover.py) * [Kahns Algorithm Long](graphs/kahns_algorithm_long.py) * [Kahns Algorithm Topo](graphs/kahns_algorithm_topo.py) * [Karger](graphs/karger.py) * [Markov Chain](graphs/markov_chain.py) * [Matching Min Vertex Cover](graphs/matching_min_vertex_cover.py) * [Minimum Path Sum](graphs/minimum_path_sum.py) * [Minimum Spanning Tree Boruvka](graphs/minimum_spanning_tree_boruvka.py) * [Minimum Spanning Tree Kruskal](graphs/minimum_spanning_tree_kruskal.py) * [Minimum Spanning Tree Kruskal2](graphs/minimum_spanning_tree_kruskal2.py) * [Minimum Spanning Tree Prims](graphs/minimum_spanning_tree_prims.py) * [Minimum Spanning Tree Prims2](graphs/minimum_spanning_tree_prims2.py) * [Multi Heuristic Astar](graphs/multi_heuristic_astar.py) * [Page Rank](graphs/page_rank.py) * [Prim](graphs/prim.py) * [Random Graph Generator](graphs/random_graph_generator.py) * [Scc Kosaraju](graphs/scc_kosaraju.py) * [Strongly Connected Components](graphs/strongly_connected_components.py) * [Tarjans Scc](graphs/tarjans_scc.py) * Tests * [Test Min Spanning Tree Kruskal](graphs/tests/test_min_spanning_tree_kruskal.py) * [Test Min Spanning Tree Prim](graphs/tests/test_min_spanning_tree_prim.py) ## Greedy Methods * [Fractional Knapsack](greedy_methods/fractional_knapsack.py) * [Fractional Knapsack 2](greedy_methods/fractional_knapsack_2.py) * [Minimum Waiting Time](greedy_methods/minimum_waiting_time.py) * [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py) ## Hashes * [Adler32](hashes/adler32.py) * [Chaos Machine](hashes/chaos_machine.py) * [Djb2](hashes/djb2.py) * [Elf](hashes/elf.py) * [Enigma Machine](hashes/enigma_machine.py) * [Hamming Code](hashes/hamming_code.py) * [Luhn](hashes/luhn.py) * [Md5](hashes/md5.py) * [Sdbm](hashes/sdbm.py) * [Sha1](hashes/sha1.py) * [Sha256](hashes/sha256.py) ## Knapsack * [Greedy Knapsack](knapsack/greedy_knapsack.py) * [Knapsack](knapsack/knapsack.py) * [Recursive Approach Knapsack](knapsack/recursive_approach_knapsack.py) * Tests * [Test Greedy Knapsack](knapsack/tests/test_greedy_knapsack.py) * [Test Knapsack](knapsack/tests/test_knapsack.py) ## Linear Algebra * Src * [Conjugate Gradient](linear_algebra/src/conjugate_gradient.py) * [Lib](linear_algebra/src/lib.py) * [Polynom For Points](linear_algebra/src/polynom_for_points.py) * [Power Iteration](linear_algebra/src/power_iteration.py) * [Rank Of Matrix](linear_algebra/src/rank_of_matrix.py) * [Rayleigh Quotient](linear_algebra/src/rayleigh_quotient.py) * [Schur Complement](linear_algebra/src/schur_complement.py) * [Test Linear Algebra](linear_algebra/src/test_linear_algebra.py) * [Transformations 2D](linear_algebra/src/transformations_2d.py) ## Linear Programming * [Simplex](linear_programming/simplex.py) ## Machine Learning * [Astar](machine_learning/astar.py) * [Data Transformations](machine_learning/data_transformations.py) * [Decision Tree](machine_learning/decision_tree.py) * [Dimensionality Reduction](machine_learning/dimensionality_reduction.py) * Forecasting * [Run](machine_learning/forecasting/run.py) * [Gradient Descent](machine_learning/gradient_descent.py) * [K Means Clust](machine_learning/k_means_clust.py) * [K Nearest Neighbours](machine_learning/k_nearest_neighbours.py) * [Knn Sklearn](machine_learning/knn_sklearn.py) * [Linear Discriminant Analysis](machine_learning/linear_discriminant_analysis.py) * [Linear Regression](machine_learning/linear_regression.py) * Local Weighted Learning * [Local Weighted Learning](machine_learning/local_weighted_learning/local_weighted_learning.py) * [Logistic Regression](machine_learning/logistic_regression.py) * Lstm * [Lstm Prediction](machine_learning/lstm/lstm_prediction.py) * [Multilayer Perceptron Classifier](machine_learning/multilayer_perceptron_classifier.py) * [Polymonial Regression](machine_learning/polymonial_regression.py) * [Scoring Functions](machine_learning/scoring_functions.py) * [Self Organizing Map](machine_learning/self_organizing_map.py) * [Sequential Minimum Optimization](machine_learning/sequential_minimum_optimization.py) * [Similarity Search](machine_learning/similarity_search.py) * [Support Vector Machines](machine_learning/support_vector_machines.py) * [Word Frequency Functions](machine_learning/word_frequency_functions.py) * [Xgboost Classifier](machine_learning/xgboost_classifier.py) * [Xgboost Regressor](machine_learning/xgboost_regressor.py) ## Maths * [3N Plus 1](maths/3n_plus_1.py) * [Abs](maths/abs.py) * [Add](maths/add.py) * [Addition Without Arithmetic](maths/addition_without_arithmetic.py) * [Aliquot Sum](maths/aliquot_sum.py) * [Allocation Number](maths/allocation_number.py) * [Arc Length](maths/arc_length.py) * [Area](maths/area.py) * [Area Under Curve](maths/area_under_curve.py) * [Armstrong Numbers](maths/armstrong_numbers.py) * [Automorphic Number](maths/automorphic_number.py) * [Average Absolute Deviation](maths/average_absolute_deviation.py) * [Average Mean](maths/average_mean.py) * [Average Median](maths/average_median.py) * [Average Mode](maths/average_mode.py) * [Bailey Borwein Plouffe](maths/bailey_borwein_plouffe.py) * [Basic Maths](maths/basic_maths.py) * [Binary Exp Mod](maths/binary_exp_mod.py) * [Binary Exponentiation](maths/binary_exponentiation.py) * [Binary Exponentiation 2](maths/binary_exponentiation_2.py) * [Binary Exponentiation 3](maths/binary_exponentiation_3.py) * [Binomial Coefficient](maths/binomial_coefficient.py) * [Binomial Distribution](maths/binomial_distribution.py) * [Bisection](maths/bisection.py) * [Carmichael Number](maths/carmichael_number.py) * [Catalan Number](maths/catalan_number.py) * [Ceil](maths/ceil.py) * [Check Polygon](maths/check_polygon.py) * [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py) * [Collatz Sequence](maths/collatz_sequence.py) * [Combinations](maths/combinations.py) * [Decimal Isolate](maths/decimal_isolate.py) * [Decimal To Fraction](maths/decimal_to_fraction.py) * [Dodecahedron](maths/dodecahedron.py) * [Double Factorial Iterative](maths/double_factorial_iterative.py) * [Double Factorial Recursive](maths/double_factorial_recursive.py) * [Dual Number Automatic Differentiation](maths/dual_number_automatic_differentiation.py) * [Entropy](maths/entropy.py) * [Euclidean Distance](maths/euclidean_distance.py) * [Euclidean Gcd](maths/euclidean_gcd.py) * [Euler Method](maths/euler_method.py) * [Euler Modified](maths/euler_modified.py) * [Eulers Totient](maths/eulers_totient.py) * [Extended Euclidean Algorithm](maths/extended_euclidean_algorithm.py) * [Factorial](maths/factorial.py) * [Factors](maths/factors.py) * [Fermat Little Theorem](maths/fermat_little_theorem.py) * [Fibonacci](maths/fibonacci.py) * [Find Max](maths/find_max.py) * [Find Max Recursion](maths/find_max_recursion.py) * [Find Min](maths/find_min.py) * [Find Min Recursion](maths/find_min_recursion.py) * [Floor](maths/floor.py) * [Gamma](maths/gamma.py) * [Gamma Recursive](maths/gamma_recursive.py) * [Gaussian](maths/gaussian.py) * [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py) * [Gcd Of N Numbers](maths/gcd_of_n_numbers.py) * [Greatest Common Divisor](maths/greatest_common_divisor.py) * [Greedy Coin Change](maths/greedy_coin_change.py) * [Hamming Numbers](maths/hamming_numbers.py) * [Hardy Ramanujanalgo](maths/hardy_ramanujanalgo.py) * [Hexagonal Number](maths/hexagonal_number.py) * [Integration By Simpson Approx](maths/integration_by_simpson_approx.py) * [Is Int Palindrome](maths/is_int_palindrome.py) * [Is Ip V4 Address Valid](maths/is_ip_v4_address_valid.py) * [Is Square Free](maths/is_square_free.py) * [Jaccard Similarity](maths/jaccard_similarity.py) * [Juggler Sequence](maths/juggler_sequence.py) * [Kadanes](maths/kadanes.py) * [Karatsuba](maths/karatsuba.py) * [Krishnamurthy Number](maths/krishnamurthy_number.py) * [Kth Lexicographic Permutation](maths/kth_lexicographic_permutation.py) * [Largest Of Very Large Numbers](maths/largest_of_very_large_numbers.py) * [Largest Subarray Sum](maths/largest_subarray_sum.py) * [Least Common Multiple](maths/least_common_multiple.py) * [Line Length](maths/line_length.py) * [Liouville Lambda](maths/liouville_lambda.py) * [Lucas Lehmer Primality Test](maths/lucas_lehmer_primality_test.py) * [Lucas Series](maths/lucas_series.py) * [Maclaurin Series](maths/maclaurin_series.py) * [Manhattan Distance](maths/manhattan_distance.py) * [Matrix Exponentiation](maths/matrix_exponentiation.py) * [Max Sum Sliding Window](maths/max_sum_sliding_window.py) * [Median Of Two Arrays](maths/median_of_two_arrays.py) * [Miller Rabin](maths/miller_rabin.py) * [Mobius Function](maths/mobius_function.py) * [Modular Exponential](maths/modular_exponential.py) * [Monte Carlo](maths/monte_carlo.py) * [Monte Carlo Dice](maths/monte_carlo_dice.py) * [Nevilles Method](maths/nevilles_method.py) * [Newton Raphson](maths/newton_raphson.py) * [Number Of Digits](maths/number_of_digits.py) * [Numerical Integration](maths/numerical_integration.py) * [Odd Sieve](maths/odd_sieve.py) * [Perfect Cube](maths/perfect_cube.py) * [Perfect Number](maths/perfect_number.py) * [Perfect Square](maths/perfect_square.py) * [Persistence](maths/persistence.py) * [Pi Generator](maths/pi_generator.py) * [Pi Monte Carlo Estimation](maths/pi_monte_carlo_estimation.py) * [Points Are Collinear 3D](maths/points_are_collinear_3d.py) * [Pollard Rho](maths/pollard_rho.py) * [Polynomial Evaluation](maths/polynomial_evaluation.py) * Polynomials * [Single Indeterminate Operations](maths/polynomials/single_indeterminate_operations.py) * [Power Using Recursion](maths/power_using_recursion.py) * [Prime Check](maths/prime_check.py) * [Prime Factors](maths/prime_factors.py) * [Prime Numbers](maths/prime_numbers.py) * [Prime Sieve Eratosthenes](maths/prime_sieve_eratosthenes.py) * [Primelib](maths/primelib.py) * [Print Multiplication Table](maths/print_multiplication_table.py) * [Pronic Number](maths/pronic_number.py) * [Proth Number](maths/proth_number.py) * [Pythagoras](maths/pythagoras.py) * [Qr Decomposition](maths/qr_decomposition.py) * [Quadratic Equations Complex Numbers](maths/quadratic_equations_complex_numbers.py) * [Radians](maths/radians.py) * [Radix2 Fft](maths/radix2_fft.py) * [Relu](maths/relu.py) * [Remove Digit](maths/remove_digit.py) * [Runge Kutta](maths/runge_kutta.py) * [Segmented Sieve](maths/segmented_sieve.py) * Series * [Arithmetic](maths/series/arithmetic.py) * [Geometric](maths/series/geometric.py) * [Geometric Series](maths/series/geometric_series.py) * [Harmonic](maths/series/harmonic.py) * [Harmonic Series](maths/series/harmonic_series.py) * [Hexagonal Numbers](maths/series/hexagonal_numbers.py) * [P Series](maths/series/p_series.py) * [Sieve Of Eratosthenes](maths/sieve_of_eratosthenes.py) * [Sigmoid](maths/sigmoid.py) * [Sigmoid Linear Unit](maths/sigmoid_linear_unit.py) * [Signum](maths/signum.py) * [Simpson Rule](maths/simpson_rule.py) * [Simultaneous Linear Equation Solver](maths/simultaneous_linear_equation_solver.py) * [Sin](maths/sin.py) * [Sock Merchant](maths/sock_merchant.py) * [Softmax](maths/softmax.py) * [Square Root](maths/square_root.py) * [Sum Of Arithmetic Series](maths/sum_of_arithmetic_series.py) * [Sum Of Digits](maths/sum_of_digits.py) * [Sum Of Geometric Progression](maths/sum_of_geometric_progression.py) * [Sum Of Harmonic Series](maths/sum_of_harmonic_series.py) * [Sumset](maths/sumset.py) * [Sylvester Sequence](maths/sylvester_sequence.py) * [Tanh](maths/tanh.py) * [Test Prime Check](maths/test_prime_check.py) * [Trapezoidal Rule](maths/trapezoidal_rule.py) * [Triplet Sum](maths/triplet_sum.py) * [Twin Prime](maths/twin_prime.py) * [Two Pointer](maths/two_pointer.py) * [Two Sum](maths/two_sum.py) * [Ugly Numbers](maths/ugly_numbers.py) * [Volume](maths/volume.py) * [Weird Number](maths/weird_number.py) * [Zellers Congruence](maths/zellers_congruence.py) ## Matrix * [Binary Search Matrix](matrix/binary_search_matrix.py) * [Count Islands In Matrix](matrix/count_islands_in_matrix.py) * [Count Negative Numbers In Sorted Matrix](matrix/count_negative_numbers_in_sorted_matrix.py) * [Count Paths](matrix/count_paths.py) * [Cramers Rule 2X2](matrix/cramers_rule_2x2.py) * [Inverse Of Matrix](matrix/inverse_of_matrix.py) * [Largest Square Area In Matrix](matrix/largest_square_area_in_matrix.py) * [Matrix Class](matrix/matrix_class.py) * [Matrix Operation](matrix/matrix_operation.py) * [Max Area Of Island](matrix/max_area_of_island.py) * [Nth Fibonacci Using Matrix Exponentiation](matrix/nth_fibonacci_using_matrix_exponentiation.py) * [Pascal Triangle](matrix/pascal_triangle.py) * [Rotate Matrix](matrix/rotate_matrix.py) * [Searching In Sorted Matrix](matrix/searching_in_sorted_matrix.py) * [Sherman Morrison](matrix/sherman_morrison.py) * [Spiral Print](matrix/spiral_print.py) * Tests * [Test Matrix Operation](matrix/tests/test_matrix_operation.py) ## Networking Flow * [Ford Fulkerson](networking_flow/ford_fulkerson.py) * [Minimum Cut](networking_flow/minimum_cut.py) ## Neural Network * [2 Hidden Layers Neural Network](neural_network/2_hidden_layers_neural_network.py) * Activation Functions * [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py) * [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py) * [Convolution Neural Network](neural_network/convolution_neural_network.py) * [Input Data](neural_network/input_data.py) * [Perceptron](neural_network/perceptron.py) * [Simple Neural Network](neural_network/simple_neural_network.py) ## Other * [Activity Selection](other/activity_selection.py) * [Alternative List Arrange](other/alternative_list_arrange.py) * [Davisb Putnamb Logemannb Loveland](other/davisb_putnamb_logemannb_loveland.py) * [Dijkstra Bankers Algorithm](other/dijkstra_bankers_algorithm.py) * [Doomsday](other/doomsday.py) * [Fischer Yates Shuffle](other/fischer_yates_shuffle.py) * [Gauss Easter](other/gauss_easter.py) * [Graham Scan](other/graham_scan.py) * [Greedy](other/greedy.py) * [Guess The Number Search](other/guess_the_number_search.py) * [H Index](other/h_index.py) * [Least Recently Used](other/least_recently_used.py) * [Lfu Cache](other/lfu_cache.py) * [Linear Congruential Generator](other/linear_congruential_generator.py) * [Lru Cache](other/lru_cache.py) * [Magicdiamondpattern](other/magicdiamondpattern.py) * [Maximum Subarray](other/maximum_subarray.py) * [Maximum Subsequence](other/maximum_subsequence.py) * [Nested Brackets](other/nested_brackets.py) * [Number Container System](other/number_container_system.py) * [Password](other/password.py) * [Quine](other/quine.py) * [Scoring Algorithm](other/scoring_algorithm.py) * [Sdes](other/sdes.py) * [Tower Of Hanoi](other/tower_of_hanoi.py) ## Physics * [Archimedes Principle](physics/archimedes_principle.py) * [Casimir Effect](physics/casimir_effect.py) * [Centripetal Force](physics/centripetal_force.py) * [Grahams Law](physics/grahams_law.py) * [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py) * [Hubble Parameter](physics/hubble_parameter.py) * [Ideal Gas Law](physics/ideal_gas_law.py) * [Kinetic Energy](physics/kinetic_energy.py) * [Lorentz Transformation Four Vector](physics/lorentz_transformation_four_vector.py) * [Malus Law](physics/malus_law.py) * [N Body Simulation](physics/n_body_simulation.py) * [Newtons Law Of Gravitation](physics/newtons_law_of_gravitation.py) * [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py) * [Potential Energy](physics/potential_energy.py) * [Rms Speed Of Molecule](physics/rms_speed_of_molecule.py) * [Shear Stress](physics/shear_stress.py) * [Speed Of Sound](physics/speed_of_sound.py) ## Project Euler * Problem 001 * [Sol1](project_euler/problem_001/sol1.py) * [Sol2](project_euler/problem_001/sol2.py) * [Sol3](project_euler/problem_001/sol3.py) * [Sol4](project_euler/problem_001/sol4.py) * [Sol5](project_euler/problem_001/sol5.py) * [Sol6](project_euler/problem_001/sol6.py) * [Sol7](project_euler/problem_001/sol7.py) * Problem 002 * [Sol1](project_euler/problem_002/sol1.py) * [Sol2](project_euler/problem_002/sol2.py) * [Sol3](project_euler/problem_002/sol3.py) * [Sol4](project_euler/problem_002/sol4.py) * [Sol5](project_euler/problem_002/sol5.py) * Problem 003 * [Sol1](project_euler/problem_003/sol1.py) * [Sol2](project_euler/problem_003/sol2.py) * [Sol3](project_euler/problem_003/sol3.py) * Problem 004 * [Sol1](project_euler/problem_004/sol1.py) * [Sol2](project_euler/problem_004/sol2.py) * Problem 005 * [Sol1](project_euler/problem_005/sol1.py) * [Sol2](project_euler/problem_005/sol2.py) * Problem 006 * [Sol1](project_euler/problem_006/sol1.py) * [Sol2](project_euler/problem_006/sol2.py) * [Sol3](project_euler/problem_006/sol3.py) * [Sol4](project_euler/problem_006/sol4.py) * Problem 007 * [Sol1](project_euler/problem_007/sol1.py) * [Sol2](project_euler/problem_007/sol2.py) * [Sol3](project_euler/problem_007/sol3.py) * Problem 008 * [Sol1](project_euler/problem_008/sol1.py) * [Sol2](project_euler/problem_008/sol2.py) * [Sol3](project_euler/problem_008/sol3.py) * Problem 009 * [Sol1](project_euler/problem_009/sol1.py) * [Sol2](project_euler/problem_009/sol2.py) * [Sol3](project_euler/problem_009/sol3.py) * Problem 010 * [Sol1](project_euler/problem_010/sol1.py) * [Sol2](project_euler/problem_010/sol2.py) * [Sol3](project_euler/problem_010/sol3.py) * Problem 011 * [Sol1](project_euler/problem_011/sol1.py) * [Sol2](project_euler/problem_011/sol2.py) * Problem 012 * [Sol1](project_euler/problem_012/sol1.py) * [Sol2](project_euler/problem_012/sol2.py) * Problem 013 * [Sol1](project_euler/problem_013/sol1.py) * Problem 014 * [Sol1](project_euler/problem_014/sol1.py) * [Sol2](project_euler/problem_014/sol2.py) * Problem 015 * [Sol1](project_euler/problem_015/sol1.py) * Problem 016 * [Sol1](project_euler/problem_016/sol1.py) * [Sol2](project_euler/problem_016/sol2.py) * Problem 017 * [Sol1](project_euler/problem_017/sol1.py) * Problem 018 * [Solution](project_euler/problem_018/solution.py) * Problem 019 * [Sol1](project_euler/problem_019/sol1.py) * Problem 020 * [Sol1](project_euler/problem_020/sol1.py) * [Sol2](project_euler/problem_020/sol2.py) * [Sol3](project_euler/problem_020/sol3.py) * [Sol4](project_euler/problem_020/sol4.py) * Problem 021 * [Sol1](project_euler/problem_021/sol1.py) * Problem 022 * [Sol1](project_euler/problem_022/sol1.py) * [Sol2](project_euler/problem_022/sol2.py) * Problem 023 * [Sol1](project_euler/problem_023/sol1.py) * Problem 024 * [Sol1](project_euler/problem_024/sol1.py) * Problem 025 * [Sol1](project_euler/problem_025/sol1.py) * [Sol2](project_euler/problem_025/sol2.py) * [Sol3](project_euler/problem_025/sol3.py) * Problem 026 * [Sol1](project_euler/problem_026/sol1.py) * Problem 027 * [Sol1](project_euler/problem_027/sol1.py) * Problem 028 * [Sol1](project_euler/problem_028/sol1.py) * Problem 029 * [Sol1](project_euler/problem_029/sol1.py) * Problem 030 * [Sol1](project_euler/problem_030/sol1.py) * Problem 031 * [Sol1](project_euler/problem_031/sol1.py) * [Sol2](project_euler/problem_031/sol2.py) * Problem 032 * [Sol32](project_euler/problem_032/sol32.py) * Problem 033 * [Sol1](project_euler/problem_033/sol1.py) * Problem 034 * [Sol1](project_euler/problem_034/sol1.py) * Problem 035 * [Sol1](project_euler/problem_035/sol1.py) * Problem 036 * [Sol1](project_euler/problem_036/sol1.py) * Problem 037 * [Sol1](project_euler/problem_037/sol1.py) * Problem 038 * [Sol1](project_euler/problem_038/sol1.py) * Problem 039 * [Sol1](project_euler/problem_039/sol1.py) * Problem 040 * [Sol1](project_euler/problem_040/sol1.py) * Problem 041 * [Sol1](project_euler/problem_041/sol1.py) * Problem 042 * [Solution42](project_euler/problem_042/solution42.py) * Problem 043 * [Sol1](project_euler/problem_043/sol1.py) * Problem 044 * [Sol1](project_euler/problem_044/sol1.py) * Problem 045 * [Sol1](project_euler/problem_045/sol1.py) * Problem 046 * [Sol1](project_euler/problem_046/sol1.py) * Problem 047 * [Sol1](project_euler/problem_047/sol1.py) * Problem 048 * [Sol1](project_euler/problem_048/sol1.py) * Problem 049 * [Sol1](project_euler/problem_049/sol1.py) * Problem 050 * [Sol1](project_euler/problem_050/sol1.py) * Problem 051 * [Sol1](project_euler/problem_051/sol1.py) * Problem 052 * [Sol1](project_euler/problem_052/sol1.py) * Problem 053 * [Sol1](project_euler/problem_053/sol1.py) * Problem 054 * [Sol1](project_euler/problem_054/sol1.py) * [Test Poker Hand](project_euler/problem_054/test_poker_hand.py) * Problem 055 * [Sol1](project_euler/problem_055/sol1.py) * Problem 056 * [Sol1](project_euler/problem_056/sol1.py) * Problem 057 * [Sol1](project_euler/problem_057/sol1.py) * Problem 058 * [Sol1](project_euler/problem_058/sol1.py) * Problem 059 * [Sol1](project_euler/problem_059/sol1.py) * Problem 062 * [Sol1](project_euler/problem_062/sol1.py) * Problem 063 * [Sol1](project_euler/problem_063/sol1.py) * Problem 064 * [Sol1](project_euler/problem_064/sol1.py) * Problem 065 * [Sol1](project_euler/problem_065/sol1.py) * Problem 067 * [Sol1](project_euler/problem_067/sol1.py) * [Sol2](project_euler/problem_067/sol2.py) * Problem 068 * [Sol1](project_euler/problem_068/sol1.py) * Problem 069 * [Sol1](project_euler/problem_069/sol1.py) * Problem 070 * [Sol1](project_euler/problem_070/sol1.py) * Problem 071 * [Sol1](project_euler/problem_071/sol1.py) * Problem 072 * [Sol1](project_euler/problem_072/sol1.py) * [Sol2](project_euler/problem_072/sol2.py) * Problem 073 * [Sol1](project_euler/problem_073/sol1.py) * Problem 074 * [Sol1](project_euler/problem_074/sol1.py) * [Sol2](project_euler/problem_074/sol2.py) * Problem 075 * [Sol1](project_euler/problem_075/sol1.py) * Problem 076 * [Sol1](project_euler/problem_076/sol1.py) * Problem 077 * [Sol1](project_euler/problem_077/sol1.py) * Problem 078 * [Sol1](project_euler/problem_078/sol1.py) * Problem 079 * [Sol1](project_euler/problem_079/sol1.py) * Problem 080 * [Sol1](project_euler/problem_080/sol1.py) * Problem 081 * [Sol1](project_euler/problem_081/sol1.py) * Problem 082 * [Sol1](project_euler/problem_082/sol1.py) * Problem 085 * [Sol1](project_euler/problem_085/sol1.py) * Problem 086 * [Sol1](project_euler/problem_086/sol1.py) * Problem 087 * [Sol1](project_euler/problem_087/sol1.py) * Problem 089 * [Sol1](project_euler/problem_089/sol1.py) * Problem 091 * [Sol1](project_euler/problem_091/sol1.py) * Problem 092 * [Sol1](project_euler/problem_092/sol1.py) * Problem 094 * [Sol1](project_euler/problem_094/sol1.py) * Problem 097 * [Sol1](project_euler/problem_097/sol1.py) * Problem 099 * [Sol1](project_euler/problem_099/sol1.py) * Problem 100 * [Sol1](project_euler/problem_100/sol1.py) * Problem 101 * [Sol1](project_euler/problem_101/sol1.py) * Problem 102 * [Sol1](project_euler/problem_102/sol1.py) * Problem 104 * [Sol1](project_euler/problem_104/sol1.py) * Problem 107 * [Sol1](project_euler/problem_107/sol1.py) * Problem 109 * [Sol1](project_euler/problem_109/sol1.py) * Problem 112 * [Sol1](project_euler/problem_112/sol1.py) * Problem 113 * [Sol1](project_euler/problem_113/sol1.py) * Problem 114 * [Sol1](project_euler/problem_114/sol1.py) * Problem 115 * [Sol1](project_euler/problem_115/sol1.py) * Problem 116 * [Sol1](project_euler/problem_116/sol1.py) * Problem 117 * [Sol1](project_euler/problem_117/sol1.py) * Problem 119 * [Sol1](project_euler/problem_119/sol1.py) * Problem 120 * [Sol1](project_euler/problem_120/sol1.py) * Problem 121 * [Sol1](project_euler/problem_121/sol1.py) * Problem 123 * [Sol1](project_euler/problem_123/sol1.py) * Problem 125 * [Sol1](project_euler/problem_125/sol1.py) * Problem 129 * [Sol1](project_euler/problem_129/sol1.py) * Problem 131 * [Sol1](project_euler/problem_131/sol1.py) * Problem 135 * [Sol1](project_euler/problem_135/sol1.py) * Problem 144 * [Sol1](project_euler/problem_144/sol1.py) * Problem 145 * [Sol1](project_euler/problem_145/sol1.py) * Problem 173 * [Sol1](project_euler/problem_173/sol1.py) * Problem 174 * [Sol1](project_euler/problem_174/sol1.py) * Problem 180 * [Sol1](project_euler/problem_180/sol1.py) * Problem 187 * [Sol1](project_euler/problem_187/sol1.py) * Problem 188 * [Sol1](project_euler/problem_188/sol1.py) * Problem 191 * [Sol1](project_euler/problem_191/sol1.py) * Problem 203 * [Sol1](project_euler/problem_203/sol1.py) * Problem 205 * [Sol1](project_euler/problem_205/sol1.py) * Problem 206 * [Sol1](project_euler/problem_206/sol1.py) * Problem 207 * [Sol1](project_euler/problem_207/sol1.py) * Problem 234 * [Sol1](project_euler/problem_234/sol1.py) * Problem 301 * [Sol1](project_euler/problem_301/sol1.py) * Problem 493 * [Sol1](project_euler/problem_493/sol1.py) * Problem 551 * [Sol1](project_euler/problem_551/sol1.py) * Problem 587 * [Sol1](project_euler/problem_587/sol1.py) * Problem 686 * [Sol1](project_euler/problem_686/sol1.py) * Problem 800 * [Sol1](project_euler/problem_800/sol1.py) ## Quantum * [Bb84](quantum/bb84.py) * [Deutsch Jozsa](quantum/deutsch_jozsa.py) * [Half Adder](quantum/half_adder.py) * [Not Gate](quantum/not_gate.py) * [Q Fourier Transform](quantum/q_fourier_transform.py) * [Q Full Adder](quantum/q_full_adder.py) * [Quantum Entanglement](quantum/quantum_entanglement.py) * [Quantum Random](quantum/quantum_random.py) * [Quantum Teleportation](quantum/quantum_teleportation.py) * [Ripple Adder Classic](quantum/ripple_adder_classic.py) * [Single Qubit Measure](quantum/single_qubit_measure.py) * [Superdense Coding](quantum/superdense_coding.py) ## Scheduling * [First Come First Served](scheduling/first_come_first_served.py) * [Highest Response Ratio Next](scheduling/highest_response_ratio_next.py) * [Job Sequencing With Deadline](scheduling/job_sequencing_with_deadline.py) * [Multi Level Feedback Queue](scheduling/multi_level_feedback_queue.py) * [Non Preemptive Shortest Job First](scheduling/non_preemptive_shortest_job_first.py) * [Round Robin](scheduling/round_robin.py) * [Shortest Job First](scheduling/shortest_job_first.py) ## Searches * [Binary Search](searches/binary_search.py) * [Binary Tree Traversal](searches/binary_tree_traversal.py) * [Double Linear Search](searches/double_linear_search.py) * [Double Linear Search Recursion](searches/double_linear_search_recursion.py) * [Fibonacci Search](searches/fibonacci_search.py) * [Hill Climbing](searches/hill_climbing.py) * [Interpolation Search](searches/interpolation_search.py) * [Jump Search](searches/jump_search.py) * [Linear Search](searches/linear_search.py) * [Quick Select](searches/quick_select.py) * [Sentinel Linear Search](searches/sentinel_linear_search.py) * [Simple Binary Search](searches/simple_binary_search.py) * [Simulated Annealing](searches/simulated_annealing.py) * [Tabu Search](searches/tabu_search.py) * [Ternary Search](searches/ternary_search.py) ## Sorts * [Bead Sort](sorts/bead_sort.py) * [Binary Insertion Sort](sorts/binary_insertion_sort.py) * [Bitonic Sort](sorts/bitonic_sort.py) * [Bogo Sort](sorts/bogo_sort.py) * [Bubble Sort](sorts/bubble_sort.py) * [Bucket Sort](sorts/bucket_sort.py) * [Circle Sort](sorts/circle_sort.py) * [Cocktail Shaker Sort](sorts/cocktail_shaker_sort.py) * [Comb Sort](sorts/comb_sort.py) * [Counting Sort](sorts/counting_sort.py) * [Cycle Sort](sorts/cycle_sort.py) * [Double Sort](sorts/double_sort.py) * [Dutch National Flag Sort](sorts/dutch_national_flag_sort.py) * [Exchange Sort](sorts/exchange_sort.py) * [External Sort](sorts/external_sort.py) * [Gnome Sort](sorts/gnome_sort.py) * [Heap Sort](sorts/heap_sort.py) * [Insertion Sort](sorts/insertion_sort.py) * [Intro Sort](sorts/intro_sort.py) * [Iterative Merge Sort](sorts/iterative_merge_sort.py) * [Merge Insertion Sort](sorts/merge_insertion_sort.py) * [Merge Sort](sorts/merge_sort.py) * [Msd Radix Sort](sorts/msd_radix_sort.py) * [Natural Sort](sorts/natural_sort.py) * [Odd Even Sort](sorts/odd_even_sort.py) * [Odd Even Transposition Parallel](sorts/odd_even_transposition_parallel.py) * [Odd Even Transposition Single Threaded](sorts/odd_even_transposition_single_threaded.py) * [Pancake Sort](sorts/pancake_sort.py) * [Patience Sort](sorts/patience_sort.py) * [Pigeon Sort](sorts/pigeon_sort.py) * [Pigeonhole Sort](sorts/pigeonhole_sort.py) * [Quick Sort](sorts/quick_sort.py) * [Quick Sort 3 Partition](sorts/quick_sort_3_partition.py) * [Radix Sort](sorts/radix_sort.py) * [Random Normal Distribution Quicksort](sorts/random_normal_distribution_quicksort.py) * [Random Pivot Quick Sort](sorts/random_pivot_quick_sort.py) * [Recursive Bubble Sort](sorts/recursive_bubble_sort.py) * [Recursive Insertion Sort](sorts/recursive_insertion_sort.py) * [Recursive Mergesort Array](sorts/recursive_mergesort_array.py) * [Recursive Quick Sort](sorts/recursive_quick_sort.py) * [Selection Sort](sorts/selection_sort.py) * [Shell Sort](sorts/shell_sort.py) * [Shrink Shell Sort](sorts/shrink_shell_sort.py) * [Slowsort](sorts/slowsort.py) * [Stooge Sort](sorts/stooge_sort.py) * [Strand Sort](sorts/strand_sort.py) * [Tim Sort](sorts/tim_sort.py) * [Topological Sort](sorts/topological_sort.py) * [Tree Sort](sorts/tree_sort.py) * [Unknown Sort](sorts/unknown_sort.py) * [Wiggle Sort](sorts/wiggle_sort.py) ## Strings * [Aho Corasick](strings/aho_corasick.py) * [Alternative String Arrange](strings/alternative_string_arrange.py) * [Anagrams](strings/anagrams.py) * [Autocomplete Using Trie](strings/autocomplete_using_trie.py) * [Barcode Validator](strings/barcode_validator.py) * [Boyer Moore Search](strings/boyer_moore_search.py) * [Can String Be Rearranged As Palindrome](strings/can_string_be_rearranged_as_palindrome.py) * [Capitalize](strings/capitalize.py) * [Check Anagrams](strings/check_anagrams.py) * [Credit Card Validator](strings/credit_card_validator.py) * [Detecting English Programmatically](strings/detecting_english_programmatically.py) * [Dna](strings/dna.py) * [Frequency Finder](strings/frequency_finder.py) * [Hamming Distance](strings/hamming_distance.py) * [Indian Phone Validator](strings/indian_phone_validator.py) * [Is Contains Unique Chars](strings/is_contains_unique_chars.py) * [Is Isogram](strings/is_isogram.py) * [Is Pangram](strings/is_pangram.py) * [Is Spain National Id](strings/is_spain_national_id.py) * [Is Srilankan Phone Number](strings/is_srilankan_phone_number.py) * [Jaro Winkler](strings/jaro_winkler.py) * [Join](strings/join.py) * [Knuth Morris Pratt](strings/knuth_morris_pratt.py) * [Levenshtein Distance](strings/levenshtein_distance.py) * [Lower](strings/lower.py) * [Manacher](strings/manacher.py) * [Min Cost String Conversion](strings/min_cost_string_conversion.py) * [Naive String Search](strings/naive_string_search.py) * [Ngram](strings/ngram.py) * [Palindrome](strings/palindrome.py) * [Prefix Function](strings/prefix_function.py) * [Rabin Karp](strings/rabin_karp.py) * [Remove Duplicate](strings/remove_duplicate.py) * [Reverse Letters](strings/reverse_letters.py) * [Reverse Long Words](strings/reverse_long_words.py) * [Reverse Words](strings/reverse_words.py) * [Snake Case To Camel Pascal Case](strings/snake_case_to_camel_pascal_case.py) * [Split](strings/split.py) * [String Switch Case](strings/string_switch_case.py) * [Text Justification](strings/text_justification.py) * [Top K Frequent Words](strings/top_k_frequent_words.py) * [Upper](strings/upper.py) * [Wave](strings/wave.py) * [Wildcard Pattern Matching](strings/wildcard_pattern_matching.py) * [Word Occurrence](strings/word_occurrence.py) * [Word Patterns](strings/word_patterns.py) * [Z Function](strings/z_function.py) ## Web Programming * [Co2 Emission](web_programming/co2_emission.py) * [Convert Number To Words](web_programming/convert_number_to_words.py) * [Covid Stats Via Xpath](web_programming/covid_stats_via_xpath.py) * [Crawl Google Results](web_programming/crawl_google_results.py) * [Crawl Google Scholar Citation](web_programming/crawl_google_scholar_citation.py) * [Currency Converter](web_programming/currency_converter.py) * [Current Stock Price](web_programming/current_stock_price.py) * [Current Weather](web_programming/current_weather.py) * [Daily Horoscope](web_programming/daily_horoscope.py) * [Download Images From Google Query](web_programming/download_images_from_google_query.py) * [Emails From Url](web_programming/emails_from_url.py) * [Fetch Bbc News](web_programming/fetch_bbc_news.py) * [Fetch Github Info](web_programming/fetch_github_info.py) * [Fetch Jobs](web_programming/fetch_jobs.py) * [Fetch Quotes](web_programming/fetch_quotes.py) * [Fetch Well Rx Price](web_programming/fetch_well_rx_price.py) * [Get Amazon Product Data](web_programming/get_amazon_product_data.py) * [Get Imdb Top 250 Movies Csv](web_programming/get_imdb_top_250_movies_csv.py) * [Get Imdbtop](web_programming/get_imdbtop.py) * [Get Top Hn Posts](web_programming/get_top_hn_posts.py) * [Get User Tweets](web_programming/get_user_tweets.py) * [Giphy](web_programming/giphy.py) * [Instagram Crawler](web_programming/instagram_crawler.py) * [Instagram Pic](web_programming/instagram_pic.py) * [Instagram Video](web_programming/instagram_video.py) * [Nasa Data](web_programming/nasa_data.py) * [Open Google Results](web_programming/open_google_results.py) * [Random Anime Character](web_programming/random_anime_character.py) * [Recaptcha Verification](web_programming/recaptcha_verification.py) * [Reddit](web_programming/reddit.py) * [Search Books By Isbn](web_programming/search_books_by_isbn.py) * [Slack Message](web_programming/slack_message.py) * [Test Fetch Github Info](web_programming/test_fetch_github_info.py) * [World Covid19 Stats](web_programming/world_covid19_stats.py)
## Arithmetic Analysis * [Bisection](arithmetic_analysis/bisection.py) * [Gaussian Elimination](arithmetic_analysis/gaussian_elimination.py) * [In Static Equilibrium](arithmetic_analysis/in_static_equilibrium.py) * [Intersection](arithmetic_analysis/intersection.py) * [Jacobi Iteration Method](arithmetic_analysis/jacobi_iteration_method.py) * [Lu Decomposition](arithmetic_analysis/lu_decomposition.py) * [Newton Forward Interpolation](arithmetic_analysis/newton_forward_interpolation.py) * [Newton Method](arithmetic_analysis/newton_method.py) * [Newton Raphson](arithmetic_analysis/newton_raphson.py) * [Newton Raphson New](arithmetic_analysis/newton_raphson_new.py) * [Secant Method](arithmetic_analysis/secant_method.py) ## Audio Filters * [Butterworth Filter](audio_filters/butterworth_filter.py) * [Iir Filter](audio_filters/iir_filter.py) * [Show Response](audio_filters/show_response.py) ## Backtracking * [All Combinations](backtracking/all_combinations.py) * [All Permutations](backtracking/all_permutations.py) * [All Subsequences](backtracking/all_subsequences.py) * [Coloring](backtracking/coloring.py) * [Combination Sum](backtracking/combination_sum.py) * [Hamiltonian Cycle](backtracking/hamiltonian_cycle.py) * [Knight Tour](backtracking/knight_tour.py) * [Minimax](backtracking/minimax.py) * [Minmax](backtracking/minmax.py) * [N Queens](backtracking/n_queens.py) * [N Queens Math](backtracking/n_queens_math.py) * [Rat In Maze](backtracking/rat_in_maze.py) * [Sudoku](backtracking/sudoku.py) * [Sum Of Subsets](backtracking/sum_of_subsets.py) * [Word Search](backtracking/word_search.py) ## Bit Manipulation * [Binary And Operator](bit_manipulation/binary_and_operator.py) * [Binary Count Setbits](bit_manipulation/binary_count_setbits.py) * [Binary Count Trailing Zeros](bit_manipulation/binary_count_trailing_zeros.py) * [Binary Or Operator](bit_manipulation/binary_or_operator.py) * [Binary Shifts](bit_manipulation/binary_shifts.py) * [Binary Twos Complement](bit_manipulation/binary_twos_complement.py) * [Binary Xor Operator](bit_manipulation/binary_xor_operator.py) * [Count 1S Brian Kernighan Method](bit_manipulation/count_1s_brian_kernighan_method.py) * [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py) * [Gray Code Sequence](bit_manipulation/gray_code_sequence.py) * [Highest Set Bit](bit_manipulation/highest_set_bit.py) * [Index Of Rightmost Set Bit](bit_manipulation/index_of_rightmost_set_bit.py) * [Is Even](bit_manipulation/is_even.py) * [Is Power Of Two](bit_manipulation/is_power_of_two.py) * [Numbers Different Signs](bit_manipulation/numbers_different_signs.py) * [Reverse Bits](bit_manipulation/reverse_bits.py) * [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py) ## Blockchain * [Chinese Remainder Theorem](blockchain/chinese_remainder_theorem.py) * [Diophantine Equation](blockchain/diophantine_equation.py) * [Modular Division](blockchain/modular_division.py) ## Boolean Algebra * [And Gate](boolean_algebra/and_gate.py) * [Nand Gate](boolean_algebra/nand_gate.py) * [Norgate](boolean_algebra/norgate.py) * [Not Gate](boolean_algebra/not_gate.py) * [Or Gate](boolean_algebra/or_gate.py) * [Quine Mc Cluskey](boolean_algebra/quine_mc_cluskey.py) * [Xnor Gate](boolean_algebra/xnor_gate.py) * [Xor Gate](boolean_algebra/xor_gate.py) ## Cellular Automata * [Conways Game Of Life](cellular_automata/conways_game_of_life.py) * [Game Of Life](cellular_automata/game_of_life.py) * [Nagel Schrekenberg](cellular_automata/nagel_schrekenberg.py) * [One Dimensional](cellular_automata/one_dimensional.py) ## Ciphers * [A1Z26](ciphers/a1z26.py) * [Affine Cipher](ciphers/affine_cipher.py) * [Atbash](ciphers/atbash.py) * [Autokey](ciphers/autokey.py) * [Baconian Cipher](ciphers/baconian_cipher.py) * [Base16](ciphers/base16.py) * [Base32](ciphers/base32.py) * [Base64](ciphers/base64.py) * [Base85](ciphers/base85.py) * [Beaufort Cipher](ciphers/beaufort_cipher.py) * [Bifid](ciphers/bifid.py) * [Brute Force Caesar Cipher](ciphers/brute_force_caesar_cipher.py) * [Caesar Cipher](ciphers/caesar_cipher.py) * [Cryptomath Module](ciphers/cryptomath_module.py) * [Decrypt Caesar With Chi Squared](ciphers/decrypt_caesar_with_chi_squared.py) * [Deterministic Miller Rabin](ciphers/deterministic_miller_rabin.py) * [Diffie](ciphers/diffie.py) * [Diffie Hellman](ciphers/diffie_hellman.py) * [Elgamal Key Generator](ciphers/elgamal_key_generator.py) * [Enigma Machine2](ciphers/enigma_machine2.py) * [Hill Cipher](ciphers/hill_cipher.py) * [Mixed Keyword Cypher](ciphers/mixed_keyword_cypher.py) * [Mono Alphabetic Ciphers](ciphers/mono_alphabetic_ciphers.py) * [Morse Code](ciphers/morse_code.py) * [Onepad Cipher](ciphers/onepad_cipher.py) * [Playfair Cipher](ciphers/playfair_cipher.py) * [Polybius](ciphers/polybius.py) * [Porta Cipher](ciphers/porta_cipher.py) * [Rabin Miller](ciphers/rabin_miller.py) * [Rail Fence Cipher](ciphers/rail_fence_cipher.py) * [Rot13](ciphers/rot13.py) * [Rsa Cipher](ciphers/rsa_cipher.py) * [Rsa Factorization](ciphers/rsa_factorization.py) * [Rsa Key Generator](ciphers/rsa_key_generator.py) * [Shuffled Shift Cipher](ciphers/shuffled_shift_cipher.py) * [Simple Keyword Cypher](ciphers/simple_keyword_cypher.py) * [Simple Substitution Cipher](ciphers/simple_substitution_cipher.py) * [Trafid Cipher](ciphers/trafid_cipher.py) * [Transposition Cipher](ciphers/transposition_cipher.py) * [Transposition Cipher Encrypt Decrypt File](ciphers/transposition_cipher_encrypt_decrypt_file.py) * [Vigenere Cipher](ciphers/vigenere_cipher.py) * [Xor Cipher](ciphers/xor_cipher.py) ## Compression * [Burrows Wheeler](compression/burrows_wheeler.py) * [Huffman](compression/huffman.py) * [Lempel Ziv](compression/lempel_ziv.py) * [Lempel Ziv Decompress](compression/lempel_ziv_decompress.py) * [Lz77](compression/lz77.py) * [Peak Signal To Noise Ratio](compression/peak_signal_to_noise_ratio.py) * [Run Length Encoding](compression/run_length_encoding.py) ## Computer Vision * [Cnn Classification](computer_vision/cnn_classification.py) * [Flip Augmentation](computer_vision/flip_augmentation.py) * [Harris Corner](computer_vision/harris_corner.py) * [Horn Schunck](computer_vision/horn_schunck.py) * [Mean Threshold](computer_vision/mean_threshold.py) * [Mosaic Augmentation](computer_vision/mosaic_augmentation.py) * [Pooling Functions](computer_vision/pooling_functions.py) ## Conversions * [Astronomical Length Scale Conversion](conversions/astronomical_length_scale_conversion.py) * [Binary To Decimal](conversions/binary_to_decimal.py) * [Binary To Hexadecimal](conversions/binary_to_hexadecimal.py) * [Binary To Octal](conversions/binary_to_octal.py) * [Decimal To Any](conversions/decimal_to_any.py) * [Decimal To Binary](conversions/decimal_to_binary.py) * [Decimal To Binary Recursion](conversions/decimal_to_binary_recursion.py) * [Decimal To Hexadecimal](conversions/decimal_to_hexadecimal.py) * [Decimal To Octal](conversions/decimal_to_octal.py) * [Energy Conversions](conversions/energy_conversions.py) * [Excel Title To Column](conversions/excel_title_to_column.py) * [Hex To Bin](conversions/hex_to_bin.py) * [Hexadecimal To Decimal](conversions/hexadecimal_to_decimal.py) * [Length Conversion](conversions/length_conversion.py) * [Molecular Chemistry](conversions/molecular_chemistry.py) * [Octal To Decimal](conversions/octal_to_decimal.py) * [Prefix Conversions](conversions/prefix_conversions.py) * [Prefix Conversions String](conversions/prefix_conversions_string.py) * [Pressure Conversions](conversions/pressure_conversions.py) * [Rgb Hsv Conversion](conversions/rgb_hsv_conversion.py) * [Roman Numerals](conversions/roman_numerals.py) * [Speed Conversions](conversions/speed_conversions.py) * [Temperature Conversions](conversions/temperature_conversions.py) * [Volume Conversions](conversions/volume_conversions.py) * [Weight Conversion](conversions/weight_conversion.py) ## Data Structures * Arrays * [Permutations](data_structures/arrays/permutations.py) * [Prefix Sum](data_structures/arrays/prefix_sum.py) * [Product Sum Array](data_structures/arrays/product_sum.py) * Binary Tree * [Avl Tree](data_structures/binary_tree/avl_tree.py) * [Basic Binary Tree](data_structures/binary_tree/basic_binary_tree.py) * [Binary Search Tree](data_structures/binary_tree/binary_search_tree.py) * [Binary Search Tree Recursive](data_structures/binary_tree/binary_search_tree_recursive.py) * [Binary Tree Mirror](data_structures/binary_tree/binary_tree_mirror.py) * [Binary Tree Node Sum](data_structures/binary_tree/binary_tree_node_sum.py) * [Binary Tree Path Sum](data_structures/binary_tree/binary_tree_path_sum.py) * [Binary Tree Traversals](data_structures/binary_tree/binary_tree_traversals.py) * [Diff Views Of Binary Tree](data_structures/binary_tree/diff_views_of_binary_tree.py) * [Distribute Coins](data_structures/binary_tree/distribute_coins.py) * [Fenwick Tree](data_structures/binary_tree/fenwick_tree.py) * [Inorder Tree Traversal 2022](data_structures/binary_tree/inorder_tree_traversal_2022.py) * [Is Bst](data_structures/binary_tree/is_bst.py) * [Lazy Segment Tree](data_structures/binary_tree/lazy_segment_tree.py) * [Lowest Common Ancestor](data_structures/binary_tree/lowest_common_ancestor.py) * [Maximum Fenwick Tree](data_structures/binary_tree/maximum_fenwick_tree.py) * [Merge Two Binary Trees](data_structures/binary_tree/merge_two_binary_trees.py) * [Non Recursive Segment Tree](data_structures/binary_tree/non_recursive_segment_tree.py) * [Number Of Possible Binary Trees](data_structures/binary_tree/number_of_possible_binary_trees.py) * [Red Black Tree](data_structures/binary_tree/red_black_tree.py) * [Segment Tree](data_structures/binary_tree/segment_tree.py) * [Segment Tree Other](data_structures/binary_tree/segment_tree_other.py) * [Treap](data_structures/binary_tree/treap.py) * [Wavelet Tree](data_structures/binary_tree/wavelet_tree.py) * Disjoint Set * [Alternate Disjoint Set](data_structures/disjoint_set/alternate_disjoint_set.py) * [Disjoint Set](data_structures/disjoint_set/disjoint_set.py) * Hashing * [Bloom Filter](data_structures/hashing/bloom_filter.py) * [Double Hash](data_structures/hashing/double_hash.py) * [Hash Map](data_structures/hashing/hash_map.py) * [Hash Table](data_structures/hashing/hash_table.py) * [Hash Table With Linked List](data_structures/hashing/hash_table_with_linked_list.py) * Number Theory * [Prime Numbers](data_structures/hashing/number_theory/prime_numbers.py) * [Quadratic Probing](data_structures/hashing/quadratic_probing.py) * Tests * [Test Hash Map](data_structures/hashing/tests/test_hash_map.py) * Heap * [Binomial Heap](data_structures/heap/binomial_heap.py) * [Heap](data_structures/heap/heap.py) * [Heap Generic](data_structures/heap/heap_generic.py) * [Max Heap](data_structures/heap/max_heap.py) * [Min Heap](data_structures/heap/min_heap.py) * [Randomized Heap](data_structures/heap/randomized_heap.py) * [Skew Heap](data_structures/heap/skew_heap.py) * Linked List * [Circular Linked List](data_structures/linked_list/circular_linked_list.py) * [Deque Doubly](data_structures/linked_list/deque_doubly.py) * [Doubly Linked List](data_structures/linked_list/doubly_linked_list.py) * [Doubly Linked List Two](data_structures/linked_list/doubly_linked_list_two.py) * [From Sequence](data_structures/linked_list/from_sequence.py) * [Has Loop](data_structures/linked_list/has_loop.py) * [Is Palindrome](data_structures/linked_list/is_palindrome.py) * [Merge Two Lists](data_structures/linked_list/merge_two_lists.py) * [Middle Element Of Linked List](data_structures/linked_list/middle_element_of_linked_list.py) * [Print Reverse](data_structures/linked_list/print_reverse.py) * [Singly Linked List](data_structures/linked_list/singly_linked_list.py) * [Skip List](data_structures/linked_list/skip_list.py) * [Swap Nodes](data_structures/linked_list/swap_nodes.py) * Queue * [Circular Queue](data_structures/queue/circular_queue.py) * [Circular Queue Linked List](data_structures/queue/circular_queue_linked_list.py) * [Double Ended Queue](data_structures/queue/double_ended_queue.py) * [Linked Queue](data_structures/queue/linked_queue.py) * [Priority Queue Using List](data_structures/queue/priority_queue_using_list.py) * [Queue By Two Stacks](data_structures/queue/queue_by_two_stacks.py) * [Queue On List](data_structures/queue/queue_on_list.py) * [Queue On Pseudo Stack](data_structures/queue/queue_on_pseudo_stack.py) * Stacks * [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py) * [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py) * [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py) * [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py) * [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py) * [Next Greater Element](data_structures/stacks/next_greater_element.py) * [Postfix Evaluation](data_structures/stacks/postfix_evaluation.py) * [Prefix Evaluation](data_structures/stacks/prefix_evaluation.py) * [Stack](data_structures/stacks/stack.py) * [Stack With Doubly Linked List](data_structures/stacks/stack_with_doubly_linked_list.py) * [Stack With Singly Linked List](data_structures/stacks/stack_with_singly_linked_list.py) * [Stock Span Problem](data_structures/stacks/stock_span_problem.py) * Trie * [Radix Tree](data_structures/trie/radix_tree.py) * [Trie](data_structures/trie/trie.py) ## Digital Image Processing * [Change Brightness](digital_image_processing/change_brightness.py) * [Change Contrast](digital_image_processing/change_contrast.py) * [Convert To Negative](digital_image_processing/convert_to_negative.py) * Dithering * [Burkes](digital_image_processing/dithering/burkes.py) * Edge Detection * [Canny](digital_image_processing/edge_detection/canny.py) * Filters * [Bilateral Filter](digital_image_processing/filters/bilateral_filter.py) * [Convolve](digital_image_processing/filters/convolve.py) * [Gabor Filter](digital_image_processing/filters/gabor_filter.py) * [Gaussian Filter](digital_image_processing/filters/gaussian_filter.py) * [Local Binary Pattern](digital_image_processing/filters/local_binary_pattern.py) * [Median Filter](digital_image_processing/filters/median_filter.py) * [Sobel Filter](digital_image_processing/filters/sobel_filter.py) * Histogram Equalization * [Histogram Stretch](digital_image_processing/histogram_equalization/histogram_stretch.py) * [Index Calculation](digital_image_processing/index_calculation.py) * Morphological Operations * [Dilation Operation](digital_image_processing/morphological_operations/dilation_operation.py) * [Erosion Operation](digital_image_processing/morphological_operations/erosion_operation.py) * Resize * [Resize](digital_image_processing/resize/resize.py) * Rotation * [Rotation](digital_image_processing/rotation/rotation.py) * [Sepia](digital_image_processing/sepia.py) * [Test Digital Image Processing](digital_image_processing/test_digital_image_processing.py) ## Divide And Conquer * [Closest Pair Of Points](divide_and_conquer/closest_pair_of_points.py) * [Convex Hull](divide_and_conquer/convex_hull.py) * [Heaps Algorithm](divide_and_conquer/heaps_algorithm.py) * [Heaps Algorithm Iterative](divide_and_conquer/heaps_algorithm_iterative.py) * [Inversions](divide_and_conquer/inversions.py) * [Kth Order Statistic](divide_and_conquer/kth_order_statistic.py) * [Max Difference Pair](divide_and_conquer/max_difference_pair.py) * [Max Subarray Sum](divide_and_conquer/max_subarray_sum.py) * [Mergesort](divide_and_conquer/mergesort.py) * [Peak](divide_and_conquer/peak.py) * [Power](divide_and_conquer/power.py) * [Strassen Matrix Multiplication](divide_and_conquer/strassen_matrix_multiplication.py) ## Dynamic Programming * [Abbreviation](dynamic_programming/abbreviation.py) * [All Construct](dynamic_programming/all_construct.py) * [Bitmask](dynamic_programming/bitmask.py) * [Catalan Numbers](dynamic_programming/catalan_numbers.py) * [Climbing Stairs](dynamic_programming/climbing_stairs.py) * [Combination Sum Iv](dynamic_programming/combination_sum_iv.py) * [Edit Distance](dynamic_programming/edit_distance.py) * [Factorial](dynamic_programming/factorial.py) * [Fast Fibonacci](dynamic_programming/fast_fibonacci.py) * [Fibonacci](dynamic_programming/fibonacci.py) * [Fizz Buzz](dynamic_programming/fizz_buzz.py) * [Floyd Warshall](dynamic_programming/floyd_warshall.py) * [Integer Partition](dynamic_programming/integer_partition.py) * [Iterating Through Submasks](dynamic_programming/iterating_through_submasks.py) * [K Means Clustering Tensorflow](dynamic_programming/k_means_clustering_tensorflow.py) * [Knapsack](dynamic_programming/knapsack.py) * [Longest Common Subsequence](dynamic_programming/longest_common_subsequence.py) * [Longest Common Substring](dynamic_programming/longest_common_substring.py) * [Longest Increasing Subsequence](dynamic_programming/longest_increasing_subsequence.py) * [Longest Increasing Subsequence O(Nlogn)](dynamic_programming/longest_increasing_subsequence_o(nlogn).py) * [Longest Sub Array](dynamic_programming/longest_sub_array.py) * [Matrix Chain Order](dynamic_programming/matrix_chain_order.py) * [Max Non Adjacent Sum](dynamic_programming/max_non_adjacent_sum.py) * [Max Product Subarray](dynamic_programming/max_product_subarray.py) * [Max Sub Array](dynamic_programming/max_sub_array.py) * [Max Sum Contiguous Subsequence](dynamic_programming/max_sum_contiguous_subsequence.py) * [Min Distance Up Bottom](dynamic_programming/min_distance_up_bottom.py) * [Minimum Coin Change](dynamic_programming/minimum_coin_change.py) * [Minimum Cost Path](dynamic_programming/minimum_cost_path.py) * [Minimum Partition](dynamic_programming/minimum_partition.py) * [Minimum Size Subarray Sum](dynamic_programming/minimum_size_subarray_sum.py) * [Minimum Squares To Represent A Number](dynamic_programming/minimum_squares_to_represent_a_number.py) * [Minimum Steps To One](dynamic_programming/minimum_steps_to_one.py) * [Minimum Tickets Cost](dynamic_programming/minimum_tickets_cost.py) * [Optimal Binary Search Tree](dynamic_programming/optimal_binary_search_tree.py) * [Palindrome Partitioning](dynamic_programming/palindrome_partitioning.py) * [Rod Cutting](dynamic_programming/rod_cutting.py) * [Subset Generation](dynamic_programming/subset_generation.py) * [Sum Of Subset](dynamic_programming/sum_of_subset.py) * [Viterbi](dynamic_programming/viterbi.py) * [Word Break](dynamic_programming/word_break.py) ## Electronics * [Apparent Power](electronics/apparent_power.py) * [Builtin Voltage](electronics/builtin_voltage.py) * [Carrier Concentration](electronics/carrier_concentration.py) * [Circular Convolution](electronics/circular_convolution.py) * [Coulombs Law](electronics/coulombs_law.py) * [Electric Conductivity](electronics/electric_conductivity.py) * [Electric Power](electronics/electric_power.py) * [Electrical Impedance](electronics/electrical_impedance.py) * [Ind Reactance](electronics/ind_reactance.py) * [Ohms Law](electronics/ohms_law.py) * [Real And Reactive Power](electronics/real_and_reactive_power.py) * [Resistor Equivalence](electronics/resistor_equivalence.py) * [Resonant Frequency](electronics/resonant_frequency.py) ## File Transfer * [Receive File](file_transfer/receive_file.py) * [Send File](file_transfer/send_file.py) * Tests * [Test Send File](file_transfer/tests/test_send_file.py) ## Financial * [Equated Monthly Installments](financial/equated_monthly_installments.py) * [Interest](financial/interest.py) * [Present Value](financial/present_value.py) * [Price Plus Tax](financial/price_plus_tax.py) ## Fractals * [Julia Sets](fractals/julia_sets.py) * [Koch Snowflake](fractals/koch_snowflake.py) * [Mandelbrot](fractals/mandelbrot.py) * [Sierpinski Triangle](fractals/sierpinski_triangle.py) ## Fuzzy Logic * [Fuzzy Operations](fuzzy_logic/fuzzy_operations.py) ## Genetic Algorithm * [Basic String](genetic_algorithm/basic_string.py) ## Geodesy * [Haversine Distance](geodesy/haversine_distance.py) * [Lamberts Ellipsoidal Distance](geodesy/lamberts_ellipsoidal_distance.py) ## Graphics * [Bezier Curve](graphics/bezier_curve.py) * [Vector3 For 2D Rendering](graphics/vector3_for_2d_rendering.py) ## Graphs * [A Star](graphs/a_star.py) * [Articulation Points](graphs/articulation_points.py) * [Basic Graphs](graphs/basic_graphs.py) * [Bellman Ford](graphs/bellman_ford.py) * [Bi Directional Dijkstra](graphs/bi_directional_dijkstra.py) * [Bidirectional A Star](graphs/bidirectional_a_star.py) * [Bidirectional Breadth First Search](graphs/bidirectional_breadth_first_search.py) * [Boruvka](graphs/boruvka.py) * [Breadth First Search](graphs/breadth_first_search.py) * [Breadth First Search 2](graphs/breadth_first_search_2.py) * [Breadth First Search Shortest Path](graphs/breadth_first_search_shortest_path.py) * [Breadth First Search Shortest Path 2](graphs/breadth_first_search_shortest_path_2.py) * [Breadth First Search Zero One Shortest Path](graphs/breadth_first_search_zero_one_shortest_path.py) * [Check Bipartite Graph Bfs](graphs/check_bipartite_graph_bfs.py) * [Check Bipartite Graph Dfs](graphs/check_bipartite_graph_dfs.py) * [Check Cycle](graphs/check_cycle.py) * [Connected Components](graphs/connected_components.py) * [Depth First Search](graphs/depth_first_search.py) * [Depth First Search 2](graphs/depth_first_search_2.py) * [Dijkstra](graphs/dijkstra.py) * [Dijkstra 2](graphs/dijkstra_2.py) * [Dijkstra Algorithm](graphs/dijkstra_algorithm.py) * [Dijkstra Alternate](graphs/dijkstra_alternate.py) * [Dijkstra Binary Grid](graphs/dijkstra_binary_grid.py) * [Dinic](graphs/dinic.py) * [Directed And Undirected (Weighted) Graph](graphs/directed_and_undirected_(weighted)_graph.py) * [Edmonds Karp Multiple Source And Sink](graphs/edmonds_karp_multiple_source_and_sink.py) * [Eulerian Path And Circuit For Undirected Graph](graphs/eulerian_path_and_circuit_for_undirected_graph.py) * [Even Tree](graphs/even_tree.py) * [Finding Bridges](graphs/finding_bridges.py) * [Frequent Pattern Graph Miner](graphs/frequent_pattern_graph_miner.py) * [G Topological Sort](graphs/g_topological_sort.py) * [Gale Shapley Bigraph](graphs/gale_shapley_bigraph.py) * [Graph Adjacency List](graphs/graph_adjacency_list.py) * [Graph Adjacency Matrix](graphs/graph_adjacency_matrix.py) * [Graph List](graphs/graph_list.py) * [Graphs Floyd Warshall](graphs/graphs_floyd_warshall.py) * [Greedy Best First](graphs/greedy_best_first.py) * [Greedy Min Vertex Cover](graphs/greedy_min_vertex_cover.py) * [Kahns Algorithm Long](graphs/kahns_algorithm_long.py) * [Kahns Algorithm Topo](graphs/kahns_algorithm_topo.py) * [Karger](graphs/karger.py) * [Markov Chain](graphs/markov_chain.py) * [Matching Min Vertex Cover](graphs/matching_min_vertex_cover.py) * [Minimum Path Sum](graphs/minimum_path_sum.py) * [Minimum Spanning Tree Boruvka](graphs/minimum_spanning_tree_boruvka.py) * [Minimum Spanning Tree Kruskal](graphs/minimum_spanning_tree_kruskal.py) * [Minimum Spanning Tree Kruskal2](graphs/minimum_spanning_tree_kruskal2.py) * [Minimum Spanning Tree Prims](graphs/minimum_spanning_tree_prims.py) * [Minimum Spanning Tree Prims2](graphs/minimum_spanning_tree_prims2.py) * [Multi Heuristic Astar](graphs/multi_heuristic_astar.py) * [Page Rank](graphs/page_rank.py) * [Prim](graphs/prim.py) * [Random Graph Generator](graphs/random_graph_generator.py) * [Scc Kosaraju](graphs/scc_kosaraju.py) * [Strongly Connected Components](graphs/strongly_connected_components.py) * [Tarjans Scc](graphs/tarjans_scc.py) * Tests * [Test Min Spanning Tree Kruskal](graphs/tests/test_min_spanning_tree_kruskal.py) * [Test Min Spanning Tree Prim](graphs/tests/test_min_spanning_tree_prim.py) ## Greedy Methods * [Fractional Knapsack](greedy_methods/fractional_knapsack.py) * [Fractional Knapsack 2](greedy_methods/fractional_knapsack_2.py) * [Minimum Waiting Time](greedy_methods/minimum_waiting_time.py) * [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py) ## Hashes * [Adler32](hashes/adler32.py) * [Chaos Machine](hashes/chaos_machine.py) * [Djb2](hashes/djb2.py) * [Elf](hashes/elf.py) * [Enigma Machine](hashes/enigma_machine.py) * [Hamming Code](hashes/hamming_code.py) * [Luhn](hashes/luhn.py) * [Md5](hashes/md5.py) * [Sdbm](hashes/sdbm.py) * [Sha1](hashes/sha1.py) * [Sha256](hashes/sha256.py) ## Knapsack * [Greedy Knapsack](knapsack/greedy_knapsack.py) * [Knapsack](knapsack/knapsack.py) * [Recursive Approach Knapsack](knapsack/recursive_approach_knapsack.py) * Tests * [Test Greedy Knapsack](knapsack/tests/test_greedy_knapsack.py) * [Test Knapsack](knapsack/tests/test_knapsack.py) ## Linear Algebra * Src * [Conjugate Gradient](linear_algebra/src/conjugate_gradient.py) * [Lib](linear_algebra/src/lib.py) * [Polynom For Points](linear_algebra/src/polynom_for_points.py) * [Power Iteration](linear_algebra/src/power_iteration.py) * [Rank Of Matrix](linear_algebra/src/rank_of_matrix.py) * [Rayleigh Quotient](linear_algebra/src/rayleigh_quotient.py) * [Schur Complement](linear_algebra/src/schur_complement.py) * [Test Linear Algebra](linear_algebra/src/test_linear_algebra.py) * [Transformations 2D](linear_algebra/src/transformations_2d.py) ## Linear Programming * [Simplex](linear_programming/simplex.py) ## Machine Learning * [Astar](machine_learning/astar.py) * [Data Transformations](machine_learning/data_transformations.py) * [Decision Tree](machine_learning/decision_tree.py) * [Dimensionality Reduction](machine_learning/dimensionality_reduction.py) * Forecasting * [Run](machine_learning/forecasting/run.py) * [Gradient Descent](machine_learning/gradient_descent.py) * [K Means Clust](machine_learning/k_means_clust.py) * [K Nearest Neighbours](machine_learning/k_nearest_neighbours.py) * [Knn Sklearn](machine_learning/knn_sklearn.py) * [Linear Discriminant Analysis](machine_learning/linear_discriminant_analysis.py) * [Linear Regression](machine_learning/linear_regression.py) * Local Weighted Learning * [Local Weighted Learning](machine_learning/local_weighted_learning/local_weighted_learning.py) * [Logistic Regression](machine_learning/logistic_regression.py) * Lstm * [Lstm Prediction](machine_learning/lstm/lstm_prediction.py) * [Multilayer Perceptron Classifier](machine_learning/multilayer_perceptron_classifier.py) * [Polymonial Regression](machine_learning/polymonial_regression.py) * [Scoring Functions](machine_learning/scoring_functions.py) * [Self Organizing Map](machine_learning/self_organizing_map.py) * [Sequential Minimum Optimization](machine_learning/sequential_minimum_optimization.py) * [Similarity Search](machine_learning/similarity_search.py) * [Support Vector Machines](machine_learning/support_vector_machines.py) * [Word Frequency Functions](machine_learning/word_frequency_functions.py) * [Xgboost Classifier](machine_learning/xgboost_classifier.py) * [Xgboost Regressor](machine_learning/xgboost_regressor.py) ## Maths * [3N Plus 1](maths/3n_plus_1.py) * [Abs](maths/abs.py) * [Add](maths/add.py) * [Addition Without Arithmetic](maths/addition_without_arithmetic.py) * [Aliquot Sum](maths/aliquot_sum.py) * [Allocation Number](maths/allocation_number.py) * [Arc Length](maths/arc_length.py) * [Area](maths/area.py) * [Area Under Curve](maths/area_under_curve.py) * [Armstrong Numbers](maths/armstrong_numbers.py) * [Automorphic Number](maths/automorphic_number.py) * [Average Absolute Deviation](maths/average_absolute_deviation.py) * [Average Mean](maths/average_mean.py) * [Average Median](maths/average_median.py) * [Average Mode](maths/average_mode.py) * [Bailey Borwein Plouffe](maths/bailey_borwein_plouffe.py) * [Basic Maths](maths/basic_maths.py) * [Binary Exp Mod](maths/binary_exp_mod.py) * [Binary Exponentiation](maths/binary_exponentiation.py) * [Binary Exponentiation 2](maths/binary_exponentiation_2.py) * [Binary Exponentiation 3](maths/binary_exponentiation_3.py) * [Binomial Coefficient](maths/binomial_coefficient.py) * [Binomial Distribution](maths/binomial_distribution.py) * [Bisection](maths/bisection.py) * [Carmichael Number](maths/carmichael_number.py) * [Catalan Number](maths/catalan_number.py) * [Ceil](maths/ceil.py) * [Check Polygon](maths/check_polygon.py) * [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py) * [Collatz Sequence](maths/collatz_sequence.py) * [Combinations](maths/combinations.py) * [Decimal Isolate](maths/decimal_isolate.py) * [Decimal To Fraction](maths/decimal_to_fraction.py) * [Dodecahedron](maths/dodecahedron.py) * [Double Factorial Iterative](maths/double_factorial_iterative.py) * [Double Factorial Recursive](maths/double_factorial_recursive.py) * [Dual Number Automatic Differentiation](maths/dual_number_automatic_differentiation.py) * [Entropy](maths/entropy.py) * [Euclidean Distance](maths/euclidean_distance.py) * [Euclidean Gcd](maths/euclidean_gcd.py) * [Euler Method](maths/euler_method.py) * [Euler Modified](maths/euler_modified.py) * [Eulers Totient](maths/eulers_totient.py) * [Extended Euclidean Algorithm](maths/extended_euclidean_algorithm.py) * [Factorial](maths/factorial.py) * [Factors](maths/factors.py) * [Fermat Little Theorem](maths/fermat_little_theorem.py) * [Fibonacci](maths/fibonacci.py) * [Find Max](maths/find_max.py) * [Find Max Recursion](maths/find_max_recursion.py) * [Find Min](maths/find_min.py) * [Find Min Recursion](maths/find_min_recursion.py) * [Floor](maths/floor.py) * [Gamma](maths/gamma.py) * [Gamma Recursive](maths/gamma_recursive.py) * [Gaussian](maths/gaussian.py) * [Gaussian Error Linear Unit](maths/gaussian_error_linear_unit.py) * [Gcd Of N Numbers](maths/gcd_of_n_numbers.py) * [Greatest Common Divisor](maths/greatest_common_divisor.py) * [Greedy Coin Change](maths/greedy_coin_change.py) * [Hamming Numbers](maths/hamming_numbers.py) * [Hardy Ramanujanalgo](maths/hardy_ramanujanalgo.py) * [Hexagonal Number](maths/hexagonal_number.py) * [Integration By Simpson Approx](maths/integration_by_simpson_approx.py) * [Is Int Palindrome](maths/is_int_palindrome.py) * [Is Ip V4 Address Valid](maths/is_ip_v4_address_valid.py) * [Is Square Free](maths/is_square_free.py) * [Jaccard Similarity](maths/jaccard_similarity.py) * [Juggler Sequence](maths/juggler_sequence.py) * [Kadanes](maths/kadanes.py) * [Karatsuba](maths/karatsuba.py) * [Krishnamurthy Number](maths/krishnamurthy_number.py) * [Kth Lexicographic Permutation](maths/kth_lexicographic_permutation.py) * [Largest Of Very Large Numbers](maths/largest_of_very_large_numbers.py) * [Largest Subarray Sum](maths/largest_subarray_sum.py) * [Least Common Multiple](maths/least_common_multiple.py) * [Line Length](maths/line_length.py) * [Liouville Lambda](maths/liouville_lambda.py) * [Lucas Lehmer Primality Test](maths/lucas_lehmer_primality_test.py) * [Lucas Series](maths/lucas_series.py) * [Maclaurin Series](maths/maclaurin_series.py) * [Manhattan Distance](maths/manhattan_distance.py) * [Matrix Exponentiation](maths/matrix_exponentiation.py) * [Max Sum Sliding Window](maths/max_sum_sliding_window.py) * [Median Of Two Arrays](maths/median_of_two_arrays.py) * [Miller Rabin](maths/miller_rabin.py) * [Mobius Function](maths/mobius_function.py) * [Modular Exponential](maths/modular_exponential.py) * [Monte Carlo](maths/monte_carlo.py) * [Monte Carlo Dice](maths/monte_carlo_dice.py) * [Nevilles Method](maths/nevilles_method.py) * [Newton Raphson](maths/newton_raphson.py) * [Number Of Digits](maths/number_of_digits.py) * [Numerical Integration](maths/numerical_integration.py) * [Odd Sieve](maths/odd_sieve.py) * [Perfect Cube](maths/perfect_cube.py) * [Perfect Number](maths/perfect_number.py) * [Perfect Square](maths/perfect_square.py) * [Persistence](maths/persistence.py) * [Pi Generator](maths/pi_generator.py) * [Pi Monte Carlo Estimation](maths/pi_monte_carlo_estimation.py) * [Points Are Collinear 3D](maths/points_are_collinear_3d.py) * [Pollard Rho](maths/pollard_rho.py) * [Polynomial Evaluation](maths/polynomial_evaluation.py) * Polynomials * [Single Indeterminate Operations](maths/polynomials/single_indeterminate_operations.py) * [Power Using Recursion](maths/power_using_recursion.py) * [Prime Check](maths/prime_check.py) * [Prime Factors](maths/prime_factors.py) * [Prime Numbers](maths/prime_numbers.py) * [Prime Sieve Eratosthenes](maths/prime_sieve_eratosthenes.py) * [Primelib](maths/primelib.py) * [Print Multiplication Table](maths/print_multiplication_table.py) * [Pronic Number](maths/pronic_number.py) * [Proth Number](maths/proth_number.py) * [Pythagoras](maths/pythagoras.py) * [Qr Decomposition](maths/qr_decomposition.py) * [Quadratic Equations Complex Numbers](maths/quadratic_equations_complex_numbers.py) * [Radians](maths/radians.py) * [Radix2 Fft](maths/radix2_fft.py) * [Relu](maths/relu.py) * [Remove Digit](maths/remove_digit.py) * [Runge Kutta](maths/runge_kutta.py) * [Segmented Sieve](maths/segmented_sieve.py) * Series * [Arithmetic](maths/series/arithmetic.py) * [Geometric](maths/series/geometric.py) * [Geometric Series](maths/series/geometric_series.py) * [Harmonic](maths/series/harmonic.py) * [Harmonic Series](maths/series/harmonic_series.py) * [Hexagonal Numbers](maths/series/hexagonal_numbers.py) * [P Series](maths/series/p_series.py) * [Sieve Of Eratosthenes](maths/sieve_of_eratosthenes.py) * [Sigmoid](maths/sigmoid.py) * [Sigmoid Linear Unit](maths/sigmoid_linear_unit.py) * [Signum](maths/signum.py) * [Simpson Rule](maths/simpson_rule.py) * [Simultaneous Linear Equation Solver](maths/simultaneous_linear_equation_solver.py) * [Sin](maths/sin.py) * [Sock Merchant](maths/sock_merchant.py) * [Softmax](maths/softmax.py) * [Square Root](maths/square_root.py) * [Sum Of Arithmetic Series](maths/sum_of_arithmetic_series.py) * [Sum Of Digits](maths/sum_of_digits.py) * [Sum Of Geometric Progression](maths/sum_of_geometric_progression.py) * [Sum Of Harmonic Series](maths/sum_of_harmonic_series.py) * [Sumset](maths/sumset.py) * [Sylvester Sequence](maths/sylvester_sequence.py) * [Tanh](maths/tanh.py) * [Test Prime Check](maths/test_prime_check.py) * [Trapezoidal Rule](maths/trapezoidal_rule.py) * [Triplet Sum](maths/triplet_sum.py) * [Twin Prime](maths/twin_prime.py) * [Two Pointer](maths/two_pointer.py) * [Two Sum](maths/two_sum.py) * [Ugly Numbers](maths/ugly_numbers.py) * [Volume](maths/volume.py) * [Weird Number](maths/weird_number.py) * [Zellers Congruence](maths/zellers_congruence.py) ## Matrix * [Binary Search Matrix](matrix/binary_search_matrix.py) * [Count Islands In Matrix](matrix/count_islands_in_matrix.py) * [Count Negative Numbers In Sorted Matrix](matrix/count_negative_numbers_in_sorted_matrix.py) * [Count Paths](matrix/count_paths.py) * [Cramers Rule 2X2](matrix/cramers_rule_2x2.py) * [Inverse Of Matrix](matrix/inverse_of_matrix.py) * [Largest Square Area In Matrix](matrix/largest_square_area_in_matrix.py) * [Matrix Class](matrix/matrix_class.py) * [Matrix Operation](matrix/matrix_operation.py) * [Max Area Of Island](matrix/max_area_of_island.py) * [Nth Fibonacci Using Matrix Exponentiation](matrix/nth_fibonacci_using_matrix_exponentiation.py) * [Pascal Triangle](matrix/pascal_triangle.py) * [Rotate Matrix](matrix/rotate_matrix.py) * [Searching In Sorted Matrix](matrix/searching_in_sorted_matrix.py) * [Sherman Morrison](matrix/sherman_morrison.py) * [Spiral Print](matrix/spiral_print.py) * Tests * [Test Matrix Operation](matrix/tests/test_matrix_operation.py) ## Networking Flow * [Ford Fulkerson](networking_flow/ford_fulkerson.py) * [Minimum Cut](networking_flow/minimum_cut.py) ## Neural Network * [2 Hidden Layers Neural Network](neural_network/2_hidden_layers_neural_network.py) * Activation Functions * [Exponential Linear Unit](neural_network/activation_functions/exponential_linear_unit.py) * [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py) * [Convolution Neural Network](neural_network/convolution_neural_network.py) * [Input Data](neural_network/input_data.py) * [Perceptron](neural_network/perceptron.py) * [Simple Neural Network](neural_network/simple_neural_network.py) ## Other * [Activity Selection](other/activity_selection.py) * [Alternative List Arrange](other/alternative_list_arrange.py) * [Davisb Putnamb Logemannb Loveland](other/davisb_putnamb_logemannb_loveland.py) * [Dijkstra Bankers Algorithm](other/dijkstra_bankers_algorithm.py) * [Doomsday](other/doomsday.py) * [Fischer Yates Shuffle](other/fischer_yates_shuffle.py) * [Gauss Easter](other/gauss_easter.py) * [Graham Scan](other/graham_scan.py) * [Greedy](other/greedy.py) * [Guess The Number Search](other/guess_the_number_search.py) * [H Index](other/h_index.py) * [Least Recently Used](other/least_recently_used.py) * [Lfu Cache](other/lfu_cache.py) * [Linear Congruential Generator](other/linear_congruential_generator.py) * [Lru Cache](other/lru_cache.py) * [Magicdiamondpattern](other/magicdiamondpattern.py) * [Maximum Subarray](other/maximum_subarray.py) * [Maximum Subsequence](other/maximum_subsequence.py) * [Nested Brackets](other/nested_brackets.py) * [Number Container System](other/number_container_system.py) * [Password](other/password.py) * [Quine](other/quine.py) * [Scoring Algorithm](other/scoring_algorithm.py) * [Sdes](other/sdes.py) * [Tower Of Hanoi](other/tower_of_hanoi.py) ## Physics * [Archimedes Principle](physics/archimedes_principle.py) * [Casimir Effect](physics/casimir_effect.py) * [Centripetal Force](physics/centripetal_force.py) * [Grahams Law](physics/grahams_law.py) * [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py) * [Hubble Parameter](physics/hubble_parameter.py) * [Ideal Gas Law](physics/ideal_gas_law.py) * [Kinetic Energy](physics/kinetic_energy.py) * [Lorentz Transformation Four Vector](physics/lorentz_transformation_four_vector.py) * [Malus Law](physics/malus_law.py) * [N Body Simulation](physics/n_body_simulation.py) * [Newtons Law Of Gravitation](physics/newtons_law_of_gravitation.py) * [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py) * [Potential Energy](physics/potential_energy.py) * [Rms Speed Of Molecule](physics/rms_speed_of_molecule.py) * [Shear Stress](physics/shear_stress.py) * [Speed Of Sound](physics/speed_of_sound.py) ## Project Euler * Problem 001 * [Sol1](project_euler/problem_001/sol1.py) * [Sol2](project_euler/problem_001/sol2.py) * [Sol3](project_euler/problem_001/sol3.py) * [Sol4](project_euler/problem_001/sol4.py) * [Sol5](project_euler/problem_001/sol5.py) * [Sol6](project_euler/problem_001/sol6.py) * [Sol7](project_euler/problem_001/sol7.py) * Problem 002 * [Sol1](project_euler/problem_002/sol1.py) * [Sol2](project_euler/problem_002/sol2.py) * [Sol3](project_euler/problem_002/sol3.py) * [Sol4](project_euler/problem_002/sol4.py) * [Sol5](project_euler/problem_002/sol5.py) * Problem 003 * [Sol1](project_euler/problem_003/sol1.py) * [Sol2](project_euler/problem_003/sol2.py) * [Sol3](project_euler/problem_003/sol3.py) * Problem 004 * [Sol1](project_euler/problem_004/sol1.py) * [Sol2](project_euler/problem_004/sol2.py) * Problem 005 * [Sol1](project_euler/problem_005/sol1.py) * [Sol2](project_euler/problem_005/sol2.py) * Problem 006 * [Sol1](project_euler/problem_006/sol1.py) * [Sol2](project_euler/problem_006/sol2.py) * [Sol3](project_euler/problem_006/sol3.py) * [Sol4](project_euler/problem_006/sol4.py) * Problem 007 * [Sol1](project_euler/problem_007/sol1.py) * [Sol2](project_euler/problem_007/sol2.py) * [Sol3](project_euler/problem_007/sol3.py) * Problem 008 * [Sol1](project_euler/problem_008/sol1.py) * [Sol2](project_euler/problem_008/sol2.py) * [Sol3](project_euler/problem_008/sol3.py) * Problem 009 * [Sol1](project_euler/problem_009/sol1.py) * [Sol2](project_euler/problem_009/sol2.py) * [Sol3](project_euler/problem_009/sol3.py) * Problem 010 * [Sol1](project_euler/problem_010/sol1.py) * [Sol2](project_euler/problem_010/sol2.py) * [Sol3](project_euler/problem_010/sol3.py) * Problem 011 * [Sol1](project_euler/problem_011/sol1.py) * [Sol2](project_euler/problem_011/sol2.py) * Problem 012 * [Sol1](project_euler/problem_012/sol1.py) * [Sol2](project_euler/problem_012/sol2.py) * Problem 013 * [Sol1](project_euler/problem_013/sol1.py) * Problem 014 * [Sol1](project_euler/problem_014/sol1.py) * [Sol2](project_euler/problem_014/sol2.py) * Problem 015 * [Sol1](project_euler/problem_015/sol1.py) * Problem 016 * [Sol1](project_euler/problem_016/sol1.py) * [Sol2](project_euler/problem_016/sol2.py) * Problem 017 * [Sol1](project_euler/problem_017/sol1.py) * Problem 018 * [Solution](project_euler/problem_018/solution.py) * Problem 019 * [Sol1](project_euler/problem_019/sol1.py) * Problem 020 * [Sol1](project_euler/problem_020/sol1.py) * [Sol2](project_euler/problem_020/sol2.py) * [Sol3](project_euler/problem_020/sol3.py) * [Sol4](project_euler/problem_020/sol4.py) * Problem 021 * [Sol1](project_euler/problem_021/sol1.py) * Problem 022 * [Sol1](project_euler/problem_022/sol1.py) * [Sol2](project_euler/problem_022/sol2.py) * Problem 023 * [Sol1](project_euler/problem_023/sol1.py) * Problem 024 * [Sol1](project_euler/problem_024/sol1.py) * Problem 025 * [Sol1](project_euler/problem_025/sol1.py) * [Sol2](project_euler/problem_025/sol2.py) * [Sol3](project_euler/problem_025/sol3.py) * Problem 026 * [Sol1](project_euler/problem_026/sol1.py) * Problem 027 * [Sol1](project_euler/problem_027/sol1.py) * Problem 028 * [Sol1](project_euler/problem_028/sol1.py) * Problem 029 * [Sol1](project_euler/problem_029/sol1.py) * Problem 030 * [Sol1](project_euler/problem_030/sol1.py) * Problem 031 * [Sol1](project_euler/problem_031/sol1.py) * [Sol2](project_euler/problem_031/sol2.py) * Problem 032 * [Sol32](project_euler/problem_032/sol32.py) * Problem 033 * [Sol1](project_euler/problem_033/sol1.py) * Problem 034 * [Sol1](project_euler/problem_034/sol1.py) * Problem 035 * [Sol1](project_euler/problem_035/sol1.py) * Problem 036 * [Sol1](project_euler/problem_036/sol1.py) * Problem 037 * [Sol1](project_euler/problem_037/sol1.py) * Problem 038 * [Sol1](project_euler/problem_038/sol1.py) * Problem 039 * [Sol1](project_euler/problem_039/sol1.py) * Problem 040 * [Sol1](project_euler/problem_040/sol1.py) * Problem 041 * [Sol1](project_euler/problem_041/sol1.py) * Problem 042 * [Solution42](project_euler/problem_042/solution42.py) * Problem 043 * [Sol1](project_euler/problem_043/sol1.py) * Problem 044 * [Sol1](project_euler/problem_044/sol1.py) * Problem 045 * [Sol1](project_euler/problem_045/sol1.py) * Problem 046 * [Sol1](project_euler/problem_046/sol1.py) * Problem 047 * [Sol1](project_euler/problem_047/sol1.py) * Problem 048 * [Sol1](project_euler/problem_048/sol1.py) * Problem 049 * [Sol1](project_euler/problem_049/sol1.py) * Problem 050 * [Sol1](project_euler/problem_050/sol1.py) * Problem 051 * [Sol1](project_euler/problem_051/sol1.py) * Problem 052 * [Sol1](project_euler/problem_052/sol1.py) * Problem 053 * [Sol1](project_euler/problem_053/sol1.py) * Problem 054 * [Sol1](project_euler/problem_054/sol1.py) * [Test Poker Hand](project_euler/problem_054/test_poker_hand.py) * Problem 055 * [Sol1](project_euler/problem_055/sol1.py) * Problem 056 * [Sol1](project_euler/problem_056/sol1.py) * Problem 057 * [Sol1](project_euler/problem_057/sol1.py) * Problem 058 * [Sol1](project_euler/problem_058/sol1.py) * Problem 059 * [Sol1](project_euler/problem_059/sol1.py) * Problem 062 * [Sol1](project_euler/problem_062/sol1.py) * Problem 063 * [Sol1](project_euler/problem_063/sol1.py) * Problem 064 * [Sol1](project_euler/problem_064/sol1.py) * Problem 065 * [Sol1](project_euler/problem_065/sol1.py) * Problem 067 * [Sol1](project_euler/problem_067/sol1.py) * [Sol2](project_euler/problem_067/sol2.py) * Problem 068 * [Sol1](project_euler/problem_068/sol1.py) * Problem 069 * [Sol1](project_euler/problem_069/sol1.py) * Problem 070 * [Sol1](project_euler/problem_070/sol1.py) * Problem 071 * [Sol1](project_euler/problem_071/sol1.py) * Problem 072 * [Sol1](project_euler/problem_072/sol1.py) * [Sol2](project_euler/problem_072/sol2.py) * Problem 073 * [Sol1](project_euler/problem_073/sol1.py) * Problem 074 * [Sol1](project_euler/problem_074/sol1.py) * [Sol2](project_euler/problem_074/sol2.py) * Problem 075 * [Sol1](project_euler/problem_075/sol1.py) * Problem 076 * [Sol1](project_euler/problem_076/sol1.py) * Problem 077 * [Sol1](project_euler/problem_077/sol1.py) * Problem 078 * [Sol1](project_euler/problem_078/sol1.py) * Problem 079 * [Sol1](project_euler/problem_079/sol1.py) * Problem 080 * [Sol1](project_euler/problem_080/sol1.py) * Problem 081 * [Sol1](project_euler/problem_081/sol1.py) * Problem 082 * [Sol1](project_euler/problem_082/sol1.py) * Problem 085 * [Sol1](project_euler/problem_085/sol1.py) * Problem 086 * [Sol1](project_euler/problem_086/sol1.py) * Problem 087 * [Sol1](project_euler/problem_087/sol1.py) * Problem 089 * [Sol1](project_euler/problem_089/sol1.py) * Problem 091 * [Sol1](project_euler/problem_091/sol1.py) * Problem 092 * [Sol1](project_euler/problem_092/sol1.py) * Problem 094 * [Sol1](project_euler/problem_094/sol1.py) * Problem 097 * [Sol1](project_euler/problem_097/sol1.py) * Problem 099 * [Sol1](project_euler/problem_099/sol1.py) * Problem 100 * [Sol1](project_euler/problem_100/sol1.py) * Problem 101 * [Sol1](project_euler/problem_101/sol1.py) * Problem 102 * [Sol1](project_euler/problem_102/sol1.py) * Problem 104 * [Sol1](project_euler/problem_104/sol1.py) * Problem 107 * [Sol1](project_euler/problem_107/sol1.py) * Problem 109 * [Sol1](project_euler/problem_109/sol1.py) * Problem 112 * [Sol1](project_euler/problem_112/sol1.py) * Problem 113 * [Sol1](project_euler/problem_113/sol1.py) * Problem 114 * [Sol1](project_euler/problem_114/sol1.py) * Problem 115 * [Sol1](project_euler/problem_115/sol1.py) * Problem 116 * [Sol1](project_euler/problem_116/sol1.py) * Problem 117 * [Sol1](project_euler/problem_117/sol1.py) * Problem 119 * [Sol1](project_euler/problem_119/sol1.py) * Problem 120 * [Sol1](project_euler/problem_120/sol1.py) * Problem 121 * [Sol1](project_euler/problem_121/sol1.py) * Problem 123 * [Sol1](project_euler/problem_123/sol1.py) * Problem 125 * [Sol1](project_euler/problem_125/sol1.py) * Problem 129 * [Sol1](project_euler/problem_129/sol1.py) * Problem 131 * [Sol1](project_euler/problem_131/sol1.py) * Problem 135 * [Sol1](project_euler/problem_135/sol1.py) * Problem 144 * [Sol1](project_euler/problem_144/sol1.py) * Problem 145 * [Sol1](project_euler/problem_145/sol1.py) * Problem 173 * [Sol1](project_euler/problem_173/sol1.py) * Problem 174 * [Sol1](project_euler/problem_174/sol1.py) * Problem 180 * [Sol1](project_euler/problem_180/sol1.py) * Problem 187 * [Sol1](project_euler/problem_187/sol1.py) * Problem 188 * [Sol1](project_euler/problem_188/sol1.py) * Problem 191 * [Sol1](project_euler/problem_191/sol1.py) * Problem 203 * [Sol1](project_euler/problem_203/sol1.py) * Problem 205 * [Sol1](project_euler/problem_205/sol1.py) * Problem 206 * [Sol1](project_euler/problem_206/sol1.py) * Problem 207 * [Sol1](project_euler/problem_207/sol1.py) * Problem 234 * [Sol1](project_euler/problem_234/sol1.py) * Problem 301 * [Sol1](project_euler/problem_301/sol1.py) * Problem 493 * [Sol1](project_euler/problem_493/sol1.py) * Problem 551 * [Sol1](project_euler/problem_551/sol1.py) * Problem 587 * [Sol1](project_euler/problem_587/sol1.py) * Problem 686 * [Sol1](project_euler/problem_686/sol1.py) * Problem 800 * [Sol1](project_euler/problem_800/sol1.py) ## Quantum * [Bb84](quantum/bb84.py) * [Deutsch Jozsa](quantum/deutsch_jozsa.py) * [Half Adder](quantum/half_adder.py) * [Not Gate](quantum/not_gate.py) * [Q Fourier Transform](quantum/q_fourier_transform.py) * [Q Full Adder](quantum/q_full_adder.py) * [Quantum Entanglement](quantum/quantum_entanglement.py) * [Quantum Random](quantum/quantum_random.py) * [Quantum Teleportation](quantum/quantum_teleportation.py) * [Ripple Adder Classic](quantum/ripple_adder_classic.py) * [Single Qubit Measure](quantum/single_qubit_measure.py) * [Superdense Coding](quantum/superdense_coding.py) ## Scheduling * [First Come First Served](scheduling/first_come_first_served.py) * [Highest Response Ratio Next](scheduling/highest_response_ratio_next.py) * [Job Sequencing With Deadline](scheduling/job_sequencing_with_deadline.py) * [Multi Level Feedback Queue](scheduling/multi_level_feedback_queue.py) * [Non Preemptive Shortest Job First](scheduling/non_preemptive_shortest_job_first.py) * [Round Robin](scheduling/round_robin.py) * [Shortest Job First](scheduling/shortest_job_first.py) ## Searches * [Binary Search](searches/binary_search.py) * [Binary Tree Traversal](searches/binary_tree_traversal.py) * [Double Linear Search](searches/double_linear_search.py) * [Double Linear Search Recursion](searches/double_linear_search_recursion.py) * [Fibonacci Search](searches/fibonacci_search.py) * [Hill Climbing](searches/hill_climbing.py) * [Interpolation Search](searches/interpolation_search.py) * [Jump Search](searches/jump_search.py) * [Linear Search](searches/linear_search.py) * [Quick Select](searches/quick_select.py) * [Sentinel Linear Search](searches/sentinel_linear_search.py) * [Simple Binary Search](searches/simple_binary_search.py) * [Simulated Annealing](searches/simulated_annealing.py) * [Tabu Search](searches/tabu_search.py) * [Ternary Search](searches/ternary_search.py) ## Sorts * [Bead Sort](sorts/bead_sort.py) * [Binary Insertion Sort](sorts/binary_insertion_sort.py) * [Bitonic Sort](sorts/bitonic_sort.py) * [Bogo Sort](sorts/bogo_sort.py) * [Bubble Sort](sorts/bubble_sort.py) * [Bucket Sort](sorts/bucket_sort.py) * [Circle Sort](sorts/circle_sort.py) * [Cocktail Shaker Sort](sorts/cocktail_shaker_sort.py) * [Comb Sort](sorts/comb_sort.py) * [Counting Sort](sorts/counting_sort.py) * [Cycle Sort](sorts/cycle_sort.py) * [Double Sort](sorts/double_sort.py) * [Dutch National Flag Sort](sorts/dutch_national_flag_sort.py) * [Exchange Sort](sorts/exchange_sort.py) * [External Sort](sorts/external_sort.py) * [Gnome Sort](sorts/gnome_sort.py) * [Heap Sort](sorts/heap_sort.py) * [Insertion Sort](sorts/insertion_sort.py) * [Intro Sort](sorts/intro_sort.py) * [Iterative Merge Sort](sorts/iterative_merge_sort.py) * [Merge Insertion Sort](sorts/merge_insertion_sort.py) * [Merge Sort](sorts/merge_sort.py) * [Msd Radix Sort](sorts/msd_radix_sort.py) * [Natural Sort](sorts/natural_sort.py) * [Odd Even Sort](sorts/odd_even_sort.py) * [Odd Even Transposition Parallel](sorts/odd_even_transposition_parallel.py) * [Odd Even Transposition Single Threaded](sorts/odd_even_transposition_single_threaded.py) * [Pancake Sort](sorts/pancake_sort.py) * [Patience Sort](sorts/patience_sort.py) * [Pigeon Sort](sorts/pigeon_sort.py) * [Pigeonhole Sort](sorts/pigeonhole_sort.py) * [Quick Sort](sorts/quick_sort.py) * [Quick Sort 3 Partition](sorts/quick_sort_3_partition.py) * [Radix Sort](sorts/radix_sort.py) * [Random Normal Distribution Quicksort](sorts/random_normal_distribution_quicksort.py) * [Random Pivot Quick Sort](sorts/random_pivot_quick_sort.py) * [Recursive Bubble Sort](sorts/recursive_bubble_sort.py) * [Recursive Insertion Sort](sorts/recursive_insertion_sort.py) * [Recursive Mergesort Array](sorts/recursive_mergesort_array.py) * [Recursive Quick Sort](sorts/recursive_quick_sort.py) * [Selection Sort](sorts/selection_sort.py) * [Shell Sort](sorts/shell_sort.py) * [Shrink Shell Sort](sorts/shrink_shell_sort.py) * [Slowsort](sorts/slowsort.py) * [Stooge Sort](sorts/stooge_sort.py) * [Strand Sort](sorts/strand_sort.py) * [Tim Sort](sorts/tim_sort.py) * [Topological Sort](sorts/topological_sort.py) * [Tree Sort](sorts/tree_sort.py) * [Unknown Sort](sorts/unknown_sort.py) * [Wiggle Sort](sorts/wiggle_sort.py) ## Strings * [Aho Corasick](strings/aho_corasick.py) * [Alternative String Arrange](strings/alternative_string_arrange.py) * [Anagrams](strings/anagrams.py) * [Autocomplete Using Trie](strings/autocomplete_using_trie.py) * [Barcode Validator](strings/barcode_validator.py) * [Boyer Moore Search](strings/boyer_moore_search.py) * [Can String Be Rearranged As Palindrome](strings/can_string_be_rearranged_as_palindrome.py) * [Capitalize](strings/capitalize.py) * [Check Anagrams](strings/check_anagrams.py) * [Credit Card Validator](strings/credit_card_validator.py) * [Detecting English Programmatically](strings/detecting_english_programmatically.py) * [Dna](strings/dna.py) * [Frequency Finder](strings/frequency_finder.py) * [Hamming Distance](strings/hamming_distance.py) * [Indian Phone Validator](strings/indian_phone_validator.py) * [Is Contains Unique Chars](strings/is_contains_unique_chars.py) * [Is Isogram](strings/is_isogram.py) * [Is Pangram](strings/is_pangram.py) * [Is Spain National Id](strings/is_spain_national_id.py) * [Is Srilankan Phone Number](strings/is_srilankan_phone_number.py) * [Jaro Winkler](strings/jaro_winkler.py) * [Join](strings/join.py) * [Knuth Morris Pratt](strings/knuth_morris_pratt.py) * [Levenshtein Distance](strings/levenshtein_distance.py) * [Lower](strings/lower.py) * [Manacher](strings/manacher.py) * [Min Cost String Conversion](strings/min_cost_string_conversion.py) * [Naive String Search](strings/naive_string_search.py) * [Ngram](strings/ngram.py) * [Palindrome](strings/palindrome.py) * [Prefix Function](strings/prefix_function.py) * [Rabin Karp](strings/rabin_karp.py) * [Remove Duplicate](strings/remove_duplicate.py) * [Reverse Letters](strings/reverse_letters.py) * [Reverse Long Words](strings/reverse_long_words.py) * [Reverse Words](strings/reverse_words.py) * [Snake Case To Camel Pascal Case](strings/snake_case_to_camel_pascal_case.py) * [Split](strings/split.py) * [String Switch Case](strings/string_switch_case.py) * [Text Justification](strings/text_justification.py) * [Top K Frequent Words](strings/top_k_frequent_words.py) * [Upper](strings/upper.py) * [Wave](strings/wave.py) * [Wildcard Pattern Matching](strings/wildcard_pattern_matching.py) * [Word Occurrence](strings/word_occurrence.py) * [Word Patterns](strings/word_patterns.py) * [Z Function](strings/z_function.py) ## Web Programming * [Co2 Emission](web_programming/co2_emission.py) * [Convert Number To Words](web_programming/convert_number_to_words.py) * [Covid Stats Via Xpath](web_programming/covid_stats_via_xpath.py) * [Crawl Google Results](web_programming/crawl_google_results.py) * [Crawl Google Scholar Citation](web_programming/crawl_google_scholar_citation.py) * [Currency Converter](web_programming/currency_converter.py) * [Current Stock Price](web_programming/current_stock_price.py) * [Current Weather](web_programming/current_weather.py) * [Daily Horoscope](web_programming/daily_horoscope.py) * [Download Images From Google Query](web_programming/download_images_from_google_query.py) * [Emails From Url](web_programming/emails_from_url.py) * [Fetch Bbc News](web_programming/fetch_bbc_news.py) * [Fetch Github Info](web_programming/fetch_github_info.py) * [Fetch Jobs](web_programming/fetch_jobs.py) * [Fetch Quotes](web_programming/fetch_quotes.py) * [Fetch Well Rx Price](web_programming/fetch_well_rx_price.py) * [Get Amazon Product Data](web_programming/get_amazon_product_data.py) * [Get Imdb Top 250 Movies Csv](web_programming/get_imdb_top_250_movies_csv.py) * [Get Imdbtop](web_programming/get_imdbtop.py) * [Get Top Hn Posts](web_programming/get_top_hn_posts.py) * [Get User Tweets](web_programming/get_user_tweets.py) * [Giphy](web_programming/giphy.py) * [Instagram Crawler](web_programming/instagram_crawler.py) * [Instagram Pic](web_programming/instagram_pic.py) * [Instagram Video](web_programming/instagram_video.py) * [Nasa Data](web_programming/nasa_data.py) * [Open Google Results](web_programming/open_google_results.py) * [Random Anime Character](web_programming/random_anime_character.py) * [Recaptcha Verification](web_programming/recaptcha_verification.py) * [Reddit](web_programming/reddit.py) * [Search Books By Isbn](web_programming/search_books_by_isbn.py) * [Slack Message](web_programming/slack_message.py) * [Test Fetch Github Info](web_programming/test_fetch_github_info.py) * [World Covid19 Stats](web_programming/world_covid19_stats.py)
1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Backtracking Backtracking is a way to speed up the search process by removing candidates when they can't be the solution of a problem. * <https://en.wikipedia.org/wiki/Backtracking> * <https://en.wikipedia.org/wiki/Decision_tree_pruning> * <https://medium.com/@priyankmistry1999/backtracking-sudoku-6e4439e4825c> * <https://www.geeksforgeeks.org/sudoku-backtracking-7/>
# Backtracking Backtracking is a way to speed up the search process by removing candidates when they can't be the solution of a problem. * <https://en.wikipedia.org/wiki/Backtracking> * <https://en.wikipedia.org/wiki/Decision_tree_pruning> * <https://medium.com/@priyankmistry1999/backtracking-sudoku-6e4439e4825c> * <https://www.geeksforgeeks.org/sudoku-backtracking-7/>
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
### Interest * Compound Interest: "Compound interest is calculated by multiplying the initial principal amount by one plus the annual interest rate raised to the number of compound periods minus one." [Compound Interest](https://www.investopedia.com/) * Simple Interest: "Simple interest paid or received over a certain period is a fixed percentage of the principal amount that was borrowed or lent. " [Simple Interest](https://www.investopedia.com/)
### Interest * Compound Interest: "Compound interest is calculated by multiplying the initial principal amount by one plus the annual interest rate raised to the number of compound periods minus one." [Compound Interest](https://www.investopedia.com/) * Simple Interest: "Simple interest paid or received over a certain period is a fixed percentage of the principal amount that was borrowed or lent. " [Simple Interest](https://www.investopedia.com/)
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Bit manipulation Bit manipulation is the act of manipulating bits to detect errors (hamming code), encrypts and decrypts messages (more on that in the 'ciphers' folder) or just do anything at the lowest level of your computer. * <https://en.wikipedia.org/wiki/Bit_manipulation> * <https://docs.python.org/3/reference/expressions.html#binary-bitwise-operations> * <https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations> * <https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types> * <https://wiki.python.org/moin/BitManipulation> * <https://wiki.python.org/moin/BitwiseOperators> * <https://www.tutorialspoint.com/python3/bitwise_operators_example.htm>
# Bit manipulation Bit manipulation is the act of manipulating bits to detect errors (hamming code), encrypts and decrypts messages (more on that in the 'ciphers' folder) or just do anything at the lowest level of your computer. * <https://en.wikipedia.org/wiki/Bit_manipulation> * <https://docs.python.org/3/reference/expressions.html#binary-bitwise-operations> * <https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations> * <https://docs.python.org/3/library/stdtypes.html#bitwise-operations-on-integer-types> * <https://wiki.python.org/moin/BitManipulation> * <https://wiki.python.org/moin/BitwiseOperators> * <https://www.tutorialspoint.com/python3/bitwise_operators_example.htm>
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# A naive recursive implementation of 0-1 Knapsack Problem This overview is taken from: https://en.wikipedia.org/wiki/Knapsack_problem --- ## Overview The knapsack problem is a problem in combinatorial optimization: Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most valuable items. The problem often arises in resource allocation where the decision makers have to choose from a set of non-divisible projects or tasks under a fixed budget or time constraint, respectively. The knapsack problem has been studied for more than a century, with early works dating as far back as 1897 The name "knapsack problem" dates back to the early works of mathematician Tobias Dantzig (1884–1956), and refers to the commonplace problem of packing the most valuable or useful items without overloading the luggage. --- ## Documentation This module uses docstrings to enable the use of Python's in-built `help(...)` function. For instance, try `help(Vector)`, `help(unit_basis_vector)`, and `help(CLASSNAME.METHODNAME)`. --- ## Usage Import the module `knapsack.py` from the **.** directory into your project. --- ## Tests `.` contains Python unit tests which can be run with `python3 -m unittest -v`.
# A naive recursive implementation of 0-1 Knapsack Problem This overview is taken from: https://en.wikipedia.org/wiki/Knapsack_problem --- ## Overview The knapsack problem is a problem in combinatorial optimization: Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible. It derives its name from the problem faced by someone who is constrained by a fixed-size knapsack and must fill it with the most valuable items. The problem often arises in resource allocation where the decision makers have to choose from a set of non-divisible projects or tasks under a fixed budget or time constraint, respectively. The knapsack problem has been studied for more than a century, with early works dating as far back as 1897 The name "knapsack problem" dates back to the early works of mathematician Tobias Dantzig (1884–1956), and refers to the commonplace problem of packing the most valuable or useful items without overloading the luggage. --- ## Documentation This module uses docstrings to enable the use of Python's in-built `help(...)` function. For instance, try `help(Vector)`, `help(unit_basis_vector)`, and `help(CLASSNAME.METHODNAME)`. --- ## Usage Import the module `knapsack.py` from the **.** directory into your project. --- ## Tests `.` contains Python unit tests which can be run with `python3 -m unittest -v`.
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Audio Filter Audio filters work on the frequency of an audio signal to attenuate unwanted frequency and amplify wanted ones. They are used within anything related to sound, whether it is radio communication or a hi-fi system. * <https://www.masteringbox.com/filter-types/> * <http://ethanwiner.com/filters.html> * <https://en.wikipedia.org/wiki/Audio_filter> * <https://en.wikipedia.org/wiki/Electronic_filter>
# Audio Filter Audio filters work on the frequency of an audio signal to attenuate unwanted frequency and amplify wanted ones. They are used within anything related to sound, whether it is radio communication or a hi-fi system. * <https://www.masteringbox.com/filter-types/> * <http://ethanwiner.com/filters.html> * <https://en.wikipedia.org/wiki/Audio_filter> * <https://en.wikipedia.org/wiki/Electronic_filter>
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Locally Weighted Linear Regression It is a non-parametric ML algorithm that does not learn on a fixed set of parameters such as **linear regression**. \ So, here comes a question of what is *linear regression*? \ **Linear regression** is a supervised learning algorithm used for computing linear relationships between input (X) and output (Y). \ ### Terminology Involved number_of_features(i) = Number of features involved. \ number_of_training_examples(m) = Number of training examples. \ output_sequence(y) = Output Sequence. \ $\theta$ $^T$ x = predicted point. \ J($\theta$) = COst function of point. The steps involved in ordinary linear regression are: Training phase: Compute \theta to minimize the cost. \ J($\theta$) = $\sum_{i=1}^m$ (($\theta$)$^T$ $x^i$ - $y^i$)$^2$ Predict output: for given query point x, \ return: ($\theta$)$^T$ x <img src="https://miro.medium.com/max/700/1*FZsLp8yTULf77qrp0Qd91g.png" alt="Linear Regression"> This training phase is possible when data points are linear, but there again comes a question can we predict non-linear relationship between x and y ? as shown below <img src="https://miro.medium.com/max/700/1*DHYvJg55uN-Kj8jHaxDKvQ.png" alt="Non-linear Data"> <br /> <br /> So, here comes the role of non-parametric algorithm which doesn't compute predictions based on fixed set of params. Rather parameters $\theta$ are computed individually for each query point/data point x. <br /> <br /> While Computing $\theta$ , a higher preference is given to points in the vicinity of x than points farther from x. Cost Function J($\theta$) = $\sum_{i=1}^m$ $w^i$ (($\theta$)$^T$ $x^i$ - $y^i$)$^2$ $w^i$ is non-negative weight associated to training point $x^i$. \ $w^i$ is large fr $x^i$'s lying closer to query point $x_i$. \ $w^i$ is small for $x^i$'s lying farther to query point $x_i$. A Typical weight can be computed using \ $w^i$ = $\exp$(-$\frac{(x^i-x)(x^i-x)^T}{2\tau^2}$) Where $\tau$ is the bandwidth parameter that controls $w^i$ distance from x. Let's look at a example : Suppose, we had a query point x=5.0 and training points $x^1$=4.9 and $x^2$=5.0 than we can calculate weights as : $w^i$ = $\exp$(-$\frac{(x^i-x)(x^i-x)^T}{2\tau^2}$) with $\tau$=0.5 $w^1$ = $\exp$(-$\frac{(4.9-5)^2}{2(0.5)^2}$) = 0.9802 $w^2$ = $\exp$(-$\frac{(3-5)^2}{2(0.5)^2}$) = 0.000335 So, J($\theta$) = 0.9802*($\theta$ $^T$ $x^1$ - $y^1$) + 0.000335*($\theta$ $^T$ $x^2$ - $y^2$) So, here by we can conclude that the weight fall exponentially as the distance between x & $x^i$ increases and So, does the contribution of error in prediction for $x^i$ to the cost. Steps involved in LWL are : \ Compute \theta to minimize the cost. J($\theta$) = $\sum_{i=1}^m$ $w^i$ (($\theta$)$^T$ $x^i$ - $y^i$)$^2$ \ Predict Output: for given query point x, \ return : $\theta$ $^T$ x <img src="https://miro.medium.com/max/700/1*H3QS05Q1GJtY-tiBL00iug.png" alt="LWL">
# Locally Weighted Linear Regression It is a non-parametric ML algorithm that does not learn on a fixed set of parameters such as **linear regression**. \ So, here comes a question of what is *linear regression*? \ **Linear regression** is a supervised learning algorithm used for computing linear relationships between input (X) and output (Y). \ ### Terminology Involved number_of_features(i) = Number of features involved. \ number_of_training_examples(m) = Number of training examples. \ output_sequence(y) = Output Sequence. \ $\theta$ $^T$ x = predicted point. \ J($\theta$) = COst function of point. The steps involved in ordinary linear regression are: Training phase: Compute \theta to minimize the cost. \ J($\theta$) = $\sum_{i=1}^m$ (($\theta$)$^T$ $x^i$ - $y^i$)$^2$ Predict output: for given query point x, \ return: ($\theta$)$^T$ x <img src="https://miro.medium.com/max/700/1*FZsLp8yTULf77qrp0Qd91g.png" alt="Linear Regression"> This training phase is possible when data points are linear, but there again comes a question can we predict non-linear relationship between x and y ? as shown below <img src="https://miro.medium.com/max/700/1*DHYvJg55uN-Kj8jHaxDKvQ.png" alt="Non-linear Data"> <br /> <br /> So, here comes the role of non-parametric algorithm which doesn't compute predictions based on fixed set of params. Rather parameters $\theta$ are computed individually for each query point/data point x. <br /> <br /> While Computing $\theta$ , a higher preference is given to points in the vicinity of x than points farther from x. Cost Function J($\theta$) = $\sum_{i=1}^m$ $w^i$ (($\theta$)$^T$ $x^i$ - $y^i$)$^2$ $w^i$ is non-negative weight associated to training point $x^i$. \ $w^i$ is large fr $x^i$'s lying closer to query point $x_i$. \ $w^i$ is small for $x^i$'s lying farther to query point $x_i$. A Typical weight can be computed using \ $w^i$ = $\exp$(-$\frac{(x^i-x)(x^i-x)^T}{2\tau^2}$) Where $\tau$ is the bandwidth parameter that controls $w^i$ distance from x. Let's look at a example : Suppose, we had a query point x=5.0 and training points $x^1$=4.9 and $x^2$=5.0 than we can calculate weights as : $w^i$ = $\exp$(-$\frac{(x^i-x)(x^i-x)^T}{2\tau^2}$) with $\tau$=0.5 $w^1$ = $\exp$(-$\frac{(4.9-5)^2}{2(0.5)^2}$) = 0.9802 $w^2$ = $\exp$(-$\frac{(3-5)^2}{2(0.5)^2}$) = 0.000335 So, J($\theta$) = 0.9802*($\theta$ $^T$ $x^1$ - $y^1$) + 0.000335*($\theta$ $^T$ $x^2$ - $y^2$) So, here by we can conclude that the weight fall exponentially as the distance between x & $x^i$ increases and So, does the contribution of error in prediction for $x^i$ to the cost. Steps involved in LWL are : \ Compute \theta to minimize the cost. J($\theta$) = $\sum_{i=1}^m$ $w^i$ (($\theta$)$^T$ $x^i$ - $y^i$)$^2$ \ Predict Output: for given query point x, \ return : $\theta$ $^T$ x <img src="https://miro.medium.com/max/700/1*H3QS05Q1GJtY-tiBL00iug.png" alt="LWL">
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Sorting Algorithms Sorting is the process of putting data in a specific order. The way to arrange data in a specific order is specified by the sorting algorithm. The most typical orders are lexical or numerical. The significance of sorting lies in the fact that, if data is stored in a sorted manner, data searching can be highly optimised. Another use for sorting is to represent data in a more readable manner. This section contains a lot of important algorithms that helps us to use sorting algorithms in various scenarios. ## References * <https://www.tutorialspoint.com/python_data_structure/python_sorting_algorithms.htm> * <https://www.geeksforgeeks.org/sorting-algorithms-in-python> * <https://realpython.com/sorting-algorithms-python>
# Sorting Algorithms Sorting is the process of putting data in a specific order. The way to arrange data in a specific order is specified by the sorting algorithm. The most typical orders are lexical or numerical. The significance of sorting lies in the fact that, if data is stored in a sorted manner, data searching can be highly optimised. Another use for sorting is to represent data in a more readable manner. This section contains a lot of important algorithms that helps us to use sorting algorithms in various scenarios. ## References * <https://www.tutorialspoint.com/python_data_structure/python_sorting_algorithms.htm> * <https://www.geeksforgeeks.org/sorting-algorithms-in-python> * <https://realpython.com/sorting-algorithms-python>
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
MIT License Copyright (c) 2016-2022 TheAlgorithms and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
MIT License Copyright (c) 2016-2022 TheAlgorithms and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Linear algebra library for Python This module contains classes and functions for doing linear algebra. --- ## Overview ### class Vector - - This class represents a vector of arbitrary size and related operations. **Overview of the methods:** - constructor(components) : init the vector - set(components) : changes the vector components. - \_\_str\_\_() : toString method - component(i): gets the i-th component (0-indexed) - \_\_len\_\_() : gets the size / length of the vector (number of components) - euclidean_length() : returns the eulidean length of the vector - operator + : vector addition - operator - : vector subtraction - operator * : scalar multiplication and dot product - copy() : copies this vector and returns it - change_component(pos,value) : changes the specified component - function zero_vector(dimension) - returns a zero vector of 'dimension' - function unit_basis_vector(dimension, pos) - returns a unit basis vector with a one at index 'pos' (0-indexed) - function axpy(scalar, vector1, vector2) - computes the axpy operation - function random_vector(N, a, b) - returns a random vector of size N, with random integer components between 'a' and 'b' inclusive ### class Matrix - - This class represents a matrix of arbitrary size and operations on it. **Overview of the methods:** - \_\_str\_\_() : returns a string representation - operator * : implements the matrix vector multiplication implements the matrix-scalar multiplication. - change_component(x, y, value) : changes the specified component. - component(x, y) : returns the specified component. - width() : returns the width of the matrix - height() : returns the height of the matrix - determinant() : returns the determinant of the matrix if it is square - operator + : implements the matrix-addition. - operator - : implements the matrix-subtraction - function square_zero_matrix(N) - returns a square zero-matrix of dimension NxN - function random_matrix(W, H, a, b) - returns a random matrix WxH with integer components between 'a' and 'b' inclusive --- ## Documentation This module uses docstrings to enable the use of Python's in-built `help(...)` function. For instance, try `help(Vector)`, `help(unit_basis_vector)`, and `help(CLASSNAME.METHODNAME)`. --- ## Usage Import the module `lib.py` from the **src** directory into your project. Alternatively, you can directly use the Python bytecode file `lib.pyc`. --- ## Tests `src/tests.py` contains Python unit tests which can be run with `python3 -m unittest -v`.
# Linear algebra library for Python This module contains classes and functions for doing linear algebra. --- ## Overview ### class Vector - - This class represents a vector of arbitrary size and related operations. **Overview of the methods:** - constructor(components) : init the vector - set(components) : changes the vector components. - \_\_str\_\_() : toString method - component(i): gets the i-th component (0-indexed) - \_\_len\_\_() : gets the size / length of the vector (number of components) - euclidean_length() : returns the eulidean length of the vector - operator + : vector addition - operator - : vector subtraction - operator * : scalar multiplication and dot product - copy() : copies this vector and returns it - change_component(pos,value) : changes the specified component - function zero_vector(dimension) - returns a zero vector of 'dimension' - function unit_basis_vector(dimension, pos) - returns a unit basis vector with a one at index 'pos' (0-indexed) - function axpy(scalar, vector1, vector2) - computes the axpy operation - function random_vector(N, a, b) - returns a random vector of size N, with random integer components between 'a' and 'b' inclusive ### class Matrix - - This class represents a matrix of arbitrary size and operations on it. **Overview of the methods:** - \_\_str\_\_() : returns a string representation - operator * : implements the matrix vector multiplication implements the matrix-scalar multiplication. - change_component(x, y, value) : changes the specified component. - component(x, y) : returns the specified component. - width() : returns the width of the matrix - height() : returns the height of the matrix - determinant() : returns the determinant of the matrix if it is square - operator + : implements the matrix-addition. - operator - : implements the matrix-subtraction - function square_zero_matrix(N) - returns a square zero-matrix of dimension NxN - function random_matrix(W, H, a, b) - returns a random matrix WxH with integer components between 'a' and 'b' inclusive --- ## Documentation This module uses docstrings to enable the use of Python's in-built `help(...)` function. For instance, try `help(Vector)`, `help(unit_basis_vector)`, and `help(CLASSNAME.METHODNAME)`. --- ## Usage Import the module `lib.py` from the **src** directory into your project. Alternatively, you can directly use the Python bytecode file `lib.pyc`. --- ## Tests `src/tests.py` contains Python unit tests which can be run with `python3 -m unittest -v`.
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Binary Tree Traversal ## Overview The combination of binary trees being data structures and traversal being an algorithm relates to classic problems, either directly or indirectly. > If you can grasp the traversal of binary trees, the traversal of other complicated trees will be easy for you. The following are some common ways to traverse trees. - Depth First Traversals (DFS): In-order, Pre-order, Post-order - Level Order Traversal or Breadth First or Traversal (BFS) There are applications for both DFS and BFS. Stack can be used to simplify the process of DFS traversal. Besides, since tree is a recursive data structure, recursion and stack are two key points for DFS. Graph for DFS: ![binary-tree-traversal-dfs](https://tva1.sinaimg.cn/large/007S8ZIlly1ghluhzhynsg30dw0dw3yl.gif) The key point of BFS is how to determine whether the traversal of each level has been completed. The answer is to use a variable as a flag to represent the end of the traversal of current level. ## Pre-order Traversal The traversal order of pre-order traversal is `root-left-right`. Algorithm Pre-order 1. Visit the root node and push it into a stack. 2. Pop a node from the stack, and push its right and left child node into the stack respectively. 3. Repeat step 2. Conclusion: This problem involves the classic recursive data structure (i.e. a binary tree), and the algorithm above demonstrates how a simplified solution can be reached by using a stack. If you look at the bigger picture, you'll find that the process of traversal is as followed. `Visit the left subtrees respectively from top to bottom, and visit the right subtrees respectively from bottom to top`. If we are to implement it from this perspective, things will be somewhat different. For the `top to bottom` part we can simply use recursion, and for the `bottom to top` part we can turn to stack. ## In-order Traversal The traversal order of in-order traversal is `left-root-right`. So the root node is not printed first. Things are getting a bit complicated here. Algorithm In-order 1. Visit the root and push it into a stack. 2. If there is a left child node, push it into the stack. Repeat this process until a leaf node reached. > At this point the root node and all the left nodes are in the stack. 3. Start popping nodes from the stack. If a node has a right child node, push the child node into the stack. Repeat step 2. It's worth pointing out that the in-order traversal of a binary search tree (BST) is a sorted array, which is helpful for coming up simplified solutions for some problems. ## Post-order Traversal The traversal order of post-order traversal is `left-right-root`. This one is a bit of a challenge. It deserves the `hard` tag of LeetCode. In this case, the root node is printed not as the first but the last one. A cunning way to do it is to: Record whether the current node has been visited. If 1) it's a leaf node or 2) both its left and right subtrees have been traversed, then it can be popped from the stack. As for `1) it's a leaf node`, you can easily tell whether a node is a leaf if both its left and right are `null`. As for `2) both its left and right subtrees have been traversed`, we only need a variable to record whether a node has been visited or not. In the worst case, we need to record the status for every single node and the space complexity is `O(n)`. But if you come to think about it, as we are using a stack and start printing the result from the leaf nodes, it makes sense that we only record the status for the current node popping from the stack, reducing the space complexity to `O(1)`. ## Level Order Traversal The key point of level order traversal is how do we know whether the traversal of each level is done. The answer is that we use a variable as a flag representing the end of the traversal of the current level. ![binary-tree-traversal-bfs](https://tva1.sinaimg.cn/large/007S8ZIlly1ghlui1tpoug30dw0dw3yl.gif) Algorithm Level-order 1. Visit the root node, put it in a FIFO queue, put in the queue a special flag (we are using `null` here). 2. Dequeue a node. 3. If the node equals `null`, it means that all nodes of the current level have been visited. If the queue is empty, we do nothing. Or else we put in another `null`. 4. If the node is not `null`, meaning the traversal of current level has not finished yet, we enqueue its left subtree and right subtree respectively. ## Bi-color marking We know that there is a tri-color marking in garbage collection algorithm, which works as described below. - The white color represents "not visited". - The gray color represents "not all child nodes visited". - The black color represents "all child nodes visited". Enlightened by tri-color marking, a bi-color marking method can be invented to solve all three traversal problems with one solution. The core idea is as follow. - Use a color to mark whether a node has been visited or not. Nodes yet to be visited are marked as white and visited nodes are marked as gray. - If we are visiting a white node, turn it into gray, and push its right child node, itself, and it's left child node into the stack respectively. - If we are visiting a gray node, print it. Implementation of pre-order and post-order traversal algorithms can be easily done by changing the order of pushing the child nodes into the stack. Reference: [LeetCode](https://github.com/azl397985856/leetcode/blob/master/thinkings/binary-tree-traversal.en.md)
# Binary Tree Traversal ## Overview The combination of binary trees being data structures and traversal being an algorithm relates to classic problems, either directly or indirectly. > If you can grasp the traversal of binary trees, the traversal of other complicated trees will be easy for you. The following are some common ways to traverse trees. - Depth First Traversals (DFS): In-order, Pre-order, Post-order - Level Order Traversal or Breadth First or Traversal (BFS) There are applications for both DFS and BFS. Stack can be used to simplify the process of DFS traversal. Besides, since tree is a recursive data structure, recursion and stack are two key points for DFS. Graph for DFS: ![binary-tree-traversal-dfs](https://tva1.sinaimg.cn/large/007S8ZIlly1ghluhzhynsg30dw0dw3yl.gif) The key point of BFS is how to determine whether the traversal of each level has been completed. The answer is to use a variable as a flag to represent the end of the traversal of current level. ## Pre-order Traversal The traversal order of pre-order traversal is `root-left-right`. Algorithm Pre-order 1. Visit the root node and push it into a stack. 2. Pop a node from the stack, and push its right and left child node into the stack respectively. 3. Repeat step 2. Conclusion: This problem involves the classic recursive data structure (i.e. a binary tree), and the algorithm above demonstrates how a simplified solution can be reached by using a stack. If you look at the bigger picture, you'll find that the process of traversal is as followed. `Visit the left subtrees respectively from top to bottom, and visit the right subtrees respectively from bottom to top`. If we are to implement it from this perspective, things will be somewhat different. For the `top to bottom` part we can simply use recursion, and for the `bottom to top` part we can turn to stack. ## In-order Traversal The traversal order of in-order traversal is `left-root-right`. So the root node is not printed first. Things are getting a bit complicated here. Algorithm In-order 1. Visit the root and push it into a stack. 2. If there is a left child node, push it into the stack. Repeat this process until a leaf node reached. > At this point the root node and all the left nodes are in the stack. 3. Start popping nodes from the stack. If a node has a right child node, push the child node into the stack. Repeat step 2. It's worth pointing out that the in-order traversal of a binary search tree (BST) is a sorted array, which is helpful for coming up simplified solutions for some problems. ## Post-order Traversal The traversal order of post-order traversal is `left-right-root`. This one is a bit of a challenge. It deserves the `hard` tag of LeetCode. In this case, the root node is printed not as the first but the last one. A cunning way to do it is to: Record whether the current node has been visited. If 1) it's a leaf node or 2) both its left and right subtrees have been traversed, then it can be popped from the stack. As for `1) it's a leaf node`, you can easily tell whether a node is a leaf if both its left and right are `null`. As for `2) both its left and right subtrees have been traversed`, we only need a variable to record whether a node has been visited or not. In the worst case, we need to record the status for every single node and the space complexity is `O(n)`. But if you come to think about it, as we are using a stack and start printing the result from the leaf nodes, it makes sense that we only record the status for the current node popping from the stack, reducing the space complexity to `O(1)`. ## Level Order Traversal The key point of level order traversal is how do we know whether the traversal of each level is done. The answer is that we use a variable as a flag representing the end of the traversal of the current level. ![binary-tree-traversal-bfs](https://tva1.sinaimg.cn/large/007S8ZIlly1ghlui1tpoug30dw0dw3yl.gif) Algorithm Level-order 1. Visit the root node, put it in a FIFO queue, put in the queue a special flag (we are using `null` here). 2. Dequeue a node. 3. If the node equals `null`, it means that all nodes of the current level have been visited. If the queue is empty, we do nothing. Or else we put in another `null`. 4. If the node is not `null`, meaning the traversal of current level has not finished yet, we enqueue its left subtree and right subtree respectively. ## Bi-color marking We know that there is a tri-color marking in garbage collection algorithm, which works as described below. - The white color represents "not visited". - The gray color represents "not all child nodes visited". - The black color represents "all child nodes visited". Enlightened by tri-color marking, a bi-color marking method can be invented to solve all three traversal problems with one solution. The core idea is as follow. - Use a color to mark whether a node has been visited or not. Nodes yet to be visited are marked as white and visited nodes are marked as gray. - If we are visiting a white node, turn it into gray, and push its right child node, itself, and it's left child node into the stack respectively. - If we are visiting a gray node, print it. Implementation of pre-order and post-order traversal algorithms can be easily done by changing the order of pushing the child nodes into the stack. Reference: [LeetCode](https://github.com/azl397985856/leetcode/blob/master/thinkings/binary-tree-traversal.en.md)
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Blockchain A Blockchain is a type of **distributed ledger** technology (DLT) that consists of growing list of records, called **blocks**, that are securely linked together using **cryptography**. Let's breakdown the terminologies in the above definition. We find below terminologies, - Digital Ledger Technology (DLT) - Blocks - Cryptography ## Digital Ledger Technology It is otherwise called as distributed ledger technology. It is simply the opposite of centralized database. Firstly, what is a **ledger**? A ledger is a book or collection of accounts that records account transactions. *Why is Blockchain addressed as digital ledger if it can record more than account transactions? What other transaction details and information can it hold?* Digital Ledger Technology is just a ledger which is shared among multiple nodes. This way there exist no need for central authority to hold the info. Okay, how is it differentiated from central database and what are their benefits? There is an organization which has 4 branches whose data are stored in a centralized database. So even if one branch needs any data from ledger they need an approval from database in charge. And if one hacks the central database he gets to tamper and control all the data. Now lets assume every branch has a copy of the ledger and then once anything is added to the ledger by anyone branch it is gonna automatically reflect in all other ledgers available in other branch. This is done using Peer-to-peer network. So this means even if information is tampered in one branch we can find out. If one branch is hacked we can be alerted ,so we can safeguard other branches. Now, assume these branches as computers or nodes and the ledger is a transaction record or digital receipt. If one ledger is hacked in a node we can detect since there will be a mismatch in comparison with other node information. So this is the concept of Digital Ledger Technology. *Is it required for all nodes to have access to all information in other nodes? Wouldn't this require enormous storage space in each node?* ## Blocks In short a block is nothing but collections of records with a labelled header. These are connected cryptographically. Once a new block is added to a chain, the previous block is connected, more precisely said as locked and hence, will remain unaltered. We can understand this concept once we get a clear understanding of working mechanism of blockchain. ## Cryptography It is the practice and study of secure communication techniques in the midst of adversarial behavior. More broadly, cryptography is the creation and analysis of protocols that prevent third parties or the general public from accessing private messages. *Which cryptography technology is most widely used in blockchain and why?* So, in general, blockchain technology is a distributed record holder which records the information about ownership of an asset. To define precisely, > Blockchain is a distributed, immutable ledger that makes it easier to record transactions and track assets in a corporate network. An asset could be tangible (such as a house, car, cash, or land) or intangible (such as a business) (intellectual property, patents, copyrights, branding). A blockchain network can track and sell almost anything of value, lowering risk and costs for everyone involved. So this is all about introduction to blockchain technology. To learn more about the topic refer below links.... * <https://en.wikipedia.org/wiki/Blockchain> * <https://en.wikipedia.org/wiki/Chinese_remainder_theorem> * <https://en.wikipedia.org/wiki/Diophantine_equation> * <https://www.geeksforgeeks.org/modular-division/>
# Blockchain A Blockchain is a type of **distributed ledger** technology (DLT) that consists of growing list of records, called **blocks**, that are securely linked together using **cryptography**. Let's breakdown the terminologies in the above definition. We find below terminologies, - Digital Ledger Technology (DLT) - Blocks - Cryptography ## Digital Ledger Technology It is otherwise called as distributed ledger technology. It is simply the opposite of centralized database. Firstly, what is a **ledger**? A ledger is a book or collection of accounts that records account transactions. *Why is Blockchain addressed as digital ledger if it can record more than account transactions? What other transaction details and information can it hold?* Digital Ledger Technology is just a ledger which is shared among multiple nodes. This way there exist no need for central authority to hold the info. Okay, how is it differentiated from central database and what are their benefits? There is an organization which has 4 branches whose data are stored in a centralized database. So even if one branch needs any data from ledger they need an approval from database in charge. And if one hacks the central database he gets to tamper and control all the data. Now lets assume every branch has a copy of the ledger and then once anything is added to the ledger by anyone branch it is gonna automatically reflect in all other ledgers available in other branch. This is done using Peer-to-peer network. So this means even if information is tampered in one branch we can find out. If one branch is hacked we can be alerted ,so we can safeguard other branches. Now, assume these branches as computers or nodes and the ledger is a transaction record or digital receipt. If one ledger is hacked in a node we can detect since there will be a mismatch in comparison with other node information. So this is the concept of Digital Ledger Technology. *Is it required for all nodes to have access to all information in other nodes? Wouldn't this require enormous storage space in each node?* ## Blocks In short a block is nothing but collections of records with a labelled header. These are connected cryptographically. Once a new block is added to a chain, the previous block is connected, more precisely said as locked and hence, will remain unaltered. We can understand this concept once we get a clear understanding of working mechanism of blockchain. ## Cryptography It is the practice and study of secure communication techniques in the midst of adversarial behavior. More broadly, cryptography is the creation and analysis of protocols that prevent third parties or the general public from accessing private messages. *Which cryptography technology is most widely used in blockchain and why?* So, in general, blockchain technology is a distributed record holder which records the information about ownership of an asset. To define precisely, > Blockchain is a distributed, immutable ledger that makes it easier to record transactions and track assets in a corporate network. An asset could be tangible (such as a house, car, cash, or land) or intangible (such as a business) (intellectual property, patents, copyrights, branding). A blockchain network can track and sell almost anything of value, lowering risk and costs for everyone involved. So this is all about introduction to blockchain technology. To learn more about the topic refer below links.... * <https://en.wikipedia.org/wiki/Blockchain> * <https://en.wikipedia.org/wiki/Chinese_remainder_theorem> * <https://en.wikipedia.org/wiki/Diophantine_equation> * <https://www.geeksforgeeks.org/modular-division/>
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Hashes Hashing is the process of mapping any amount of data to a specified size using an algorithm. This is known as a hash value (or, if you're feeling fancy, a hash code, hash sums, or even a hash digest). Hashing is a one-way function, whereas encryption is a two-way function. While it is functionally conceivable to reverse-hash stuff, the required computing power makes it impractical. Hashing is a one-way street. Unlike encryption, which is intended to protect data in transit, hashing is intended to authenticate that a file or piece of data has not been altered—that it is authentic. In other words, it functions as a checksum. ## Common hashing algorithms ### MD5 This is one of the first algorithms that has gained widespread acceptance. MD5 is hashing algorithm made by Ray Rivest that is known to suffer vulnerabilities. It was created in 1992 as the successor to MD4. Currently MD6 is in the works, but as of 2009 Rivest had removed it from NIST consideration for SHA-3. ### SHA SHA stands for Security Hashing Algorithm and it’s probably best known as the hashing algorithm used in most SSL/TLS cipher suites. A cipher suite is a collection of ciphers and algorithms that are used for SSL/TLS connections. SHA handles the hashing aspects. SHA-1, as we mentioned earlier, is now deprecated. SHA-2 is now mandatory. SHA-2 is sometimes known has SHA-256, though variants with longer bit lengths are also available. ### SHA256 SHA 256 is a member of the SHA 2 algorithm family, under which SHA stands for Secure Hash Algorithm. It was a collaborative effort between both the NSA and NIST to implement a successor to the SHA 1 family, which was beginning to lose potency against brute force attacks. It was published in 2001. The importance of the 256 in the name refers to the final hash digest value, i.e. the hash value will remain 256 bits regardless of the size of the plaintext/cleartext. Other algorithms in the SHA family are similar to SHA 256 in some ways. ### Luhn The Luhn algorithm, also renowned as the modulus 10 or mod 10 algorithm, is a straightforward checksum formula used to validate a wide range of identification numbers, including credit card numbers, IMEI numbers, and Canadian Social Insurance Numbers. A community of mathematicians developed the LUHN formula in the late 1960s. Companies offering credit cards quickly followed suit. Since the algorithm is in the public interest, anyone can use it. The algorithm is used by most credit cards and many government identification numbers as a simple method of differentiating valid figures from mistyped or otherwise incorrect numbers. It was created to guard against unintentional errors, not malicious attacks.
# Hashes Hashing is the process of mapping any amount of data to a specified size using an algorithm. This is known as a hash value (or, if you're feeling fancy, a hash code, hash sums, or even a hash digest). Hashing is a one-way function, whereas encryption is a two-way function. While it is functionally conceivable to reverse-hash stuff, the required computing power makes it impractical. Hashing is a one-way street. Unlike encryption, which is intended to protect data in transit, hashing is intended to authenticate that a file or piece of data has not been altered—that it is authentic. In other words, it functions as a checksum. ## Common hashing algorithms ### MD5 This is one of the first algorithms that has gained widespread acceptance. MD5 is hashing algorithm made by Ray Rivest that is known to suffer vulnerabilities. It was created in 1992 as the successor to MD4. Currently MD6 is in the works, but as of 2009 Rivest had removed it from NIST consideration for SHA-3. ### SHA SHA stands for Security Hashing Algorithm and it’s probably best known as the hashing algorithm used in most SSL/TLS cipher suites. A cipher suite is a collection of ciphers and algorithms that are used for SSL/TLS connections. SHA handles the hashing aspects. SHA-1, as we mentioned earlier, is now deprecated. SHA-2 is now mandatory. SHA-2 is sometimes known has SHA-256, though variants with longer bit lengths are also available. ### SHA256 SHA 256 is a member of the SHA 2 algorithm family, under which SHA stands for Secure Hash Algorithm. It was a collaborative effort between both the NSA and NIST to implement a successor to the SHA 1 family, which was beginning to lose potency against brute force attacks. It was published in 2001. The importance of the 256 in the name refers to the final hash digest value, i.e. the hash value will remain 256 bits regardless of the size of the plaintext/cleartext. Other algorithms in the SHA family are similar to SHA 256 in some ways. ### Luhn The Luhn algorithm, also renowned as the modulus 10 or mod 10 algorithm, is a straightforward checksum formula used to validate a wide range of identification numbers, including credit card numbers, IMEI numbers, and Canadian Social Insurance Numbers. A community of mathematicians developed the LUHN formula in the late 1960s. Companies offering credit cards quickly followed suit. Since the algorithm is in the public interest, anyone can use it. The algorithm is used by most credit cards and many government identification numbers as a simple method of differentiating valid figures from mistyped or otherwise incorrect numbers. It was created to guard against unintentional errors, not malicious attacks.
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Project Euler Problems are taken from https://projecteuler.net/, the Project Euler. [Problems are licensed under CC BY-NC-SA 4.0](https://projecteuler.net/copyright). Project Euler is a series of challenging mathematical/computer programming problems that require more than just mathematical insights to solve. Project Euler is ideal for mathematicians who are learning to code. The solutions will be checked by our [automated testing on GitHub Actions](https://github.com/TheAlgorithms/Python/actions) with the help of [this script](https://github.com/TheAlgorithms/Python/blob/master/scripts/validate_solutions.py). The efficiency of your code is also checked. You can view the top 10 slowest solutions on GitHub Actions logs (under `slowest 10 durations`) and open a pull request to improve those solutions. ## Solution Guidelines Welcome to [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python)! Before reading the solution guidelines, make sure you read the whole [Contributing Guidelines](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md) as it won't be repeated in here. If you have any doubt on the guidelines, please feel free to [state it clearly in an issue](https://github.com/TheAlgorithms/Python/issues/new) or ask the community in [Gitter](https://gitter.im/TheAlgorithms/community). You can use the [template](https://github.com/TheAlgorithms/Python/blob/master/project_euler/README.md#solution-template) we have provided below as your starting point but be sure to read the [Coding Style](https://github.com/TheAlgorithms/Python/blob/master/project_euler/README.md#coding-style) part first. ### Coding Style * Please maintain consistency in project directory and solution file names. Keep the following points in mind: * Create a new directory only for the problems which do not exist yet. * If you create a new directory, please create an empty `__init__.py` file inside it as well. * Please name the project **directory** as `problem_<problem_number>` where `problem_number` should be filled with 0s so as to occupy 3 digits. Example: `problem_001`, `problem_002`, `problem_067`, `problem_145`, and so on. * Please provide a link to the problem and other references, if used, in the **module-level docstring**. * All imports should come ***after*** the module-level docstring. * You can have as many helper functions as you want but there should be one main function called `solution` which should satisfy the conditions as stated below: * It should contain positional argument(s) whose default value is the question input. Example: Please take a look at [Problem 1](https://projecteuler.net/problem=1) where the question is to *Find the sum of all the multiples of 3 or 5 below 1000.* In this case the main solution function will be `solution(limit: int = 1000)`. * When the `solution` function is called without any arguments like so: `solution()`, it should return the answer to the problem. * Every function, which includes all the helper functions, if any, and the main solution function, should have `doctest` in the function docstring along with a brief statement mentioning what the function is about. * There should not be a `doctest` for testing the answer as that is done by our GitHub Actions build using this [script](https://github.com/TheAlgorithms/Python/blob/master/scripts/validate_solutions.py). Keeping in mind the above example of [Problem 1](https://projecteuler.net/problem=1): ```python def solution(limit: int = 1000): """ A brief statement mentioning what the function is about. You can have a detailed explanation about the solution method in the module-level docstring. >>> solution(1) ... >>> solution(16) ... >>> solution(100) ... """ ``` ### Solution Template You can use the below template as your starting point but please read the [Coding Style](https://github.com/TheAlgorithms/Python/blob/master/project_euler/README.md#coding-style) first to understand how the template works. Please change the name of the helper functions accordingly, change the parameter names with a descriptive one, replace the content within `[square brackets]` (including the brackets) with the appropriate content. ```python """ Project Euler Problem [problem number]: [link to the original problem] ... [Entire problem statement] ... ... [Solution explanation - Optional] ... References [Optional]: - [Wikipedia link to the topic] - [Stackoverflow link] ... """ import module1 import module2 ... def helper1(arg1: [type hint], arg2: [type hint], ...) -> [Return type hint]: """ A brief statement explaining what the function is about. ... A more elaborate description ... [Optional] ... [Doctest] ... """ ... # calculations ... return # You can have multiple helper functions but the solution function should be # after all the helper functions ... def solution(arg1: [type hint], arg2: [type hint], ...) -> [Return type hint]: """ A brief statement mentioning what the function is about. You can have a detailed explanation about the solution in the module-level docstring. ... [Doctest as mentioned above] ... """ ... # calculations ... return answer if __name__ == "__main__": print(f"{solution() = }") ```
# Project Euler Problems are taken from https://projecteuler.net/, the Project Euler. [Problems are licensed under CC BY-NC-SA 4.0](https://projecteuler.net/copyright). Project Euler is a series of challenging mathematical/computer programming problems that require more than just mathematical insights to solve. Project Euler is ideal for mathematicians who are learning to code. The solutions will be checked by our [automated testing on GitHub Actions](https://github.com/TheAlgorithms/Python/actions) with the help of [this script](https://github.com/TheAlgorithms/Python/blob/master/scripts/validate_solutions.py). The efficiency of your code is also checked. You can view the top 10 slowest solutions on GitHub Actions logs (under `slowest 10 durations`) and open a pull request to improve those solutions. ## Solution Guidelines Welcome to [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python)! Before reading the solution guidelines, make sure you read the whole [Contributing Guidelines](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md) as it won't be repeated in here. If you have any doubt on the guidelines, please feel free to [state it clearly in an issue](https://github.com/TheAlgorithms/Python/issues/new) or ask the community in [Gitter](https://gitter.im/TheAlgorithms/community). You can use the [template](https://github.com/TheAlgorithms/Python/blob/master/project_euler/README.md#solution-template) we have provided below as your starting point but be sure to read the [Coding Style](https://github.com/TheAlgorithms/Python/blob/master/project_euler/README.md#coding-style) part first. ### Coding Style * Please maintain consistency in project directory and solution file names. Keep the following points in mind: * Create a new directory only for the problems which do not exist yet. * If you create a new directory, please create an empty `__init__.py` file inside it as well. * Please name the project **directory** as `problem_<problem_number>` where `problem_number` should be filled with 0s so as to occupy 3 digits. Example: `problem_001`, `problem_002`, `problem_067`, `problem_145`, and so on. * Please provide a link to the problem and other references, if used, in the **module-level docstring**. * All imports should come ***after*** the module-level docstring. * You can have as many helper functions as you want but there should be one main function called `solution` which should satisfy the conditions as stated below: * It should contain positional argument(s) whose default value is the question input. Example: Please take a look at [Problem 1](https://projecteuler.net/problem=1) where the question is to *Find the sum of all the multiples of 3 or 5 below 1000.* In this case the main solution function will be `solution(limit: int = 1000)`. * When the `solution` function is called without any arguments like so: `solution()`, it should return the answer to the problem. * Every function, which includes all the helper functions, if any, and the main solution function, should have `doctest` in the function docstring along with a brief statement mentioning what the function is about. * There should not be a `doctest` for testing the answer as that is done by our GitHub Actions build using this [script](https://github.com/TheAlgorithms/Python/blob/master/scripts/validate_solutions.py). Keeping in mind the above example of [Problem 1](https://projecteuler.net/problem=1): ```python def solution(limit: int = 1000): """ A brief statement mentioning what the function is about. You can have a detailed explanation about the solution method in the module-level docstring. >>> solution(1) ... >>> solution(16) ... >>> solution(100) ... """ ``` ### Solution Template You can use the below template as your starting point but please read the [Coding Style](https://github.com/TheAlgorithms/Python/blob/master/project_euler/README.md#coding-style) first to understand how the template works. Please change the name of the helper functions accordingly, change the parameter names with a descriptive one, replace the content within `[square brackets]` (including the brackets) with the appropriate content. ```python """ Project Euler Problem [problem number]: [link to the original problem] ... [Entire problem statement] ... ... [Solution explanation - Optional] ... References [Optional]: - [Wikipedia link to the topic] - [Stackoverflow link] ... """ import module1 import module2 ... def helper1(arg1: [type hint], arg2: [type hint], ...) -> [Return type hint]: """ A brief statement explaining what the function is about. ... A more elaborate description ... [Optional] ... [Doctest] ... """ ... # calculations ... return # You can have multiple helper functions but the solution function should be # after all the helper functions ... def solution(arg1: [type hint], arg2: [type hint], ...) -> [Return type hint]: """ A brief statement mentioning what the function is about. You can have a detailed explanation about the solution in the module-level docstring. ... [Doctest as mentioned above] ... """ ... # calculations ... return answer if __name__ == "__main__": print(f"{solution() = }") ```
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Boolean Algebra Boolean algebra is used to do arithmetic with bits of values True (1) or False (0). There are three basic operations: 'and', 'or' and 'not'. * <https://en.wikipedia.org/wiki/Boolean_algebra> * <https://plato.stanford.edu/entries/boolalg-math/>
# Boolean Algebra Boolean algebra is used to do arithmetic with bits of values True (1) or False (0). There are three basic operations: 'and', 'or' and 'not'. * <https://en.wikipedia.org/wiki/Boolean_algebra> * <https://plato.stanford.edu/entries/boolalg-math/>
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Normal Distribution QuickSort QuickSort Algorithm where the pivot element is chosen randomly between first and last elements of the array, and the array elements are taken from Standard Normal Distribution. ## 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) >>> 'The array is' >>> 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() ``` ------ ![normal distribution large](https://upload.wikimedia.org/wikipedia/commons/thumb/2/25/The_Normal_Distribution.svg/1280px-The_Normal_Distribution.svg.png) ------ ## Comparing the numbers of comparisons We can plot the function for Checking 'The Number of Comparisons' taking place between Normal Distribution QuickSort and Ordinary QuickSort: ```python >>> import matplotlib.pyplot as plt # Normal Distribution 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 QuickSort Algorithm where the pivot element is chosen randomly between first and last elements of the array, and the array elements are taken from Standard Normal Distribution. ## 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) >>> 'The array is' >>> 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() ``` ------ ![normal distribution large](https://upload.wikimedia.org/wikipedia/commons/thumb/2/25/The_Normal_Distribution.svg/1280px-The_Normal_Distribution.svg.png) ------ ## Comparing the numbers of comparisons We can plot the function for Checking 'The Number of Comparisons' taking place between Normal Distribution QuickSort and Ordinary QuickSort: ```python >>> import matplotlib.pyplot as plt # Normal Distribution 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
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Cellular Automata Cellular automata are a way to simulate the behavior of "life", no matter if it is a robot or cell. They usually follow simple rules but can lead to the creation of complex forms. The most popular cellular automaton is Conway's [Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). * <https://en.wikipedia.org/wiki/Cellular_automaton> * <https://mathworld.wolfram.com/ElementaryCellularAutomaton.html>
# Cellular Automata Cellular automata are a way to simulate the behavior of "life", no matter if it is a robot or cell. They usually follow simple rules but can lead to the creation of complex forms. The most popular cellular automaton is Conway's [Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). * <https://en.wikipedia.org/wiki/Cellular_automaton> * <https://mathworld.wolfram.com/ElementaryCellularAutomaton.html>
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Arithmetic analysis Arithmetic analysis is a branch of mathematics that deals with solving linear equations. * <https://en.wikipedia.org/wiki/System_of_linear_equations> * <https://en.wikipedia.org/wiki/Gaussian_elimination> * <https://en.wikipedia.org/wiki/Root-finding_algorithms>
# Arithmetic analysis Arithmetic analysis is a branch of mathematics that deals with solving linear equations. * <https://en.wikipedia.org/wiki/System_of_linear_equations> * <https://en.wikipedia.org/wiki/Gaussian_elimination> * <https://en.wikipedia.org/wiki/Root-finding_algorithms>
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Conversion Conversion programs convert a type of data, a number from a numerical base or unit into one of another type, base or unit, e.g. binary to decimal, integer to string or foot to meters. * <https://en.wikipedia.org/wiki/Data_conversion> * <https://en.wikipedia.org/wiki/Transcoding>
# Conversion Conversion programs convert a type of data, a number from a numerical base or unit into one of another type, base or unit, e.g. binary to decimal, integer to string or foot to meters. * <https://en.wikipedia.org/wiki/Data_conversion> * <https://en.wikipedia.org/wiki/Transcoding>
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" You have m types of coins available in infinite quantities where the value of each coins is given in the array S=[S0,... Sm-1] Can you determine number of ways of making change for n units using the given types of coins? https://www.hackerrank.com/challenges/coin-change/problem """ def dp_count(s, n): """ >>> dp_count([1, 2, 3], 4) 4 >>> dp_count([1, 2, 3], 7) 8 >>> dp_count([2, 5, 3, 6], 10) 5 >>> dp_count([10], 99) 0 >>> dp_count([4, 5, 6], 0) 1 >>> dp_count([1, 2, 3], -5) 0 """ if n < 0: return 0 # table[i] represents the number of ways to get to amount i table = [0] * (n + 1) # There is exactly 1 way to get to zero(You pick no coins). table[0] = 1 # Pick all coins one by one and update table[] values # after the index greater than or equal to the value of the # picked coin for coin_val in s: for j in range(coin_val, n + 1): table[j] += table[j - coin_val] return table[n] if __name__ == "__main__": import doctest doctest.testmod()
""" You have m types of coins available in infinite quantities where the value of each coins is given in the array S=[S0,... Sm-1] Can you determine number of ways of making change for n units using the given types of coins? https://www.hackerrank.com/challenges/coin-change/problem """ def dp_count(s, n): """ >>> dp_count([1, 2, 3], 4) 4 >>> dp_count([1, 2, 3], 7) 8 >>> dp_count([2, 5, 3, 6], 10) 5 >>> dp_count([10], 99) 0 >>> dp_count([4, 5, 6], 0) 1 >>> dp_count([1, 2, 3], -5) 0 """ if n < 0: return 0 # table[i] represents the number of ways to get to amount i table = [0] * (n + 1) # There is exactly 1 way to get to zero(You pick no coins). table[0] = 1 # Pick all coins one by one and update table[] values # after the index greater than or equal to the value of the # picked coin for coin_val in s: for j in range(coin_val, n + 1): table[j] += table[j - coin_val] return table[n] if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
0000000000000000000000000000000000000000 9caf4784aada17dc75348f77cc8c356df503c0f3 jupyter <[email protected]> 1704811012 +0000 clone: from https://github.com/TheAlgorithms/Python.git
0000000000000000000000000000000000000000 9caf4784aada17dc75348f77cc8c356df503c0f3 jupyter <[email protected]> 1704811012 +0000 clone: from https://github.com/TheAlgorithms/Python.git
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Illustrate how to implement inorder traversal in binary search tree. Author: Gurneet Singh https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/ """ class BinaryTreeNode: """Defining the structure of BinaryTreeNode""" def __init__(self, data: int) -> None: self.data = data self.left_child: BinaryTreeNode | None = None self.right_child: BinaryTreeNode | None = None def insert(node: BinaryTreeNode | None, new_value: int) -> BinaryTreeNode | None: """ If the binary search tree is empty, make a new node and declare it as root. >>> node_a = BinaryTreeNode(12345) >>> node_b = insert(node_a, 67890) >>> node_a.left_child == node_b.left_child True >>> node_a.right_child == node_b.right_child True >>> node_a.data == node_b.data True """ if node is None: node = BinaryTreeNode(new_value) return node # binary search tree is not empty, # so we will insert it into the tree # if new_value is less than value of data in node, # add it to left subtree and proceed recursively if new_value < node.data: node.left_child = insert(node.left_child, new_value) else: # if new_value is greater than value of data in node, # add it to right subtree and proceed recursively node.right_child = insert(node.right_child, new_value) return node def inorder(node: None | BinaryTreeNode) -> list[int]: # if node is None,return """ >>> inorder(make_tree()) [6, 10, 14, 15, 20, 25, 60] """ if node: inorder_array = inorder(node.left_child) inorder_array = [*inorder_array, node.data] inorder_array = inorder_array + inorder(node.right_child) else: inorder_array = [] return inorder_array def make_tree() -> BinaryTreeNode | None: root = insert(None, 15) insert(root, 10) insert(root, 25) insert(root, 6) insert(root, 14) insert(root, 20) insert(root, 60) return root def main() -> None: # main function root = make_tree() print("Printing values of binary search tree in Inorder Traversal.") inorder(root) if __name__ == "__main__": import doctest doctest.testmod() main()
""" Illustrate how to implement inorder traversal in binary search tree. Author: Gurneet Singh https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/ """ class BinaryTreeNode: """Defining the structure of BinaryTreeNode""" def __init__(self, data: int) -> None: self.data = data self.left_child: BinaryTreeNode | None = None self.right_child: BinaryTreeNode | None = None def insert(node: BinaryTreeNode | None, new_value: int) -> BinaryTreeNode | None: """ If the binary search tree is empty, make a new node and declare it as root. >>> node_a = BinaryTreeNode(12345) >>> node_b = insert(node_a, 67890) >>> node_a.left_child == node_b.left_child True >>> node_a.right_child == node_b.right_child True >>> node_a.data == node_b.data True """ if node is None: node = BinaryTreeNode(new_value) return node # binary search tree is not empty, # so we will insert it into the tree # if new_value is less than value of data in node, # add it to left subtree and proceed recursively if new_value < node.data: node.left_child = insert(node.left_child, new_value) else: # if new_value is greater than value of data in node, # add it to right subtree and proceed recursively node.right_child = insert(node.right_child, new_value) return node def inorder(node: None | BinaryTreeNode) -> list[int]: # if node is None,return """ >>> inorder(make_tree()) [6, 10, 14, 15, 20, 25, 60] """ if node: inorder_array = inorder(node.left_child) inorder_array = [*inorder_array, node.data] inorder_array = inorder_array + inorder(node.right_child) else: inorder_array = [] return inorder_array def make_tree() -> BinaryTreeNode | None: root = insert(None, 15) insert(root, 10) insert(root, 25) insert(root, 6) insert(root, 14) insert(root, 20) insert(root, 60) return root def main() -> None: # main function root = make_tree() print("Printing values of binary search tree in Inorder Traversal.") inorder(root) if __name__ == "__main__": import doctest doctest.testmod() main()
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
PNG  IHDR=GgAMA asRGBPLTEGpL  $7.G # e {}~~&y?I8MH` "l|/"w'xz v 0zB#H$?J` 'T^l %z &М/_s:OgR$ 'vP " xmju +Wze][p1"-7a|<G~?rs()7N .XAV1KC%@b:=@8ӊ/GSEKWl41}!}bŹɯd³mYXJvw,u)'&hf[%nOsjVVVH~~~) EEEfff544rrr׹cP7raGꡠ@qɲѐ.Vd~{DARLkLj,|DN\Z/KfMtRNS- 9? '3JYl|6$NL֋3o`zfAӪ옇i۶yӮ ֪dIDATxKiG4̍{tXQ*-Z+;Ȅ!11\8cXݖ xE"VʵOG.[լ-E".<$dd-d5y)/b\N\^q)erb2ywp0π|0&EXvhxǐ('2 + ~a.h@js^ =*@.6g,7GA~$KxXںON"$4]iVmׇF@T|]k~w=wx:/b8?QhcZ*vtbVW2p4ș"8A跿'qMuEL%a =YZrO1[Uc&`;;W~*+s^/m(>ćɏ4:j]/Fq_C EwZ[ŴeɩpD|| \: [v.1BA;kU姉[Fl ߟO"[0rD6 *jiit GN?r n<΍FwP;6 ݛ _QқO]vjYs/XnM7ڐhŽ#95 bSV;f\[7.pF>EZ(< ji}]#QرPd2Ct\A|D|M'$#E 6 ‹])Fm lS"(x7WizjvqڪKf,]NY74_a"LhtlXاu">h\q߀zE(/gWZjY k- ku&ˌ,[-?d l/r%DjY=(<pREټ^a'>uקSxyuwXLciW#z/0tn ^ Riu|\nx^7S e'{:Mtt5r>pÿ7w68fv…TYm2 p:K&^pf4'vX#&#:<l%-j5LV)/ \eMLy. OQn\ Y͘U@1n"=Tm<<>˚2f9RAeEYwBkNQ'V*V_p8g֌Yse' .U[MzŊ0HO10f$)K`I^2ڪ<о/vfAxĘ-Aw ;. #/;y2ez+40($E@rK[҃"*=`u1ⷬ\/?uoEt#=^+CaLyYl1Ap|C1@ફa*5nk5?Q%y9"َ'^ӆE$!Gy<,a %Z[*=,fJjx`r 4ա@ZW`^L'YMBzpN+.U#I>9'SG˘pǮʏK%J=Zj=esvxG"pL Uz#f)\"ѫ#+#jpA|wH/>> وnzyj*%frّ%ZsrsPl$.=no<ti&7` *%,Ɍ ĕaf(Y},a.lO_~vii`WΥo3_~Gs=8I7{2=#`䨜# sΕ7ܸ#Y<|  A0Kwe~nL̍rB&HV!s!Ɵ?"c πpGP*KKs;gLeu.JToWL!=,Γs ϏOWhGc౎Jv=9a%Z å;`\|Рʕ=w.$ @rc|: hFK) IUشt!0C[X}fH|/5|f>1>zQIGt! [owqJnJ/O-6B R>g|4nTTn) kkv{tW9^jfsPL.8|a` .Tb W]Rc:8+mo}.# kYFTd[EMzDsk[@wM}!g٦MO3I(ݕgGC$! I m|X甏g_ɺWo[ZvqJJu 0 7 Oݓv&dln1/pu}T 7㧊 :{/!Ǎm#xh*=YЯq]Z8hTJ#=E:X?TO˂jK`=m{ge6XS.I_XXl%j|?/A8S͹@oӆ"Grd4AK|+sViQhr/۫o'+R cORcz8@qcFmcuiFf\4$wzQ $[nrڮ@|$MEU}饀^T !oҚz76 nF/x#tCÀAzZ??sVqaw0˲, ea.0x{oC1{u!y%Z3Y(@5H4KkwFIe)<$vf!Dmy0\)=@oauﻱtȓ}+xivw{hU5kԟrcר0kYo=L/c{ӧcLRӱp蚉{K{o/ ;.<97{.t<EV1竣ѳK[zpOzk1@TyR5Fr}p+7Sx7=QGc xayt=w3ć%s&=<]1W{:j=;@9={v>]#ˈ7Se\|*eKuq}sz0LzWm}]#_\\|̚gU+ֵ˝c ye.{7</KY ;-;ٮ}dX2Opc$;FǸk,-^xȟ/>/^s TzzB:Ogv,>b;Ն\e;L~4U3xX(oˇq7}=AL;Tv6+ <+3lbVE@/'><ǣqWjX2=n亮&>`[Ns ^^ q@cl tݟBXƲv=Kod{oV6{g=:bxxk:#x9,@oi)߃ v bkGt7z__|KY3tȎ^?2hq6s^;9:|G~(9 ޤUv"gV9]v *Z ^Rm5 hO~&[~Ǔ@oe7ɼ^3 C41qv`(<'ZH F?jX?|=27^IzZ+/+GJxg,?F0.qtILZd0 ؟mW ?Y _oab^ʃ2'Vv l/W@`Yh0"~9@K#;Kx܄ȆK0~ׅLPzPU^Gy*QEz#?Xbz'4:;>`Uf7a!?շv\BZFrs|A%Dž|f} !eDϒ&:bg M&ՠ?|?L=rᱼ4?zn#hgFfA@H aʎJhjAw2A|+ fEq,ި6*?( *W^м͕`n"9ɮ 4+ ]o7z,o]r+Xqq o#Y[,c,vULHJȲpۢEOd6EЖ5mux=) B}Ṷv\(w6-6Aɫب9V%Eխt,7u8svL]m\4bC~Y U yAgbNt l'(Gώ׷VX_DɜxKT<Dxw xl[=(o+EJ9 ohg%ze5Mu4%/Zĭw/*;hW.@+ ƎcHx4n݉OV;/2S_DĖ(Y]ykV 1TS*ww ٙ dpWXdLhKf;qob5O{">/=!@ X.Q&!:O. BNӪM Wo_Obwxٙ VTmFwD`cq3&˙vvS箄_E6G yC|:"[ V6PuBxx7h=T$2U#ӗJ9 <h n|\>Э܋J*uS% 4 Dh&״x <I)ί 2B!TlIaZ5 \R$-hvlD3Z MύԧFZ_ƴM"xfHKAI @hS ?^Mt]Ja~ 5'|\, W$jQ> l9.T?C3QЭg'5I2x_nMLBh@fLlzbVKȎj,_*={t?}?Çid5ph e>ZtvnLnKZUSI$'@)59`DLC|3nROi7&K\Y8۽5XMO#! Cr&Qg_݃ے7SĬi~^'躘+b@|=T4JZJDf1".9 eeExLͳ@uUW]/ɂ'dfҳ%zmqHw}`6PWp$7Ў!йG;D Bsmgm,4\EKidj~l 0H"!QXf>7@߀^SM:f4wR?Bl%z+M!Y*t _C9#C ~.@3z @K i s|V:mTIgh >z/o抢#)3=aw2A;3@6V PXۥuc] xoA+:1@s)ɾj&`~@K8 U'O3;:rW=.%IE/?m K 0Vڵ x5l Co2hŅExnvWۚF-\nki֖, vb`<$K$nߢ:|y>Hy\եdZP\,yM.& >۸MA.=_|.'ܓm=B <^||X)WZpø* ^E O\4{ ~#x-v5 $@.Ւ;>N xr|8+լN OR xx( KZ:7&.)W9BP(yѱ\>SYM(jx#& 1m'MxN8Yw9dz?fI1. Z b q9" r?+ ]{լi4t4^P+~ 40UI`)n̋0/bcϔ=8YTPZIbd}BGjm1NyQcz<RN.iE1;|5Ւɕ՛R: 53BF)U^8"06 ^9OǛԷ"_^h{lJrC⸅":؂0 gTEӲc tX!!@|j t߿ɲ" [F獇aq6)ZH\3iAw/nx0_纑+Ua!P|}[aQt\FL7-̚%U'ũhx0>Ĥ7<b͂^X SU!rsNac: c>8fAH@=qzҞ]Ћ [n,98ZYx=1 5/nvdq`&1b ?XcvөG!]N)L*ꁯI#,mMu|pk[4IZ͂j} +>#>=;"^f" $I`lF4 K|Z"`X}긺gp{wv9"Z<9=}GH䂹''BzG鑁o]̳q㎬%59^98zq=wmQ{AG{ľ;H5^PqcRCzE'4:}zC\^{|k}hén`{g{~l<yr,Hh8sCVtҋ 7w6v{rg˧_ݽӭݗ];xr;>݃NwoMz1{p8y*?&D[w{9t:gggvW*%;;;_ܻq;0ӛaMu #aU3I}=ƽ8d 6_߼%ڿ}I֭v^ȥl{l H_MUؼY|fq3z0ՠJ d`w@r?twVyo6YKSNJ z0KWE03 PHGhTR |Aj= tEKhJ&>[`8R! u# dUa|M(J0րh5Xc+ D'StD\ZzB¯Jf?~Ɯ0p=>,2Ĩ'(8B];u|% _IS{຅TsY1] ͿǷp0ĥQ݈}p C/>Pz1U'7" ˗Հ3%)n5;LQwS40 ղf"@:-<0{ `xǫb:BmĮfP;p<&_çs Od$qL&a9Z mՌWך)<<L ==8=紁 ts81Rx3k-֦ eGٶf=#dSkOKNV1{0A pe]4VN/^HW9|<丘ey,[ \wsOLz OTqbelI_-"FYUZov&6 %D‡/@O^R -`W爙ASVO =7mp4$AP+WbΤC\l\FhgU3$ rs]ôbł`8f$I͚Q#*İOsCY?ȀX.[[NX!g؛Z*è$*FNdA|J_bX1 ^ð$ ϊ&S^Ff#VQɴ#c1At$8 $xtkKa@(ST!#) <iȬ /kVE {nEKsRңǔTlMpJd 6#E$\۬)B!ǿ`Ǥ<ǰxNd2OՈAߦ8 6T=f$I o{Oqt#sI8M8ʔLh=nY QGnv*ճ&q? ryy0%ۣDw?vU4ŸPs!7djƗ@&O1IB$2A<Ā0ɕ7g :(NpL65c,OH1 t濶"_dacْPǧEZx2 IUUī3@;<!v*> ^,F<>脧tp8WDOOd9.U"A /vgF[v&.DOؾ&`IR~>,=\D&A`0(|ƹn@{> -?v/mdkj*-,K_0(a`0$Y%$s1FPTH\u-nXXX{v[Vq9g&3dfٓF<VwZm⇹2ۼ(Vr-F~ZWeJ+y]>[V}<ܧK_W/nvt*d%uDuNwʕ+b,S]9{ ϖ+ KzZ}<ߕkڨ _X.#nGA[]^gUڍf#B~mһUJB5][}z=3<\gVaX 1 dp״#羮<F&- x/yt*2\%'vF4#ZQ,=0`,Z"9emL/hH}<6]<W|FrhoׯP:M'mxo4J*IғClFgצS~5BII`g h ٥GN{.p e!:8'zUHFz]׼70עBЈ\^28&#4}7;|h1CR]: [/=O!8^)TlCn봌yck04#T$΀S|?*a ><h =Z <G!V( &Ep|4ZKOIrq17J@G|c5s{mmY%77)g.m4 "ϥefŜ0cMLwA@#HI; a9lHWVWlC/bk|1kznq/Ϳ#cJ_u@LA  ԖrR L@*_ؗ6-lkL "4܅\* 0BzOehz"]P {NmC@/wThB.7n~/{^]?&84۝6i4b 95ˬ-tȦ"J ˠ?q}}s\jP̼#4fg }Ml-@XdrG mԀ)8njďW6WҨѾ<BFhϴ5ܴ,)r)MF KX`dJ[iR)3|X䬃)]{ziYʥ\BrӹLd[Y:d- >/=sH#42sXܧw.ω\Fp<K3n/]&zJۥQS@z+̴A-1]B“M- 5|}#=_K}/^.K\ӈfemy{`]?Yz^S9~aO#T X1ӽxq<-fʭ| ah ]IEE Qz=ަ{4-*@oySnStI@zТW};c؏9mɅD\LD% 5 {s4H{dL)Nm 43l*(^t L`/Ȣ˙jc_RdHӤy0|1ͭ!=9 $zbLiwE/~|/||3VQ8V #~L|tޞ af2ŔPre_mn<A1hfEtwĤh ћ%Ƿs5Eon2x*4~{>ɻw,؉m VON_ $= Cc 3sNwh[xT2Wٞ;%q}vٛ`*ix0(BjU|P8(tFp(_iSj^TM!=2\mn?[~=Z 6R3एp_MFmxًeBΟ:<.u C$Yt?/[$j ANjҗ&z{!9v.)ޖ>T~󕭔fq完E߂0%IOj(.NH|Y|M[X izRB2:F|bS1mEgsF4%axKjLWgzIA|f=e3>L[$Fǡdeö.7נ$=a(nPrl>htT?hH,m1n/H̆eƧ'3==MI/A)],qdPňqBN >V{Do/ |t^ڽTr#xO>-@_R;]:]Ct˭cNue{-/lK~ =qB1w`b򕭔 DDM7KRӪ0Q# q[Ywa6~oyyOKئ?N &O! ?)oU"Q~E{FC|tYQ^R2 Ll"Zhm+yEЏ 7,Zzw* E•H9{钞H.!sTQRO:hoayS\!|Ώ3Rhn/3>7U*Qjϱ#h/=#l"ˍ)ꯅ_B^,|&DQ}-kTi^~v^M\%|4G̖ a>14c !>=vy <\Yzmedo1]"Lwx[kCO^ ='퉸Ev{a?94#\~]Br(6uu{mԄ~b =nY,|;zs Z;AkGoJB,Yv^a<|{*H_6=w~]L-»ND_2XWv]gEO! uzI0hTTDl# W,K6y.Vˀ _Z, 㶮cԝ?BZ1A6E'Y"! yiƠyThDVGj)DF(c{νq<&6Ϸ{9S@!a@w>e) ]`^x{;X5ᣝ*/zx01b8Sx4ќKLJ{CcT'vK{:M%3C_𽚞^3q=)y;<>fʫ 9YrYF!g]NDAquPzW.]H81Um=Ѩ/nBϱ .8gb c;|{uzf~5VVkCz=:@DC1sÕږsImȢCoxAb(.zlek`mui$DTnmfowۢD.afƋv{Y0wqqV-$Z&.iN躌\^A<=|bngt؜N'4M89esc%*Y2^qOiг{h D|}}7M#MǓMGtjSMK/?~'u3eV$'鵷cG>{yK>%Ǜ0w,HkZ4x~<DmA̞G|A@U I}gE&=/PzzH1m{wu0M|)U'Jc>r>赵|}ңg&D_&͢{iލl;Xcscs&Oqn]vQ|)^+MI^N2Bi^~b2yc"|x"g`wzz;HҒy^W],J ς(%+U٬mVK &@67>sFC>sv!W\!,{waA1UFgs4{ W%,Iw(Qbd~bG(<qYw.,嬧 z _o Jz}k}}~E,E4ׂ1q>E|R:s*ѽp'R.z:ozcHPuūt=z'n`=)frƥ(P^~3鳢E@;l~.(_쀹[Yk j)ts]c$ ѓуξfJݹH kWjx*ו0> p\87ȩ4pgc[7K':dCEXM3-=*|3aÚ֭6(B-Ӕ6-=o}li4sE$I(rqg)gqKY> zN0zE0^kWzg>s4Ckr2?s8=A6dΗ,/rTg؆|u¾׈ie,퐼S-z=Gߟ7;NۙEN<Gz?6n$jd?=NHzӳ#щ #iadmױH/Gd4TPvF>ؘ<uϨ^ r1-7)p;*ָ'+o7d;t\HIݸ`hR:N3zr|& SWu$baL0{؍:b߰C }7kx2L!Ž%Aꥫ<M50^^ҖǣkO1XrjNt8O |S|TrPܬ6+BRnju&X*ˋN堐_TV*+aT*|rAO-Vwv*+fъʠSy lHpr|!ʖ"R;Ki7A{޹tpBXIQ.(x4dH5,†P =rg~t^N1@.~g)]|+Jb0̧e:V:e|$jJ;HwLP5fG_YOK f1وB^W ͲUc^Xo:x Жy.*[m\-Or@ /C<mMIJ_]l)d!;Sfxeɇ/\,G©vJ$J9e],3 Bu{Jl@ن߄67U:"Xr 3{ݑX6%OT]'*8jP6-ɋ6mSŝ METLPXBfj0)dK@dR.P*.^58%$ݿvzzh+ھ4(>^ONGUx^+*TU1 Yʊ\JC]/($|;GYe瓾gDz!+TWo8M}!'/ ::ܢR8UKO6%mX 2.ճZ<[ 6HĤ)X ZڦF$+i"["~7tmEs͡}g-  "jDׁݩ̓u JLk<fN:ȱtN|CVDыBo]r_{{pTW\n(GhB%8(~ zC!ᕕx^jD1w֜2e& 3 tUwG>SLG' JfQk!z>c~C_N1?$j=b*b pٚ!eXupK9Jv4Hz¢]TJ7NXB&z߆,§]/'aMˬnORUlǙFҔ% ze)eVf0,\'D`E:FDg"w/c Jr?B/LO)7y*$Gz8Ϊ^m]Ҫ7}z|)Y.\KƖEb:`1Kv4 cDŽKDX;KH msfΌ_Ȯ=F1O</62V؉B A~7"c6V|fu\ |XOI6|!`čG" қ0vi0>Q6 faVzTEU5%M>L{gg-Uw;.>Uo (f=*|]Q8…70<C{OLv2>K;{3%"*pX4xjO. b6s)?ʲΪf|wa,K?̬#zﰞb* kI/kI2CY')$"se|{9 z25Jv!_2T&=mvTb'@:rgᣀ=+>)ݵ-MfB7`W ʣSM*ײQ KYQH|a6nZbHBi5333; @$5 #.pO8="d7yܽOmi W5MurJŐ}r,ǃNXec!qS̓=1c-Lx Dw=a_b[jrUwxun) ?%uh[v_a25f x-_(sHt>cQ>(|73S(ndz#ydķ.79-sG1i\Ukc}}ܑ\e` w3mo÷b?߶ݎYt G Äw"ynﶏ.[xlr,c+<{ڇgKtgX 8XzߨEkg$3Y@~րzdoWh .'ϟ;xcII\rz2? zڤݒW8U9e9zZҫNޖv/yߥxAnmc !6 ^,obYG D ܾfk~&~W{h{-tXb`:==G#x=7$z\X&]M1^IFRvL@첪owݕ1o6.ı<8K~KQj/0=|@-x?Pkң}IqGN 2GS ƌc_#L{o&~e cw.~2? vL fyOh6[fRqp [;B^ ݺ,-U~ݿx3caYBxu1vSgᅇH|{䀧 z-g< Pu[Od/>FgsTkwhEtܛ2=,,iLfmͤbB:E. [,2<3/gLixsCeUfR?zL+\n/!Fy^R[[{f }+0bJm/3c(ˡ i=W6Wilrj׸GŻHUGWBz]+BxX C7"z2/H{Zmܲ_ZqMwGqQ1JI:Wǐ/C}#%GeOO(ƧW=D7-z6*^r]#m=Y㇣=RՒNej-h$tt7+8yb:*gLڡvk o|ēēm)!%zQapާ_%OhWjh0.oKrZr1EqeHR=-z 5Tqf60%ot*.g3ZN~v[FK ?dM%rgmKؼrE-5OF1AʪX0KY U<j`q?Ͱ^'4?_;Bgk686vC -e)t;r](˒A`GcwhXYP@}wARgM'СПf^0Dh3VRj%K~ /Kf72qվ$ޠŔ7zKt"7Zx! [k2Vh]TNnKGS!! .Zj_rusH 5r:GWo.Z!(6k-3\z,k~ #G06s &y5)]C" ": 'K|&\$L*Q+8 ^wbp6Ce }0|hYeW7azm_Mc=M/0|>]|e9L/hkD0;ASF9!F5 Ž L"~Nӛ ^>8i'zL[7\87['&sDSz~Ҟ)PĮ5t;Ӧ<Is9nr%Na>xu^)ɰ?q<NpЃV"Je><qx<U'Q%]< e3@S.;2je $t'73z'4p6e?LuVq1yܽS+d8磏gf@7>_@Bh-Flqa}{mMq+DG"tqd1{kH,0$?_p=:-28\h kPZ< RԲT&j[c`2=e g"ѣH,r9g 4 ujV^/ x@hӞE~i~8Ͼ"c]1_|իVmYk@Hbq$Ք,TK%D^c4=I}>UNw\{&Cl(un7Ç߼yÇNOO߽{ L*jC:JՑZ-ف > IИ#_4_~CM|~n]MWۦ4j*izhcF[,<= G# ,iY*Yl㰾uz9'}͛7׉|?s<x{0yoIdb 2ɩݫWAn \B<L?e .Tz"8ej*z^ݻn( uՁ?;=t@dpEoz SQ7bS@`-aQ˸TOFJ۷ *զJj+I[տL$%`_@ < .)=LCEzbMEEdwT߿~ߠ{oit|~Ӄ[T.tb dCϮHy8DK;ۍJܴ <4+fdj݇o~xarGoz=K:X*|%"Xl"",R4]{m[(kh( ײy^1X0= w;"݃Ite79C/bea/X1` m 7=T?siV!5$7PAMd)R\az=WyŦ)hã= ?®(,9rz`i-Kb7 P`a>( ϙyna-16㬦 (ba_M@($%ZƑ^M;_=21wull`^V@E&,/i>$:7=PEbr _y<!y(sZ%0^deYXOÏ_l% NJ97bjl!@zb8J_Y>@%9˵H@~ \hv97@R|_j@z9G TnPv Z Lg͍D¡؟$fhRZ`MOe CW\AA-ON|* B6(E!Kat> br"S"1b,p҃lh9;j`q7?wdT ~ߠQ@ J?  ?ϦgTUq?g*tpWvVvb +þ >yRW;՝^|W"vIuQq Ѿy>/Ge Bl1_JrD(mYVwbP?_j{1tM9U{0_]uV]H.ϭE?@|6 2"?h=,>}YjnA@1|Ji3Y`}[(tAbN%PW׶PYTO'UuNlUfcI@o\wXf nY8z(HϬ-[{VS3JF @t[bBNяna1x6wsf-Eg]$R\AV<ͥ2Q @=K?H$$^|VJP:[PN ub,%Zt]!|k33F 6gh禳 OD|C]yB8n&~cාS'6ɇs,T<|"ėـMIGx/<!v Õ[H=]D0#773s_h9kwڭboF#L)@y F;KԭDby1"FǞV;t}g0J㞓] ឡ~/5mZQCϗZXt/7MLn "*;w(Ɨw#@J^T՞Nabh-2" v Ƃ-L/͊h|>vz:]O(Dǐׂ%P \PuIsډWNsB'‘h _W;D/2ADŝ]: R?4{ ^Aw> &  _ ٩ u?R0;x";sG]ơq¸2;Lx'i޾7&Kg Kz Zs73q. :>7ŭ*ur˯'VOZ( ^ @.ˎi7b|,x ]CƩ%>RU$q3Z?p7@@`!Kib/VG?lW/{mroXڍO'&l@ģtk,vbl|=C' У/=};^mzTKa[ۻPd4~2v7cR%FukzlEϵmك1<n :;=ձ,iӔj;G&PZ?@x4 7[İR48= >* SG]VģztGvb< l| ##NMNL}ԳҪ<<LJg7gĢw`5:/Ng_C@6/v{MXDxO wBA@c?ov8H\t\4ݳv(e)20:a|gNꃥN99懸y@wcA/4'IZ$)]T:ۇۻ{@=/|$;w*T^giiXh"2Mr7L< ɩۖ'#zʧۧ-eH fO'"U<BؿyK x~|H 覦nLEsTK\ ww%+<~uK/%vB : ;/Ҽۯ(`6{'8>MqƧ=Qez76+'ehHq=r.mdYwI(@mӄJ`UW+bHV3 M `Л7sʏ<$y{O]ח1ϭwrߞ>;葳h$l淧gU~2>3<anE[{n'FUX8&}3<Jo﫫ѣ,g'ӜKNrxSуiG32w>䧅޿$z'`'3KExD[{#|ECǏ7<;A4ƞǧ_?׸Uzc|P @UL =jx-ʯPioGgw_5Q3-j'<1c_~D'1*5$x$v`Fnqo-*^X{7xߏ4 0? Oblž%zWTV~JG}\, _z >֏9'A$? ߞ0x:8a9n{j"g5wb~~a1k3#ڃQGG Q,cC;>>HƇI=+<Qw^z.~7ޘ!U">,|~'Ə{o-JK7ʀy9n/jGzL)w5DOxH-G>D|ci't| =$<|FNI }{V4r0wp@<\]+鍏;'L~TxrT/ iVzpbGG(H=4v[:" ^nhoYM渊XXc)y=Hoz0lhS)#b40)Ӆ XZp>i[#cVξ~(?ׅNS'K5u\ S{ȦĢ~QW Ozx|Rzр%4wm _ ~T0z`^v)@xoOO^ Fmu\zs۸ Ge08#o->$x2>P|=&=<4+UAX°'y-vVï^'oOs[Ҥz`nOnC%ܕ\C*=wb_踀W,]bۍd Rxz8*>[zJe=,Y~fݠւq,C<F}|>k4y疰di!7#'Xښ=5 'D8;qzC)KL޶K`f];. p~%)W*>uZ襬` r\8xMR-\f x;ju=xT#y9+ˢE{Y0Rfayn{ћ2x&(^7ҷ;?nׄ"Gzʳj/az?<_zzEl ?f3A0zI^{4g+9׋^:Ed[W8!Xso~VaԬT >\6+/C^[ߦr+U,uA| =V|~X=0[k>B 81Q=s!^+11PHb< 2h#JN35:}>J=ozX}VbQ!2LmSi -QK⋔z.zۇvCg<klɚTj>}yTw G(fQ+p+/[c//8lj5_VGՕymqY$Vz]mW3zbf E7&hO[w E U 7R"HZ ^ #5{Ky?W%}"b m0Ճ K[cی=0o*T|2w^b'm+-0"L{N[gjm,KuAO]Oqܳhog#kQx.=Jit~Q4$1rk"Tz7Y:'+"Ҿy[w&xbMmÁ[/lYA?]P?FZXi\CFo^J:JozzG-lc|_Z%0|,F9@I~Lƭ{\~|BdHMl+rG6 Q]g$ӣGO2kƖGgmᅢvL FY10#HD~Zs+$/q/!;݁i~O]c5[xQAz<e#&~Af>S#!9<Q zi2ΫVkt;0 7[op~AУ{%QY}r 8Nh#9Mm e5@zNggium_JyOG8@N?A!k-NVVNki mz'XGi$|F~AMaxO._q ?{0p>㇇SZk?k#Et": |)=7~[nF'M}VbTX)jdDžgdjMwO^6݁lqFh,c&9hޑUx& !kܛX]u}͖ w qڴn(8ވ5z^V1I$;`=ۑDɎd zsr+UZ|~:n1͊&8J)q͉4vh9Kvys(M T%S$tĺFM<xk9dq$Ǘ_#08RMXJ(B;&YЉZg7= A1ߦ待*l}S>/ i; Qvtv/~/ӻsҳj<iY HaG>/p2<}Y;O_'^)#<k;BfBuvd *O_?0)$9̴Qq$Bؙ~Y6 s#ajH1~fӸ7}DNѸ)tBصI? 3 [12;m )"ui# +ml3I&cE i XԾ`>=.|Mۿ?EԀr$]l괭0˫]Qqk6V [W9^|B?ߚ'ݵv)=`Y{{:Vr6֑LD ߫)KbQ.ucSi[ OkU[@-Xd;Ns@w墲lDۺoj;]uٟ{MFʱtN3_l-qN%N8[Q?U gj ([onHt/Wӱ `Ydԃhz&/OE(Ґl4V7~8+MwƳQm"pj $0oM]8UĎz< ڃiE0M$=hd7IyyH1$1gt4W w}z7$ƮsspVti2y"򐵬Lɬ[ y;<72 !0 :4h5(u\Wy#5%ws` IcFsWB2b՝10C.53.?]B0&ĆqT-HkI,^Sm9DCnr1 !CĘ1M 7[.- ˢL rU7@FFo #!!0Ĉ4zI e\ؠHADŤ =R# bizw`J xÐ#R<-Hl1+-%eK a~<\LFɃ|"|PlEJIENDB`
PNG  IHDR=GgAMA asRGBPLTEGpL  $7.G # e {}~~&y?I8MH` "l|/"w'xz v 0zB#H$?J` 'T^l %z &М/_s:OgR$ 'vP " xmju +Wze][p1"-7a|<G~?rs()7N .XAV1KC%@b:=@8ӊ/GSEKWl41}!}bŹɯd³mYXJvw,u)'&hf[%nOsjVVVH~~~) EEEfff544rrr׹cP7raGꡠ@qɲѐ.Vd~{DARLkLj,|DN\Z/KfMtRNS- 9? '3JYl|6$NL֋3o`zfAӪ옇i۶yӮ ֪dIDATxKiG4̍{tXQ*-Z+;Ȅ!11\8cXݖ xE"VʵOG.[լ-E".<$dd-d5y)/b\N\^q)erb2ywp0π|0&EXvhxǐ('2 + ~a.h@js^ =*@.6g,7GA~$KxXںON"$4]iVmׇF@T|]k~w=wx:/b8?QhcZ*vtbVW2p4ș"8A跿'qMuEL%a =YZrO1[Uc&`;;W~*+s^/m(>ćɏ4:j]/Fq_C EwZ[ŴeɩpD|| \: [v.1BA;kU姉[Fl ߟO"[0rD6 *jiit GN?r n<΍FwP;6 ݛ _QқO]vjYs/XnM7ڐhŽ#95 bSV;f\[7.pF>EZ(< ji}]#QرPd2Ct\A|D|M'$#E 6 ‹])Fm lS"(x7WizjvqڪKf,]NY74_a"LhtlXاu">h\q߀zE(/gWZjY k- ku&ˌ,[-?d l/r%DjY=(<pREټ^a'>uקSxyuwXLciW#z/0tn ^ Riu|\nx^7S e'{:Mtt5r>pÿ7w68fv…TYm2 p:K&^pf4'vX#&#:<l%-j5LV)/ \eMLy. OQn\ Y͘U@1n"=Tm<<>˚2f9RAeEYwBkNQ'V*V_p8g֌Yse' .U[MzŊ0HO10f$)K`I^2ڪ<о/vfAxĘ-Aw ;. #/;y2ez+40($E@rK[҃"*=`u1ⷬ\/?uoEt#=^+CaLyYl1Ap|C1@ફa*5nk5?Q%y9"َ'^ӆE$!Gy<,a %Z[*=,fJjx`r 4ա@ZW`^L'YMBzpN+.U#I>9'SG˘pǮʏK%J=Zj=esvxG"pL Uz#f)\"ѫ#+#jpA|wH/>> وnzyj*%frّ%ZsrsPl$.=no<ti&7` *%,Ɍ ĕaf(Y},a.lO_~vii`WΥo3_~Gs=8I7{2=#`䨜# sΕ7ܸ#Y<|  A0Kwe~nL̍rB&HV!s!Ɵ?"c πpGP*KKs;gLeu.JToWL!=,Γs ϏOWhGc౎Jv=9a%Z å;`\|Рʕ=w.$ @rc|: hFK) IUشt!0C[X}fH|/5|f>1>zQIGt! [owqJnJ/O-6B R>g|4nTTn) kkv{tW9^jfsPL.8|a` .Tb W]Rc:8+mo}.# kYFTd[EMzDsk[@wM}!g٦MO3I(ݕgGC$! I m|X甏g_ɺWo[ZvqJJu 0 7 Oݓv&dln1/pu}T 7㧊 :{/!Ǎm#xh*=YЯq]Z8hTJ#=E:X?TO˂jK`=m{ge6XS.I_XXl%j|?/A8S͹@oӆ"Grd4AK|+sViQhr/۫o'+R cORcz8@qcFmcuiFf\4$wzQ $[nrڮ@|$MEU}饀^T !oҚz76 nF/x#tCÀAzZ??sVqaw0˲, ea.0x{oC1{u!y%Z3Y(@5H4KkwFIe)<$vf!Dmy0\)=@oauﻱtȓ}+xivw{hU5kԟrcר0kYo=L/c{ӧcLRӱp蚉{K{o/ ;.<97{.t<EV1竣ѳK[zpOzk1@TyR5Fr}p+7Sx7=QGc xayt=w3ć%s&=<]1W{:j=;@9={v>]#ˈ7Se\|*eKuq}sz0LzWm}]#_\\|̚gU+ֵ˝c ye.{7</KY ;-;ٮ}dX2Opc$;FǸk,-^xȟ/>/^s TzzB:Ogv,>b;Ն\e;L~4U3xX(oˇq7}=AL;Tv6+ <+3lbVE@/'><ǣqWjX2=n亮&>`[Ns ^^ q@cl tݟBXƲv=Kod{oV6{g=:bxxk:#x9,@oi)߃ v bkGt7z__|KY3tȎ^?2hq6s^;9:|G~(9 ޤUv"gV9]v *Z ^Rm5 hO~&[~Ǔ@oe7ɼ^3 C41qv`(<'ZH F?jX?|=27^IzZ+/+GJxg,?F0.qtILZd0 ؟mW ?Y _oab^ʃ2'Vv l/W@`Yh0"~9@K#;Kx܄ȆK0~ׅLPzPU^Gy*QEz#?Xbz'4:;>`Uf7a!?շv\BZFrs|A%Dž|f} !eDϒ&:bg M&ՠ?|?L=rᱼ4?zn#hgFfA@H aʎJhjAw2A|+ fEq,ި6*?( *W^м͕`n"9ɮ 4+ ]o7z,o]r+Xqq o#Y[,c,vULHJȲpۢEOd6EЖ5mux=) B}Ṷv\(w6-6Aɫب9V%Eխt,7u8svL]m\4bC~Y U yAgbNt l'(Gώ׷VX_DɜxKT<Dxw xl[=(o+EJ9 ohg%ze5Mu4%/Zĭw/*;hW.@+ ƎcHx4n݉OV;/2S_DĖ(Y]ykV 1TS*ww ٙ dpWXdLhKf;qob5O{">/=!@ X.Q&!:O. BNӪM Wo_Obwxٙ VTmFwD`cq3&˙vvS箄_E6G yC|:"[ V6PuBxx7h=T$2U#ӗJ9 <h n|\>Э܋J*uS% 4 Dh&״x <I)ί 2B!TlIaZ5 \R$-hvlD3Z MύԧFZ_ƴM"xfHKAI @hS ?^Mt]Ja~ 5'|\, W$jQ> l9.T?C3QЭg'5I2x_nMLBh@fLlzbVKȎj,_*={t?}?Çid5ph e>ZtvnLnKZUSI$'@)59`DLC|3nROi7&K\Y8۽5XMO#! Cr&Qg_݃ے7SĬi~^'躘+b@|=T4JZJDf1".9 eeExLͳ@uUW]/ɂ'dfҳ%zmqHw}`6PWp$7Ў!йG;D Bsmgm,4\EKidj~l 0H"!QXf>7@߀^SM:f4wR?Bl%z+M!Y*t _C9#C ~.@3z @K i s|V:mTIgh >z/o抢#)3=aw2A;3@6V PXۥuc] xoA+:1@s)ɾj&`~@K8 U'O3;:rW=.%IE/?m K 0Vڵ x5l Co2hŅExnvWۚF-\nki֖, vb`<$K$nߢ:|y>Hy\եdZP\,yM.& >۸MA.=_|.'ܓm=B <^||X)WZpø* ^E O\4{ ~#x-v5 $@.Ւ;>N xr|8+լN OR xx( KZ:7&.)W9BP(yѱ\>SYM(jx#& 1m'MxN8Yw9dz?fI1. Z b q9" r?+ ]{լi4t4^P+~ 40UI`)n̋0/bcϔ=8YTPZIbd}BGjm1NyQcz<RN.iE1;|5Ւɕ՛R: 53BF)U^8"06 ^9OǛԷ"_^h{lJrC⸅":؂0 gTEӲc tX!!@|j t߿ɲ" [F獇aq6)ZH\3iAw/nx0_纑+Ua!P|}[aQt\FL7-̚%U'ũhx0>Ĥ7<b͂^X SU!rsNac: c>8fAH@=qzҞ]Ћ [n,98ZYx=1 5/nvdq`&1b ?XcvөG!]N)L*ꁯI#,mMu|pk[4IZ͂j} +>#>=;"^f" $I`lF4 K|Z"`X}긺gp{wv9"Z<9=}GH䂹''BzG鑁o]̳q㎬%59^98zq=wmQ{AG{ľ;H5^PqcRCzE'4:}zC\^{|k}hén`{g{~l<yr,Hh8sCVtҋ 7w6v{rg˧_ݽӭݗ];xr;>݃NwoMz1{p8y*?&D[w{9t:gggvW*%;;;_ܻq;0ӛaMu #aU3I}=ƽ8d 6_߼%ڿ}I֭v^ȥl{l H_MUؼY|fq3z0ՠJ d`w@r?twVyo6YKSNJ z0KWE03 PHGhTR |Aj= tEKhJ&>[`8R! u# dUa|M(J0րh5Xc+ D'StD\ZzB¯Jf?~Ɯ0p=>,2Ĩ'(8B];u|% _IS{຅TsY1] ͿǷp0ĥQ݈}p C/>Pz1U'7" ˗Հ3%)n5;LQwS40 ղf"@:-<0{ `xǫb:BmĮfP;p<&_çs Od$qL&a9Z mՌWך)<<L ==8=紁 ts81Rx3k-֦ eGٶf=#dSkOKNV1{0A pe]4VN/^HW9|<丘ey,[ \wsOLz OTqbelI_-"FYUZov&6 %D‡/@O^R -`W爙ASVO =7mp4$AP+WbΤC\l\FhgU3$ rs]ôbł`8f$I͚Q#*İOsCY?ȀX.[[NX!g؛Z*è$*FNdA|J_bX1 ^ð$ ϊ&S^Ff#VQɴ#c1At$8 $xtkKa@(ST!#) <iȬ /kVE {nEKsRңǔTlMpJd 6#E$\۬)B!ǿ`Ǥ<ǰxNd2OՈAߦ8 6T=f$I o{Oqt#sI8M8ʔLh=nY QGnv*ճ&q? ryy0%ۣDw?vU4ŸPs!7djƗ@&O1IB$2A<Ā0ɕ7g :(NpL65c,OH1 t濶"_dacْPǧEZx2 IUUī3@;<!v*> ^,F<>脧tp8WDOOd9.U"A /vgF[v&.DOؾ&`IR~>,=\D&A`0(|ƹn@{> -?v/mdkj*-,K_0(a`0$Y%$s1FPTH\u-nXXX{v[Vq9g&3dfٓF<VwZm⇹2ۼ(Vr-F~ZWeJ+y]>[V}<ܧK_W/nvt*d%uDuNwʕ+b,S]9{ ϖ+ KzZ}<ߕkڨ _X.#nGA[]^gUڍf#B~mһUJB5][}z=3<\gVaX 1 dp״#羮<F&- x/yt*2\%'vF4#ZQ,=0`,Z"9emL/hH}<6]<W|FrhoׯP:M'mxo4J*IғClFgצS~5BII`g h ٥GN{.p e!:8'zUHFz]׼70עBЈ\^28&#4}7;|h1CR]: [/=O!8^)TlCn봌yck04#T$΀S|?*a ><h =Z <G!V( &Ep|4ZKOIrq17J@G|c5s{mmY%77)g.m4 "ϥefŜ0cMLwA@#HI; a9lHWVWlC/bk|1kznq/Ϳ#cJ_u@LA  ԖrR L@*_ؗ6-lkL "4܅\* 0BzOehz"]P {NmC@/wThB.7n~/{^]?&84۝6i4b 95ˬ-tȦ"J ˠ?q}}s\jP̼#4fg }Ml-@XdrG mԀ)8njďW6WҨѾ<BFhϴ5ܴ,)r)MF KX`dJ[iR)3|X䬃)]{ziYʥ\BrӹLd[Y:d- >/=sH#42sXܧw.ω\Fp<K3n/]&zJۥQS@z+̴A-1]B“M- 5|}#=_K}/^.K\ӈfemy{`]?Yz^S9~aO#T X1ӽxq<-fʭ| ah ]IEE Qz=ަ{4-*@oySnStI@zТW};c؏9mɅD\LD% 5 {s4H{dL)Nm 43l*(^t L`/Ȣ˙jc_RdHӤy0|1ͭ!=9 $zbLiwE/~|/||3VQ8V #~L|tޞ af2ŔPre_mn<A1hfEtwĤh ћ%Ƿs5Eon2x*4~{>ɻw,؉m VON_ $= Cc 3sNwh[xT2Wٞ;%q}vٛ`*ix0(BjU|P8(tFp(_iSj^TM!=2\mn?[~=Z 6R3एp_MFmxًeBΟ:<.u C$Yt?/[$j ANjҗ&z{!9v.)ޖ>T~󕭔fq完E߂0%IOj(.NH|Y|M[X izRB2:F|bS1mEgsF4%axKjLWgzIA|f=e3>L[$Fǡdeö.7נ$=a(nPrl>htT?hH,m1n/H̆eƧ'3==MI/A)],qdPňqBN >V{Do/ |t^ڽTr#xO>-@_R;]:]Ct˭cNue{-/lK~ =qB1w`b򕭔 DDM7KRӪ0Q# q[Ywa6~oyyOKئ?N &O! ?)oU"Q~E{FC|tYQ^R2 Ll"Zhm+yEЏ 7,Zzw* E•H9{钞H.!sTQRO:hoayS\!|Ώ3Rhn/3>7U*Qjϱ#h/=#l"ˍ)ꯅ_B^,|&DQ}-kTi^~v^M\%|4G̖ a>14c !>=vy <\Yzmedo1]"Lwx[kCO^ ='퉸Ev{a?94#\~]Br(6uu{mԄ~b =nY,|;zs Z;AkGoJB,Yv^a<|{*H_6=w~]L-»ND_2XWv]gEO! uzI0hTTDl# W,K6y.Vˀ _Z, 㶮cԝ?BZ1A6E'Y"! yiƠyThDVGj)DF(c{νq<&6Ϸ{9S@!a@w>e) ]`^x{;X5ᣝ*/zx01b8Sx4ќKLJ{CcT'vK{:M%3C_𽚞^3q=)y;<>fʫ 9YrYF!g]NDAquPzW.]H81Um=Ѩ/nBϱ .8gb c;|{uzf~5VVkCz=:@DC1sÕږsImȢCoxAb(.zlek`mui$DTnmfowۢD.afƋv{Y0wqqV-$Z&.iN躌\^A<=|bngt؜N'4M89esc%*Y2^qOiг{h D|}}7M#MǓMGtjSMK/?~'u3eV$'鵷cG>{yK>%Ǜ0w,HkZ4x~<DmA̞G|A@U I}gE&=/PzzH1m{wu0M|)U'Jc>r>赵|}ңg&D_&͢{iލl;Xcscs&Oqn]vQ|)^+MI^N2Bi^~b2yc"|x"g`wzz;HҒy^W],J ς(%+U٬mVK &@67>sFC>sv!W\!,{waA1UFgs4{ W%,Iw(Qbd~bG(<qYw.,嬧 z _o Jz}k}}~E,E4ׂ1q>E|R:s*ѽp'R.z:ozcHPuūt=z'n`=)frƥ(P^~3鳢E@;l~.(_쀹[Yk j)ts]c$ ѓуξfJݹH kWjx*ו0> p\87ȩ4pgc[7K':dCEXM3-=*|3aÚ֭6(B-Ӕ6-=o}li4sE$I(rqg)gqKY> zN0zE0^kWzg>s4Ckr2?s8=A6dΗ,/rTg؆|u¾׈ie,퐼S-z=Gߟ7;NۙEN<Gz?6n$jd?=NHzӳ#щ #iadmױH/Gd4TPvF>ؘ<uϨ^ r1-7)p;*ָ'+o7d;t\HIݸ`hR:N3zr|& SWu$baL0{؍:b߰C }7kx2L!Ž%Aꥫ<M50^^ҖǣkO1XrjNt8O |S|TrPܬ6+BRnju&X*ˋN堐_TV*+aT*|rAO-Vwv*+fъʠSy lHpr|!ʖ"R;Ki7A{޹tpBXIQ.(x4dH5,†P =rg~t^N1@.~g)]|+Jb0̧e:V:e|$jJ;HwLP5fG_YOK f1وB^W ͲUc^Xo:x Жy.*[m\-Or@ /C<mMIJ_]l)d!;Sfxeɇ/\,G©vJ$J9e],3 Bu{Jl@ن߄67U:"Xr 3{ݑX6%OT]'*8jP6-ɋ6mSŝ METLPXBfj0)dK@dR.P*.^58%$ݿvzzh+ھ4(>^ONGUx^+*TU1 Yʊ\JC]/($|;GYe瓾gDz!+TWo8M}!'/ ::ܢR8UKO6%mX 2.ճZ<[ 6HĤ)X ZڦF$+i"["~7tmEs͡}g-  "jDׁݩ̓u JLk<fN:ȱtN|CVDыBo]r_{{pTW\n(GhB%8(~ zC!ᕕx^jD1w֜2e& 3 tUwG>SLG' JfQk!z>c~C_N1?$j=b*b pٚ!eXupK9Jv4Hz¢]TJ7NXB&z߆,§]/'aMˬnORUlǙFҔ% ze)eVf0,\'D`E:FDg"w/c Jr?B/LO)7y*$Gz8Ϊ^m]Ҫ7}z|)Y.\KƖEb:`1Kv4 cDŽKDX;KH msfΌ_Ȯ=F1O</62V؉B A~7"c6V|fu\ |XOI6|!`čG" қ0vi0>Q6 faVzTEU5%M>L{gg-Uw;.>Uo (f=*|]Q8…70<C{OLv2>K;{3%"*pX4xjO. b6s)?ʲΪf|wa,K?̬#zﰞb* kI/kI2CY')$"se|{9 z25Jv!_2T&=mvTb'@:rgᣀ=+>)ݵ-MfB7`W ʣSM*ײQ KYQH|a6nZbHBi5333; @$5 #.pO8="d7yܽOmi W5MurJŐ}r,ǃNXec!qS̓=1c-Lx Dw=a_b[jrUwxun) ?%uh[v_a25f x-_(sHt>cQ>(|73S(ndz#ydķ.79-sG1i\Ukc}}ܑ\e` w3mo÷b?߶ݎYt G Äw"ynﶏ.[xlr,c+<{ڇgKtgX 8XzߨEkg$3Y@~րzdoWh .'ϟ;xcII\rz2? zڤݒW8U9e9zZҫNޖv/yߥxAnmc !6 ^,obYG D ܾfk~&~W{h{-tXb`:==G#x=7$z\X&]M1^IFRvL@첪owݕ1o6.ı<8K~KQj/0=|@-x?Pkң}IqGN 2GS ƌc_#L{o&~e cw.~2? vL fyOh6[fRqp [;B^ ݺ,-U~ݿx3caYBxu1vSgᅇH|{䀧 z-g< Pu[Od/>FgsTkwhEtܛ2=,,iLfmͤbB:E. [,2<3/gLixsCeUfR?zL+\n/!Fy^R[[{f }+0bJm/3c(ˡ i=W6Wilrj׸GŻHUGWBz]+BxX C7"z2/H{Zmܲ_ZqMwGqQ1JI:Wǐ/C}#%GeOO(ƧW=D7-z6*^r]#m=Y㇣=RՒNej-h$tt7+8yb:*gLڡvk o|ēēm)!%zQapާ_%OhWjh0.oKrZr1EqeHR=-z 5Tqf60%ot*.g3ZN~v[FK ?dM%rgmKؼrE-5OF1AʪX0KY U<j`q?Ͱ^'4?_;Bgk686vC -e)t;r](˒A`GcwhXYP@}wARgM'СПf^0Dh3VRj%K~ /Kf72qվ$ޠŔ7zKt"7Zx! [k2Vh]TNnKGS!! .Zj_rusH 5r:GWo.Z!(6k-3\z,k~ #G06s &y5)]C" ": 'K|&\$L*Q+8 ^wbp6Ce }0|hYeW7azm_Mc=M/0|>]|e9L/hkD0;ASF9!F5 Ž L"~Nӛ ^>8i'zL[7\87['&sDSz~Ҟ)PĮ5t;Ӧ<Is9nr%Na>xu^)ɰ?q<NpЃV"Je><qx<U'Q%]< e3@S.;2je $t'73z'4p6e?LuVq1yܽS+d8磏gf@7>_@Bh-Flqa}{mMq+DG"tqd1{kH,0$?_p=:-28\h kPZ< RԲT&j[c`2=e g"ѣH,r9g 4 ujV^/ x@hӞE~i~8Ͼ"c]1_|իVmYk@Hbq$Ք,TK%D^c4=I}>UNw\{&Cl(un7Ç߼yÇNOO߽{ L*jC:JՑZ-ف > IИ#_4_~CM|~n]MWۦ4j*izhcF[,<= G# ,iY*Yl㰾uz9'}͛7׉|?s<x{0yoIdb 2ɩݫWAn \B<L?e .Tz"8ej*z^ݻn( uՁ?;=t@dpEoz SQ7bS@`-aQ˸TOFJ۷ *զJj+I[տL$%`_@ < .)=LCEzbMEEdwT߿~ߠ{oit|~Ӄ[T.tb dCϮHy8DK;ۍJܴ <4+fdj݇o~xarGoz=K:X*|%"Xl"",R4]{m[(kh( ײy^1X0= w;"݃Ite79C/bea/X1` m 7=T?siV!5$7PAMd)R\az=WyŦ)hã= ?®(,9rz`i-Kb7 P`a>( ϙyna-16㬦 (ba_M@($%ZƑ^M;_=21wull`^V@E&,/i>$:7=PEbr _y<!y(sZ%0^deYXOÏ_l% NJ97bjl!@zb8J_Y>@%9˵H@~ \hv97@R|_j@z9G TnPv Z Lg͍D¡؟$fhRZ`MOe CW\AA-ON|* B6(E!Kat> br"S"1b,p҃lh9;j`q7?wdT ~ߠQ@ J?  ?ϦgTUq?g*tpWvVvb +þ >yRW;՝^|W"vIuQq Ѿy>/Ge Bl1_JrD(mYVwbP?_j{1tM9U{0_]uV]H.ϭE?@|6 2"?h=,>}YjnA@1|Ji3Y`}[(tAbN%PW׶PYTO'UuNlUfcI@o\wXf nY8z(HϬ-[{VS3JF @t[bBNяna1x6wsf-Eg]$R\AV<ͥ2Q @=K?H$$^|VJP:[PN ub,%Zt]!|k33F 6gh禳 OD|C]yB8n&~cාS'6ɇs,T<|"ėـMIGx/<!v Õ[H=]D0#773s_h9kwڭboF#L)@y F;KԭDby1"FǞV;t}g0J㞓] ឡ~/5mZQCϗZXt/7MLn "*;w(Ɨw#@J^T՞Nabh-2" v Ƃ-L/͊h|>vz:]O(Dǐׂ%P \PuIsډWNsB'‘h _W;D/2ADŝ]: R?4{ ^Aw> &  _ ٩ u?R0;x";sG]ơq¸2;Lx'i޾7&Kg Kz Zs73q. :>7ŭ*ur˯'VOZ( ^ @.ˎi7b|,x ]CƩ%>RU$q3Z?p7@@`!Kib/VG?lW/{mroXڍO'&l@ģtk,vbl|=C' У/=};^mzTKa[ۻPd4~2v7cR%FukzlEϵmك1<n :;=ձ,iӔj;G&PZ?@x4 7[İR48= >* SG]VģztGvb< l| ##NMNL}ԳҪ<<LJg7gĢw`5:/Ng_C@6/v{MXDxO wBA@c?ov8H\t\4ݳv(e)20:a|gNꃥN99懸y@wcA/4'IZ$)]T:ۇۻ{@=/|$;w*T^giiXh"2Mr7L< ɩۖ'#zʧۧ-eH fO'"U<BؿyK x~|H 覦nLEsTK\ ww%+<~uK/%vB : ;/Ҽۯ(`6{'8>MqƧ=Qez76+'ehHq=r.mdYwI(@mӄJ`UW+bHV3 M `Л7sʏ<$y{O]ח1ϭwrߞ>;葳h$l淧gU~2>3<anE[{n'FUX8&}3<Jo﫫ѣ,g'ӜKNrxSуiG32w>䧅޿$z'`'3KExD[{#|ECǏ7<;A4ƞǧ_?׸Uzc|P @UL =jx-ʯPioGgw_5Q3-j'<1c_~D'1*5$x$v`Fnqo-*^X{7xߏ4 0? Oblž%zWTV~JG}\, _z >֏9'A$? ߞ0x:8a9n{j"g5wb~~a1k3#ڃQGG Q,cC;>>HƇI=+<Qw^z.~7ޘ!U">,|~'Ə{o-JK7ʀy9n/jGzL)w5DOxH-G>D|ci't| =$<|FNI }{V4r0wp@<\]+鍏;'L~TxrT/ iVzpbGG(H=4v[:" ^nhoYM渊XXc)y=Hoz0lhS)#b40)Ӆ XZp>i[#cVξ~(?ׅNS'K5u\ S{ȦĢ~QW Ozx|Rzр%4wm _ ~T0z`^v)@xoOO^ Fmu\zs۸ Ge08#o->$x2>P|=&=<4+UAX°'y-vVï^'oOs[Ҥz`nOnC%ܕ\C*=wb_踀W,]bۍd Rxz8*>[zJe=,Y~fݠւq,C<F}|>k4y疰di!7#'Xښ=5 'D8;qzC)KL޶K`f];. p~%)W*>uZ襬` r\8xMR-\f x;ju=xT#y9+ˢE{Y0Rfayn{ћ2x&(^7ҷ;?nׄ"Gzʳj/az?<_zzEl ?f3A0zI^{4g+9׋^:Ed[W8!Xso~VaԬT >\6+/C^[ߦr+U,uA| =V|~X=0[k>B 81Q=s!^+11PHb< 2h#JN35:}>J=ozX}VbQ!2LmSi -QK⋔z.zۇvCg<klɚTj>}yTw G(fQ+p+/[c//8lj5_VGՕymqY$Vz]mW3zbf E7&hO[w E U 7R"HZ ^ #5{Ky?W%}"b m0Ճ K[cی=0o*T|2w^b'm+-0"L{N[gjm,KuAO]Oqܳhog#kQx.=Jit~Q4$1rk"Tz7Y:'+"Ҿy[w&xbMmÁ[/lYA?]P?FZXi\CFo^J:JozzG-lc|_Z%0|,F9@I~Lƭ{\~|BdHMl+rG6 Q]g$ӣGO2kƖGgmᅢvL FY10#HD~Zs+$/q/!;݁i~O]c5[xQAz<e#&~Af>S#!9<Q zi2ΫVkt;0 7[op~AУ{%QY}r 8Nh#9Mm e5@zNggium_JyOG8@N?A!k-NVVNki mz'XGi$|F~AMaxO._q ?{0p>㇇SZk?k#Et": |)=7~[nF'M}VbTX)jdDžgdjMwO^6݁lqFh,c&9hޑUx& !kܛX]u}͖ w qڴn(8ވ5z^V1I$;`=ۑDɎd zsr+UZ|~:n1͊&8J)q͉4vh9Kvys(M T%S$tĺFM<xk9dq$Ǘ_#08RMXJ(B;&YЉZg7= A1ߦ待*l}S>/ i; Qvtv/~/ӻsҳj<iY HaG>/p2<}Y;O_'^)#<k;BfBuvd *O_?0)$9̴Qq$Bؙ~Y6 s#ajH1~fӸ7}DNѸ)tBصI? 3 [12;m )"ui# +ml3I&cE i XԾ`>=.|Mۿ?EԀr$]l괭0˫]Qqk6V [W9^|B?ߚ'ݵv)=`Y{{:Vr6֑LD ߫)KbQ.ucSi[ OkU[@-Xd;Ns@w墲lDۺoj;]uٟ{MFʱtN3_l-qN%N8[Q?U gj ([onHt/Wӱ `Ydԃhz&/OE(Ґl4V7~8+MwƳQm"pj $0oM]8UĎz< ڃiE0M$=hd7IyyH1$1gt4W w}z7$ƮsspVti2y"򐵬Lɬ[ y;<72 !0 :4h5(u\Wy#5%ws` IcFsWB2b՝10C.53.?]B0&ĆqT-HkI,^Sm9DCnr1 !CĘ1M 7[.- ˢL rU7@FFo #!!0Ĉ4zI e\ؠHADŤ =R# bizw`J xÐ#R<-Hl1+-%eK a~<\LFɃ|"|PlEJIENDB`
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [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
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def text_justification(word: str, max_width: int) -> list: """ Will format the string such that each line has exactly (max_width) characters and is fully (left and right) justified, and return the list of justified text. example 1: string = "This is an example of text justification." max_width = 16 output = ['This is an', 'example of text', 'justification. '] >>> text_justification("This is an example of text justification.", 16) ['This is an', 'example of text', 'justification. '] example 2: string = "Two roads diverged in a yellow wood" max_width = 16 output = ['Two roads', 'diverged in a', 'yellow wood '] >>> text_justification("Two roads diverged in a yellow wood", 16) ['Two roads', 'diverged in a', 'yellow wood '] Time complexity: O(m*n) Space complexity: O(m*n) """ # Converting string into list of strings split by a space words = word.split() def justify(line: list, width: int, max_width: int) -> str: overall_spaces_count = max_width - width words_count = len(line) if len(line) == 1: # if there is only word in line # just insert overall_spaces_count for the remainder of line return line[0] + " " * overall_spaces_count else: spaces_to_insert_between_words = words_count - 1 # num_spaces_between_words_list[i] : tells you to insert # num_spaces_between_words_list[i] spaces # after word on line[i] num_spaces_between_words_list = spaces_to_insert_between_words * [ overall_spaces_count // spaces_to_insert_between_words ] spaces_count_in_locations = ( overall_spaces_count % spaces_to_insert_between_words ) # distribute spaces via round robin to the left words for i in range(spaces_count_in_locations): num_spaces_between_words_list[i] += 1 aligned_words_list = [] for i in range(spaces_to_insert_between_words): # add the word aligned_words_list.append(line[i]) # add the spaces to insert aligned_words_list.append(num_spaces_between_words_list[i] * " ") # just add the last word to the sentence aligned_words_list.append(line[-1]) # join the aligned words list to form a justified line return "".join(aligned_words_list) answer = [] line: list[str] = [] width = 0 for word in words: if width + len(word) + len(line) <= max_width: # keep adding words until we can fill out max_width # width = sum of length of all words (without overall_spaces_count) # len(word) = length of current word # len(line) = number of overall_spaces_count to insert between words line.append(word) width += len(word) else: # justify the line and add it to result answer.append(justify(line, width, max_width)) # reset new line and new width line, width = [word], len(word) remaining_spaces = max_width - width - len(line) answer.append(" ".join(line) + (remaining_spaces + 1) * " ") return answer if __name__ == "__main__": from doctest import testmod testmod()
def text_justification(word: str, max_width: int) -> list: """ Will format the string such that each line has exactly (max_width) characters and is fully (left and right) justified, and return the list of justified text. example 1: string = "This is an example of text justification." max_width = 16 output = ['This is an', 'example of text', 'justification. '] >>> text_justification("This is an example of text justification.", 16) ['This is an', 'example of text', 'justification. '] example 2: string = "Two roads diverged in a yellow wood" max_width = 16 output = ['Two roads', 'diverged in a', 'yellow wood '] >>> text_justification("Two roads diverged in a yellow wood", 16) ['Two roads', 'diverged in a', 'yellow wood '] Time complexity: O(m*n) Space complexity: O(m*n) """ # Converting string into list of strings split by a space words = word.split() def justify(line: list, width: int, max_width: int) -> str: overall_spaces_count = max_width - width words_count = len(line) if len(line) == 1: # if there is only word in line # just insert overall_spaces_count for the remainder of line return line[0] + " " * overall_spaces_count else: spaces_to_insert_between_words = words_count - 1 # num_spaces_between_words_list[i] : tells you to insert # num_spaces_between_words_list[i] spaces # after word on line[i] num_spaces_between_words_list = spaces_to_insert_between_words * [ overall_spaces_count // spaces_to_insert_between_words ] spaces_count_in_locations = ( overall_spaces_count % spaces_to_insert_between_words ) # distribute spaces via round robin to the left words for i in range(spaces_count_in_locations): num_spaces_between_words_list[i] += 1 aligned_words_list = [] for i in range(spaces_to_insert_between_words): # add the word aligned_words_list.append(line[i]) # add the spaces to insert aligned_words_list.append(num_spaces_between_words_list[i] * " ") # just add the last word to the sentence aligned_words_list.append(line[-1]) # join the aligned words list to form a justified line return "".join(aligned_words_list) answer = [] line: list[str] = [] width = 0 for word in words: if width + len(word) + len(line) <= max_width: # keep adding words until we can fill out max_width # width = sum of length of all words (without overall_spaces_count) # len(word) = length of current word # len(line) = number of overall_spaces_count to insert between words line.append(word) width += len(word) else: # justify the line and add it to result answer.append(justify(line, width, max_width)) # reset new line and new width line, width = [word], len(word) remaining_spaces = max_width - width - len(line) answer.append(" ".join(line) + (remaining_spaces + 1) * " ") return answer if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
# Source : https://computersciencewiki.org/index.php/Max-pooling_/_Pooling # Importing the libraries import numpy as np from PIL import Image # Maxpooling Function def maxpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: """ This function is used to perform maxpooling on the input array of 2D matrix(image) Args: arr: numpy array size: size of pooling matrix stride: the number of pixels shifts over the input matrix Returns: numpy array of maxpooled matrix Sample Input Output: >>> maxpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2) array([[ 6., 8.], [14., 16.]]) >>> maxpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1) array([[241., 180.], [241., 157.]]) """ arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") i = 0 j = 0 mat_i = 0 mat_j = 0 # compute the shape of the output matrix maxpool_shape = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape updated_arr = np.zeros((maxpool_shape, maxpool_shape)) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix updated_arr[mat_i][mat_j] = np.max(arr[i : i + size, j : j + size]) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 j = 0 mat_j = 0 return updated_arr # Averagepooling Function def avgpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: """ This function is used to perform avgpooling on the input array of 2D matrix(image) Args: arr: numpy array size: size of pooling matrix stride: the number of pixels shifts over the input matrix Returns: numpy array of avgpooled matrix Sample Input Output: >>> avgpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2) array([[ 3., 5.], [11., 13.]]) >>> avgpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1) array([[161., 102.], [114., 69.]]) """ arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") i = 0 j = 0 mat_i = 0 mat_j = 0 # compute the shape of the output matrix avgpool_shape = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape updated_arr = np.zeros((avgpool_shape, avgpool_shape)) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix updated_arr[mat_i][mat_j] = int(np.average(arr[i : i + size, j : j + size])) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 j = 0 mat_j = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="avgpooling", verbose=True) # Loading the image image = Image.open("path_to_image") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
# Source : https://computersciencewiki.org/index.php/Max-pooling_/_Pooling # Importing the libraries import numpy as np from PIL import Image # Maxpooling Function def maxpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: """ This function is used to perform maxpooling on the input array of 2D matrix(image) Args: arr: numpy array size: size of pooling matrix stride: the number of pixels shifts over the input matrix Returns: numpy array of maxpooled matrix Sample Input Output: >>> maxpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2) array([[ 6., 8.], [14., 16.]]) >>> maxpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1) array([[241., 180.], [241., 157.]]) """ arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") i = 0 j = 0 mat_i = 0 mat_j = 0 # compute the shape of the output matrix maxpool_shape = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape updated_arr = np.zeros((maxpool_shape, maxpool_shape)) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix updated_arr[mat_i][mat_j] = np.max(arr[i : i + size, j : j + size]) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 j = 0 mat_j = 0 return updated_arr # Averagepooling Function def avgpooling(arr: np.ndarray, size: int, stride: int) -> np.ndarray: """ This function is used to perform avgpooling on the input array of 2D matrix(image) Args: arr: numpy array size: size of pooling matrix stride: the number of pixels shifts over the input matrix Returns: numpy array of avgpooled matrix Sample Input Output: >>> avgpooling([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 2, 2) array([[ 3., 5.], [11., 13.]]) >>> avgpooling([[147, 180, 122],[241, 76, 32],[126, 13, 157]], 2, 1) array([[161., 102.], [114., 69.]]) """ arr = np.array(arr) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") i = 0 j = 0 mat_i = 0 mat_j = 0 # compute the shape of the output matrix avgpool_shape = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape updated_arr = np.zeros((avgpool_shape, avgpool_shape)) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix updated_arr[mat_i][mat_j] = int(np.average(arr[i : i + size, j : j + size])) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 j = 0 mat_j = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name="avgpooling", verbose=True) # Loading the image image = Image.open("path_to_image") # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ even_fibs = [] a, b = 0, 1 while b <= n: if b % 2 == 0: even_fibs.append(b) a, b = b, a + b return sum(even_fibs) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 2: https://projecteuler.net/problem=2 Even Fibonacci Numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. References: - https://en.wikipedia.org/wiki/Fibonacci_number """ def solution(n: int = 4000000) -> int: """ Returns the sum of all even fibonacci sequence elements that are lower or equal to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ even_fibs = [] a, b = 0, 1 while b <= n: if b % 2 == 0: even_fibs.append(b) a, b = b, a + b return sum(even_fibs) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
import numpy as np from PIL import Image def rgb2gray(rgb: np.array) -> np.array: """ Return gray image from rgb image >>> rgb2gray(np.array([[[127, 255, 0]]])) array([[187.6453]]) >>> rgb2gray(np.array([[[0, 0, 0]]])) array([[0.]]) >>> rgb2gray(np.array([[[2, 4, 1]]])) array([[3.0598]]) >>> rgb2gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]])) array([[159.0524, 90.0635, 117.6989]]) """ r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray2binary(gray: np.array) -> np.array: """ Return binary image from gray image >>> gray2binary(np.array([[127, 255, 0]])) array([[False, True, False]]) >>> gray2binary(np.array([[0]])) array([[False]]) >>> gray2binary(np.array([[26.2409, 4.9315, 1.4729]])) array([[False, False, False]]) >>> gray2binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]])) array([[False, True, False], [False, True, False], [False, True, False]]) """ return (gray > 127) & (gray <= 255) def erosion(image: np.array, kernel: np.array) -> np.array: """ Return eroded image >>> erosion(np.array([[True, True, False]]), np.array([[0, 1, 0]])) array([[False, False, False]]) >>> erosion(np.array([[True, False, False]]), np.array([[1, 1, 0]])) array([[False, False, False]]) """ output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image # Iterate over image & apply kernel for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation == 5) return output # kernel to be applied structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) if __name__ == "__main__": # read original image image = np.array(Image.open(r"..\image_data\lena.jpg")) # Apply erosion operation to a binary image output = erosion(gray2binary(rgb2gray(image)), structuring_element) # Save the output image pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_erosion.png")
import numpy as np from PIL import Image def rgb2gray(rgb: np.array) -> np.array: """ Return gray image from rgb image >>> rgb2gray(np.array([[[127, 255, 0]]])) array([[187.6453]]) >>> rgb2gray(np.array([[[0, 0, 0]]])) array([[0.]]) >>> rgb2gray(np.array([[[2, 4, 1]]])) array([[3.0598]]) >>> rgb2gray(np.array([[[26, 255, 14], [5, 147, 20], [1, 200, 0]]])) array([[159.0524, 90.0635, 117.6989]]) """ r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def gray2binary(gray: np.array) -> np.array: """ Return binary image from gray image >>> gray2binary(np.array([[127, 255, 0]])) array([[False, True, False]]) >>> gray2binary(np.array([[0]])) array([[False]]) >>> gray2binary(np.array([[26.2409, 4.9315, 1.4729]])) array([[False, False, False]]) >>> gray2binary(np.array([[26, 255, 14], [5, 147, 20], [1, 200, 0]])) array([[False, True, False], [False, True, False], [False, True, False]]) """ return (gray > 127) & (gray <= 255) def erosion(image: np.array, kernel: np.array) -> np.array: """ Return eroded image >>> erosion(np.array([[True, True, False]]), np.array([[0, 1, 0]])) array([[False, False, False]]) >>> erosion(np.array([[True, False, False]]), np.array([[1, 1, 0]])) array([[False, False, False]]) """ output = np.zeros_like(image) image_padded = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image image_padded[kernel.shape[0] - 2 : -1 :, kernel.shape[1] - 2 : -1 :] = image # Iterate over image & apply kernel for x in range(image.shape[1]): for y in range(image.shape[0]): summation = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() output[y, x] = int(summation == 5) return output # kernel to be applied structuring_element = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) if __name__ == "__main__": # read original image image = np.array(Image.open(r"..\image_data\lena.jpg")) # Apply erosion operation to a binary image output = erosion(gray2binary(rgb2gray(image)), structuring_element) # Save the output image pil_img = Image.fromarray(output).convert("RGB") pil_img.save("result_erosion.png")
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
def calculate_pi(limit: int) -> str: """ https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80 Leibniz Formula for Pi The Leibniz formula is the special case arctan 1 = 1/4 Pi . Leibniz's formula converges extremely slowly: it exhibits sublinear convergence. Convergence (https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80#Convergence) We cannot try to prove against an interrupted, uncompleted generation. https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80#Unusual_behaviour The errors can in fact be predicted; but those calculations also approach infinity for accuracy. Our output will always be a string since we can defintely store all digits in there. For simplicity' sake, let's just compare against known values and since our outpit is a string, we need to convert to float. >>> import math >>> float(calculate_pi(15)) == math.pi True Since we cannot predict errors or interrupt any infinite alternating series generation since they approach infinity, or interrupt any alternating series, we are going to need math.isclose() >>> math.isclose(float(calculate_pi(50)), math.pi) True >>> math.isclose(float(calculate_pi(100)), math.pi) True Since math.pi-constant contains only 16 digits, here some test with preknown values: >>> calculate_pi(50) '3.14159265358979323846264338327950288419716939937510' >>> calculate_pi(80) '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899' To apply the Leibniz formula for calculating pi, the variables q, r, t, k, n, and l are used for the iteration process. """ q = 1 r = 0 t = 1 k = 1 n = 3 l = 3 decimal = limit counter = 0 result = "" """ We will avoid using yield since we otherwise get a Generator-Object, which we can't just compare against anything. We would have to make a list out of it after the generation, so we will just stick to plain return logic: """ while counter != decimal + 1: if 4 * q + r - t < n * t: result += str(n) if counter == 0: result += "." if decimal == counter: break counter += 1 nr = 10 * (r - n * t) n = ((10 * (3 * q + r)) // t) - 10 * n q *= 10 r = nr else: nr = (2 * q + r) * l nn = (q * (7 * k) + 2 + (r * l)) // (t * l) q *= k t *= l l += 2 k += 1 n = nn r = nr return result def main() -> None: print(f"{calculate_pi(50) = }") import doctest doctest.testmod() if __name__ == "__main__": main()
def calculate_pi(limit: int) -> str: """ https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80 Leibniz Formula for Pi The Leibniz formula is the special case arctan 1 = 1/4 Pi . Leibniz's formula converges extremely slowly: it exhibits sublinear convergence. Convergence (https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80#Convergence) We cannot try to prove against an interrupted, uncompleted generation. https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80#Unusual_behaviour The errors can in fact be predicted; but those calculations also approach infinity for accuracy. Our output will always be a string since we can defintely store all digits in there. For simplicity' sake, let's just compare against known values and since our outpit is a string, we need to convert to float. >>> import math >>> float(calculate_pi(15)) == math.pi True Since we cannot predict errors or interrupt any infinite alternating series generation since they approach infinity, or interrupt any alternating series, we are going to need math.isclose() >>> math.isclose(float(calculate_pi(50)), math.pi) True >>> math.isclose(float(calculate_pi(100)), math.pi) True Since math.pi-constant contains only 16 digits, here some test with preknown values: >>> calculate_pi(50) '3.14159265358979323846264338327950288419716939937510' >>> calculate_pi(80) '3.14159265358979323846264338327950288419716939937510582097494459230781640628620899' To apply the Leibniz formula for calculating pi, the variables q, r, t, k, n, and l are used for the iteration process. """ q = 1 r = 0 t = 1 k = 1 n = 3 l = 3 decimal = limit counter = 0 result = "" """ We will avoid using yield since we otherwise get a Generator-Object, which we can't just compare against anything. We would have to make a list out of it after the generation, so we will just stick to plain return logic: """ while counter != decimal + 1: if 4 * q + r - t < n * t: result += str(n) if counter == 0: result += "." if decimal == counter: break counter += 1 nr = 10 * (r - n * t) n = ((10 * (3 * q + r)) // t) - 10 * n q *= 10 r = nr else: nr = (2 * q + r) * l nn = (q * (7 * k) + 2 + (r * l)) // (t * l) q *= k t *= l l += 2 k += 1 n = nn r = nr return result def main() -> None: print(f"{calculate_pi(50) = }") import doctest doctest.testmod() if __name__ == "__main__": main()
-1
TheAlgorithms/Python
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [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
8,833
Clarify how to add issue numbers in PR template and CONTRIBUTING.md
### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
tianyizheng02
"2023-06-23T07:07:39Z"
"2023-06-23T13:56:59Z"
331585f3f866e210e23d11700b09a8770a1c2490
267a8b72f97762383e7c313ed20df859115e2815
Clarify how to add issue numbers in PR template and CONTRIBUTING.md. ### Describe your change: Fixes #8735 Per the discussion in #8735, I've updated the last checkbox in the PR template to specify that issue numbers should go in the _description_ of the PR. There's also a link to the [GitHub docs page on the topic](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) for those contributors who care to look into it further. I've also elaborated on the paragraph discussing issue numbers in the contributing guidelines by providing an example of adding an issue number. Hopefully that'll be enough for most contributors (who actually read the guidelines) to know what to do. * [ ] Add an algorithm? * [ ] Fix a bug or typo in an existing algorithm? * [x] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
from __future__ import annotations import csv import requests from bs4 import BeautifulSoup def get_imdb_top_250_movies(url: str = "") -> dict[str, float]: url = url or "https://www.imdb.com/chart/top/?ref_=nv_mv_250" soup = BeautifulSoup(requests.get(url).text, "html.parser") titles = soup.find_all("td", attrs="titleColumn") ratings = soup.find_all("td", class_="ratingColumn imdbRating") return { title.a.text: float(rating.strong.text) for title, rating in zip(titles, ratings) } def write_movies(filename: str = "IMDb_Top_250_Movies.csv") -> None: movies = get_imdb_top_250_movies() with open(filename, "w", newline="") as out_file: writer = csv.writer(out_file) writer.writerow(["Movie title", "IMDb rating"]) for title, rating in movies.items(): writer.writerow([title, rating]) if __name__ == "__main__": write_movies()
from __future__ import annotations import csv import requests from bs4 import BeautifulSoup def get_imdb_top_250_movies(url: str = "") -> dict[str, float]: url = url or "https://www.imdb.com/chart/top/?ref_=nv_mv_250" soup = BeautifulSoup(requests.get(url).text, "html.parser") titles = soup.find_all("td", attrs="titleColumn") ratings = soup.find_all("td", class_="ratingColumn imdbRating") return { title.a.text: float(rating.strong.text) for title, rating in zip(titles, ratings) } def write_movies(filename: str = "IMDb_Top_250_Movies.csv") -> None: movies = get_imdb_top_250_movies() with open(filename, "w", newline="") as out_file: writer = csv.writer(out_file) writer.writerow(["Movie title", "IMDb rating"]) for title, rating in movies.items(): writer.writerow([title, rating]) if __name__ == "__main__": write_movies()
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: check-executables-have-shebangs - id: check-toml - id: check-yaml - id: end-of-file-fixer types: [python] - id: trailing-whitespace - id: requirements-txt-fixer - repo: https://github.com/MarcoGorelli/auto-walrus rev: v0.2.2 hooks: - id: auto-walrus - repo: https://github.com/charliermarsh/ruff-pre-commit rev: v0.0.272 hooks: - id: ruff - repo: https://github.com/psf/black rev: 23.3.0 hooks: - id: black - repo: https://github.com/codespell-project/codespell rev: v2.2.5 hooks: - id: codespell additional_dependencies: - tomli - repo: https://github.com/tox-dev/pyproject-fmt rev: "0.12.0" hooks: - id: pyproject-fmt - repo: local hooks: - id: validate-filenames name: Validate filenames entry: ./scripts/validate_filenames.py language: script pass_filenames: false - repo: https://github.com/abravalheri/validate-pyproject rev: v0.13 hooks: - id: validate-pyproject - repo: https://github.com/pre-commit/mirrors-mypy rev: v1.3.0 hooks: - id: mypy args: - --ignore-missing-imports - --install-types # See mirrors-mypy README.md - --non-interactive additional_dependencies: [types-requests]
repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: check-executables-have-shebangs - id: check-toml - id: check-yaml - id: end-of-file-fixer types: [python] - id: trailing-whitespace - id: requirements-txt-fixer - repo: https://github.com/MarcoGorelli/auto-walrus rev: v0.2.2 hooks: - id: auto-walrus - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.0.274 hooks: - id: ruff - repo: https://github.com/psf/black rev: 23.3.0 hooks: - id: black - repo: https://github.com/codespell-project/codespell rev: v2.2.5 hooks: - id: codespell additional_dependencies: - tomli - repo: https://github.com/tox-dev/pyproject-fmt rev: "0.12.0" hooks: - id: pyproject-fmt - repo: local hooks: - id: validate-filenames name: Validate filenames entry: ./scripts/validate_filenames.py language: script pass_filenames: false - repo: https://github.com/abravalheri/validate-pyproject rev: v0.13 hooks: - id: validate-pyproject - repo: https://github.com/pre-commit/mirrors-mypy rev: v1.3.0 hooks: - id: mypy args: - --ignore-missing-imports - --install-types # See mirrors-mypy README.md - --non-interactive additional_dependencies: [types-requests]
1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
""" Implementation of double ended queue. """ from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass from typing import Any class Deque: """ Deque data structure. Operations ---------- append(val: Any) -> None appendleft(val: Any) -> None extend(iterable: Iterable) -> None extendleft(iterable: Iterable) -> None pop() -> Any popleft() -> Any Observers --------- is_empty() -> bool Attributes ---------- _front: _Node front of the deque a.k.a. the first element _back: _Node back of the element a.k.a. the last element _len: int the number of nodes """ __slots__ = ["_front", "_back", "_len"] @dataclass class _Node: """ Representation of a node. Contains a value and a pointer to the next node as well as to the previous one. """ val: Any = None next_node: Deque._Node | None = None prev_node: Deque._Node | None = None class _Iterator: """ Helper class for iteration. Will be used to implement iteration. Attributes ---------- _cur: _Node the current node of the iteration. """ __slots__ = ["_cur"] def __init__(self, cur: Deque._Node | None) -> None: self._cur = cur def __iter__(self) -> Deque._Iterator: """ >>> our_deque = Deque([1, 2, 3]) >>> iterator = iter(our_deque) """ return self def __next__(self) -> Any: """ >>> our_deque = Deque([1, 2, 3]) >>> iterator = iter(our_deque) >>> next(iterator) 1 >>> next(iterator) 2 >>> next(iterator) 3 """ if self._cur is None: # finished iterating raise StopIteration val = self._cur.val self._cur = self._cur.next_node return val def __init__(self, iterable: Iterable[Any] | None = None) -> None: self._front: Any = None self._back: Any = None self._len: int = 0 if iterable is not None: # append every value to the deque for val in iterable: self.append(val) def append(self, val: Any) -> None: """ Adds val to the end of the deque. Time complexity: O(1) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.append(4) >>> our_deque_1 [1, 2, 3, 4] >>> our_deque_2 = Deque('ab') >>> our_deque_2.append('c') >>> our_deque_2 ['a', 'b', 'c'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.append(4) >>> deque_collections_1 deque([1, 2, 3, 4]) >>> deque_collections_2 = deque('ab') >>> deque_collections_2.append('c') >>> deque_collections_2 deque(['a', 'b', 'c']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes self._back.next_node = node node.prev_node = self._back self._back = node # assign new back to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def appendleft(self, val: Any) -> None: """ Adds val to the beginning of the deque. Time complexity: O(1) >>> our_deque_1 = Deque([2, 3]) >>> our_deque_1.appendleft(1) >>> our_deque_1 [1, 2, 3] >>> our_deque_2 = Deque('bc') >>> our_deque_2.appendleft('a') >>> our_deque_2 ['a', 'b', 'c'] >>> from collections import deque >>> deque_collections_1 = deque([2, 3]) >>> deque_collections_1.appendleft(1) >>> deque_collections_1 deque([1, 2, 3]) >>> deque_collections_2 = deque('bc') >>> deque_collections_2.appendleft('a') >>> deque_collections_2 deque(['a', 'b', 'c']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes node.next_node = self._front self._front.prev_node = node self._front = node # assign new front to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def extend(self, iterable: Iterable[Any]) -> None: """ Appends every value of iterable to the end of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extend([4, 5]) >>> our_deque_1 [1, 2, 3, 4, 5] >>> our_deque_2 = Deque('ab') >>> our_deque_2.extend('cd') >>> our_deque_2 ['a', 'b', 'c', 'd'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.extend([4, 5]) >>> deque_collections_1 deque([1, 2, 3, 4, 5]) >>> deque_collections_2 = deque('ab') >>> deque_collections_2.extend('cd') >>> deque_collections_2 deque(['a', 'b', 'c', 'd']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ for val in iterable: self.append(val) def extendleft(self, iterable: Iterable[Any]) -> None: """ Appends every value of iterable to the beginning of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extendleft([0, -1]) >>> our_deque_1 [-1, 0, 1, 2, 3] >>> our_deque_2 = Deque('cd') >>> our_deque_2.extendleft('ba') >>> our_deque_2 ['a', 'b', 'c', 'd'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.extendleft([0, -1]) >>> deque_collections_1 deque([-1, 0, 1, 2, 3]) >>> deque_collections_2 = deque('cd') >>> deque_collections_2.extendleft('ba') >>> deque_collections_2 deque(['a', 'b', 'c', 'd']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ for val in iterable: self.appendleft(val) def pop(self) -> Any: """ Removes the last element of the deque and returns it. Time complexity: O(1) @returns topop.val: the value of the node to pop. >>> our_deque = Deque([1, 2, 3, 15182]) >>> our_popped = our_deque.pop() >>> our_popped 15182 >>> our_deque [1, 2, 3] >>> from collections import deque >>> deque_collections = deque([1, 2, 3, 15182]) >>> collections_popped = deque_collections.pop() >>> collections_popped 15182 >>> deque_collections deque([1, 2, 3]) >>> list(our_deque) == list(deque_collections) True >>> our_popped == collections_popped True """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._back self._back = self._back.prev_node # set new back # drop the last node - python will deallocate memory automatically self._back.next_node = None self._len -= 1 return topop.val def popleft(self) -> Any: """ Removes the first element of the deque and returns it. Time complexity: O(1) @returns topop.val: the value of the node to pop. >>> our_deque = Deque([15182, 1, 2, 3]) >>> our_popped = our_deque.popleft() >>> our_popped 15182 >>> our_deque [1, 2, 3] >>> from collections import deque >>> deque_collections = deque([15182, 1, 2, 3]) >>> collections_popped = deque_collections.popleft() >>> collections_popped 15182 >>> deque_collections deque([1, 2, 3]) >>> list(our_deque) == list(deque_collections) True >>> our_popped == collections_popped True """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._front self._front = self._front.next_node # set new front and drop the first node self._front.prev_node = None self._len -= 1 return topop.val def is_empty(self) -> bool: """ Checks if the deque is empty. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> our_deque.is_empty() False >>> our_empty_deque = Deque() >>> our_empty_deque.is_empty() True >>> from collections import deque >>> empty_deque_collections = deque() >>> list(our_empty_deque) == list(empty_deque_collections) True """ return self._front is None def __len__(self) -> int: """ Implements len() function. Returns the length of the deque. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> len(our_deque) 3 >>> our_empty_deque = Deque() >>> len(our_empty_deque) 0 >>> from collections import deque >>> deque_collections = deque([1, 2, 3]) >>> len(deque_collections) 3 >>> empty_deque_collections = deque() >>> len(empty_deque_collections) 0 >>> len(our_empty_deque) == len(empty_deque_collections) True """ return self._len def __eq__(self, other: object) -> bool: """ Implements "==" operator. Returns if *self* is equal to *other*. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_2 = Deque([1, 2, 3]) >>> our_deque_1 == our_deque_2 True >>> our_deque_3 = Deque([1, 2]) >>> our_deque_1 == our_deque_3 False >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_2 = deque([1, 2, 3]) >>> deque_collections_1 == deque_collections_2 True >>> deque_collections_3 = deque([1, 2]) >>> deque_collections_1 == deque_collections_3 False >>> (our_deque_1 == our_deque_2) == (deque_collections_1 == deque_collections_2) True >>> (our_deque_1 == our_deque_3) == (deque_collections_1 == deque_collections_3) True """ if not isinstance(other, Deque): return NotImplemented me = self._front oth = other._front # if the length of the dequeues are not the same, they are not equal if len(self) != len(other): return False while me is not None and oth is not None: # compare every value if me.val != oth.val: return False me = me.next_node oth = oth.next_node return True def __iter__(self) -> Deque._Iterator: """ Implements iteration. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> for v in our_deque: ... print(v) 1 2 3 >>> from collections import deque >>> deque_collections = deque([1, 2, 3]) >>> for v in deque_collections: ... print(v) 1 2 3 """ return Deque._Iterator(self._front) def __repr__(self) -> str: """ Implements representation of the deque. Represents it as a list, with its values between '[' and ']'. Time complexity: O(n) >>> our_deque = Deque([1, 2, 3]) >>> our_deque [1, 2, 3] """ values_list = [] aux = self._front while aux is not None: # append the values in a list to display values_list.append(aux.val) aux = aux.next_node return f"[{', '.join(repr(val) for val in values_list)}]" if __name__ == "__main__": import doctest doctest.testmod()
""" Implementation of double ended queue. """ from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass from typing import Any class Deque: """ Deque data structure. Operations ---------- append(val: Any) -> None appendleft(val: Any) -> None extend(iterable: Iterable) -> None extendleft(iterable: Iterable) -> None pop() -> Any popleft() -> Any Observers --------- is_empty() -> bool Attributes ---------- _front: _Node front of the deque a.k.a. the first element _back: _Node back of the element a.k.a. the last element _len: int the number of nodes """ __slots__ = ("_front", "_back", "_len") @dataclass class _Node: """ Representation of a node. Contains a value and a pointer to the next node as well as to the previous one. """ val: Any = None next_node: Deque._Node | None = None prev_node: Deque._Node | None = None class _Iterator: """ Helper class for iteration. Will be used to implement iteration. Attributes ---------- _cur: _Node the current node of the iteration. """ __slots__ = "_cur" def __init__(self, cur: Deque._Node | None) -> None: self._cur = cur def __iter__(self) -> Deque._Iterator: """ >>> our_deque = Deque([1, 2, 3]) >>> iterator = iter(our_deque) """ return self def __next__(self) -> Any: """ >>> our_deque = Deque([1, 2, 3]) >>> iterator = iter(our_deque) >>> next(iterator) 1 >>> next(iterator) 2 >>> next(iterator) 3 """ if self._cur is None: # finished iterating raise StopIteration val = self._cur.val self._cur = self._cur.next_node return val def __init__(self, iterable: Iterable[Any] | None = None) -> None: self._front: Any = None self._back: Any = None self._len: int = 0 if iterable is not None: # append every value to the deque for val in iterable: self.append(val) def append(self, val: Any) -> None: """ Adds val to the end of the deque. Time complexity: O(1) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.append(4) >>> our_deque_1 [1, 2, 3, 4] >>> our_deque_2 = Deque('ab') >>> our_deque_2.append('c') >>> our_deque_2 ['a', 'b', 'c'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.append(4) >>> deque_collections_1 deque([1, 2, 3, 4]) >>> deque_collections_2 = deque('ab') >>> deque_collections_2.append('c') >>> deque_collections_2 deque(['a', 'b', 'c']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes self._back.next_node = node node.prev_node = self._back self._back = node # assign new back to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def appendleft(self, val: Any) -> None: """ Adds val to the beginning of the deque. Time complexity: O(1) >>> our_deque_1 = Deque([2, 3]) >>> our_deque_1.appendleft(1) >>> our_deque_1 [1, 2, 3] >>> our_deque_2 = Deque('bc') >>> our_deque_2.appendleft('a') >>> our_deque_2 ['a', 'b', 'c'] >>> from collections import deque >>> deque_collections_1 = deque([2, 3]) >>> deque_collections_1.appendleft(1) >>> deque_collections_1 deque([1, 2, 3]) >>> deque_collections_2 = deque('bc') >>> deque_collections_2.appendleft('a') >>> deque_collections_2 deque(['a', 'b', 'c']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ node = self._Node(val, None, None) if self.is_empty(): # front = back self._front = self._back = node self._len = 1 else: # connect nodes node.next_node = self._front self._front.prev_node = node self._front = node # assign new front to the new node self._len += 1 # make sure there were no errors assert not self.is_empty(), "Error on appending value." def extend(self, iterable: Iterable[Any]) -> None: """ Appends every value of iterable to the end of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extend([4, 5]) >>> our_deque_1 [1, 2, 3, 4, 5] >>> our_deque_2 = Deque('ab') >>> our_deque_2.extend('cd') >>> our_deque_2 ['a', 'b', 'c', 'd'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.extend([4, 5]) >>> deque_collections_1 deque([1, 2, 3, 4, 5]) >>> deque_collections_2 = deque('ab') >>> deque_collections_2.extend('cd') >>> deque_collections_2 deque(['a', 'b', 'c', 'd']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ for val in iterable: self.append(val) def extendleft(self, iterable: Iterable[Any]) -> None: """ Appends every value of iterable to the beginning of the deque. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_1.extendleft([0, -1]) >>> our_deque_1 [-1, 0, 1, 2, 3] >>> our_deque_2 = Deque('cd') >>> our_deque_2.extendleft('ba') >>> our_deque_2 ['a', 'b', 'c', 'd'] >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_1.extendleft([0, -1]) >>> deque_collections_1 deque([-1, 0, 1, 2, 3]) >>> deque_collections_2 = deque('cd') >>> deque_collections_2.extendleft('ba') >>> deque_collections_2 deque(['a', 'b', 'c', 'd']) >>> list(our_deque_1) == list(deque_collections_1) True >>> list(our_deque_2) == list(deque_collections_2) True """ for val in iterable: self.appendleft(val) def pop(self) -> Any: """ Removes the last element of the deque and returns it. Time complexity: O(1) @returns topop.val: the value of the node to pop. >>> our_deque = Deque([1, 2, 3, 15182]) >>> our_popped = our_deque.pop() >>> our_popped 15182 >>> our_deque [1, 2, 3] >>> from collections import deque >>> deque_collections = deque([1, 2, 3, 15182]) >>> collections_popped = deque_collections.pop() >>> collections_popped 15182 >>> deque_collections deque([1, 2, 3]) >>> list(our_deque) == list(deque_collections) True >>> our_popped == collections_popped True """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._back self._back = self._back.prev_node # set new back # drop the last node - python will deallocate memory automatically self._back.next_node = None self._len -= 1 return topop.val def popleft(self) -> Any: """ Removes the first element of the deque and returns it. Time complexity: O(1) @returns topop.val: the value of the node to pop. >>> our_deque = Deque([15182, 1, 2, 3]) >>> our_popped = our_deque.popleft() >>> our_popped 15182 >>> our_deque [1, 2, 3] >>> from collections import deque >>> deque_collections = deque([15182, 1, 2, 3]) >>> collections_popped = deque_collections.popleft() >>> collections_popped 15182 >>> deque_collections deque([1, 2, 3]) >>> list(our_deque) == list(deque_collections) True >>> our_popped == collections_popped True """ # make sure the deque has elements to pop assert not self.is_empty(), "Deque is empty." topop = self._front self._front = self._front.next_node # set new front and drop the first node self._front.prev_node = None self._len -= 1 return topop.val def is_empty(self) -> bool: """ Checks if the deque is empty. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> our_deque.is_empty() False >>> our_empty_deque = Deque() >>> our_empty_deque.is_empty() True >>> from collections import deque >>> empty_deque_collections = deque() >>> list(our_empty_deque) == list(empty_deque_collections) True """ return self._front is None def __len__(self) -> int: """ Implements len() function. Returns the length of the deque. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> len(our_deque) 3 >>> our_empty_deque = Deque() >>> len(our_empty_deque) 0 >>> from collections import deque >>> deque_collections = deque([1, 2, 3]) >>> len(deque_collections) 3 >>> empty_deque_collections = deque() >>> len(empty_deque_collections) 0 >>> len(our_empty_deque) == len(empty_deque_collections) True """ return self._len def __eq__(self, other: object) -> bool: """ Implements "==" operator. Returns if *self* is equal to *other*. Time complexity: O(n) >>> our_deque_1 = Deque([1, 2, 3]) >>> our_deque_2 = Deque([1, 2, 3]) >>> our_deque_1 == our_deque_2 True >>> our_deque_3 = Deque([1, 2]) >>> our_deque_1 == our_deque_3 False >>> from collections import deque >>> deque_collections_1 = deque([1, 2, 3]) >>> deque_collections_2 = deque([1, 2, 3]) >>> deque_collections_1 == deque_collections_2 True >>> deque_collections_3 = deque([1, 2]) >>> deque_collections_1 == deque_collections_3 False >>> (our_deque_1 == our_deque_2) == (deque_collections_1 == deque_collections_2) True >>> (our_deque_1 == our_deque_3) == (deque_collections_1 == deque_collections_3) True """ if not isinstance(other, Deque): return NotImplemented me = self._front oth = other._front # if the length of the dequeues are not the same, they are not equal if len(self) != len(other): return False while me is not None and oth is not None: # compare every value if me.val != oth.val: return False me = me.next_node oth = oth.next_node return True def __iter__(self) -> Deque._Iterator: """ Implements iteration. Time complexity: O(1) >>> our_deque = Deque([1, 2, 3]) >>> for v in our_deque: ... print(v) 1 2 3 >>> from collections import deque >>> deque_collections = deque([1, 2, 3]) >>> for v in deque_collections: ... print(v) 1 2 3 """ return Deque._Iterator(self._front) def __repr__(self) -> str: """ Implements representation of the deque. Represents it as a list, with its values between '[' and ']'. Time complexity: O(n) >>> our_deque = Deque([1, 2, 3]) >>> our_deque [1, 2, 3] """ values_list = [] aux = self._front while aux is not None: # append the values in a list to display values_list.append(aux.val) aux = aux.next_node return f"[{', '.join(repr(val) for val in values_list)}]" if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
import unittest from timeit import timeit def least_common_multiple_slow(first_num: int, second_num: int) -> int: """ Find the least common multiple of two numbers. Learn more: https://en.wikipedia.org/wiki/Least_common_multiple >>> least_common_multiple_slow(5, 2) 10 >>> least_common_multiple_slow(12, 76) 228 """ max_num = first_num if first_num >= second_num else second_num common_mult = max_num while (common_mult % first_num > 0) or (common_mult % second_num > 0): common_mult += max_num return common_mult def greatest_common_divisor(a: int, b: int) -> int: """ Calculate Greatest Common Divisor (GCD). see greatest_common_divisor.py >>> greatest_common_divisor(24, 40) 8 >>> greatest_common_divisor(1, 1) 1 >>> greatest_common_divisor(1, 800) 1 >>> greatest_common_divisor(11, 37) 1 >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(16, 4) 4 """ return b if a == 0 else greatest_common_divisor(b % a, a) def least_common_multiple_fast(first_num: int, second_num: int) -> int: """ Find the least common multiple of two numbers. https://en.wikipedia.org/wiki/Least_common_multiple#Using_the_greatest_common_divisor >>> least_common_multiple_fast(5,2) 10 >>> least_common_multiple_fast(12,76) 228 """ return first_num // greatest_common_divisor(first_num, second_num) * second_num def benchmark(): setup = ( "from __main__ import least_common_multiple_slow, least_common_multiple_fast" ) print( "least_common_multiple_slow():", timeit("least_common_multiple_slow(1000, 999)", setup=setup), ) print( "least_common_multiple_fast():", timeit("least_common_multiple_fast(1000, 999)", setup=setup), ) class TestLeastCommonMultiple(unittest.TestCase): test_inputs = [ (10, 20), (13, 15), (4, 31), (10, 42), (43, 34), (5, 12), (12, 25), (10, 25), (6, 9), ] expected_results = [20, 195, 124, 210, 1462, 60, 300, 50, 18] def test_lcm_function(self): for i, (first_num, second_num) in enumerate(self.test_inputs): slow_result = least_common_multiple_slow(first_num, second_num) fast_result = least_common_multiple_fast(first_num, second_num) with self.subTest(i=i): self.assertEqual(slow_result, self.expected_results[i]) self.assertEqual(fast_result, self.expected_results[i]) if __name__ == "__main__": benchmark() unittest.main()
import unittest from timeit import timeit def least_common_multiple_slow(first_num: int, second_num: int) -> int: """ Find the least common multiple of two numbers. Learn more: https://en.wikipedia.org/wiki/Least_common_multiple >>> least_common_multiple_slow(5, 2) 10 >>> least_common_multiple_slow(12, 76) 228 """ max_num = first_num if first_num >= second_num else second_num common_mult = max_num while (common_mult % first_num > 0) or (common_mult % second_num > 0): common_mult += max_num return common_mult def greatest_common_divisor(a: int, b: int) -> int: """ Calculate Greatest Common Divisor (GCD). see greatest_common_divisor.py >>> greatest_common_divisor(24, 40) 8 >>> greatest_common_divisor(1, 1) 1 >>> greatest_common_divisor(1, 800) 1 >>> greatest_common_divisor(11, 37) 1 >>> greatest_common_divisor(3, 5) 1 >>> greatest_common_divisor(16, 4) 4 """ return b if a == 0 else greatest_common_divisor(b % a, a) def least_common_multiple_fast(first_num: int, second_num: int) -> int: """ Find the least common multiple of two numbers. https://en.wikipedia.org/wiki/Least_common_multiple#Using_the_greatest_common_divisor >>> least_common_multiple_fast(5,2) 10 >>> least_common_multiple_fast(12,76) 228 """ return first_num // greatest_common_divisor(first_num, second_num) * second_num def benchmark(): setup = ( "from __main__ import least_common_multiple_slow, least_common_multiple_fast" ) print( "least_common_multiple_slow():", timeit("least_common_multiple_slow(1000, 999)", setup=setup), ) print( "least_common_multiple_fast():", timeit("least_common_multiple_fast(1000, 999)", setup=setup), ) class TestLeastCommonMultiple(unittest.TestCase): test_inputs = ( (10, 20), (13, 15), (4, 31), (10, 42), (43, 34), (5, 12), (12, 25), (10, 25), (6, 9), ) expected_results = (20, 195, 124, 210, 1462, 60, 300, 50, 18) def test_lcm_function(self): for i, (first_num, second_num) in enumerate(self.test_inputs): slow_result = least_common_multiple_slow(first_num, second_num) fast_result = least_common_multiple_fast(first_num, second_num) with self.subTest(i=i): self.assertEqual(slow_result, self.expected_results[i]) self.assertEqual(fast_result, self.expected_results[i]) if __name__ == "__main__": benchmark() unittest.main()
1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
""" Problem: https://projecteuler.net/problem=54 In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way: High Card: Highest value card. One Pair: Two cards of the same value. Two Pairs: Two different pairs. Three of a Kind: Three cards of the same value. Straight: All cards are consecutive values. Flush: All cards of the same suit. Full House: Three of a kind and a pair. Four of a Kind: Four cards of the same value. Straight Flush: All cards are consecutive values of same suit. Royal Flush: Ten, Jack, Queen, King, Ace, in same suit. The cards are valued in the order: 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace. If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives. But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared; if the highest cards tie then the next highest cards are compared, and so on. The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1's cards and the last five are Player 2's cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player's hand is in no specific order, and in each hand there is a clear winner. How many hands does Player 1 win? Resources used: https://en.wikipedia.org/wiki/Texas_hold_%27em https://en.wikipedia.org/wiki/List_of_poker_hands Similar problem on codewars: https://www.codewars.com/kata/ranking-poker-hands https://www.codewars.com/kata/sortable-poker-hands """ from __future__ import annotations import os class PokerHand: """Create an object representing a Poker Hand based on an input of a string which represents the best 5 card combination from the player's hand and board cards. Attributes: (read-only) hand: string representing the hand consisting of five cards Methods: compare_with(opponent): takes in player's hand (self) and opponent's hand (opponent) and compares both hands according to the rules of Texas Hold'em. Returns one of 3 strings (Win, Loss, Tie) based on whether player's hand is better than opponent's hand. hand_name(): Returns a string made up of two parts: hand name and high card. Supported operators: Rich comparison operators: <, >, <=, >=, ==, != Supported builtin methods and functions: list.sort(), sorted() """ _HAND_NAME = [ "High card", "One pair", "Two pairs", "Three of a kind", "Straight", "Flush", "Full house", "Four of a kind", "Straight flush", "Royal flush", ] _CARD_NAME = [ "", # placeholder as lists are zero indexed "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace", ] def __init__(self, hand: str) -> None: """ Initialize hand. Hand should of type str and should contain only five cards each separated by a space. The cards should be of the following format: [card value][card suit] The first character is the value of the card: 2, 3, 4, 5, 6, 7, 8, 9, T(en), J(ack), Q(ueen), K(ing), A(ce) The second character represents the suit: S(pades), H(earts), D(iamonds), C(lubs) For example: "6S 4C KC AS TH" """ if not isinstance(hand, str): msg = f"Hand should be of type 'str': {hand!r}" raise TypeError(msg) # split removes duplicate whitespaces so no need of strip if len(hand.split(" ")) != 5: msg = f"Hand should contain only 5 cards: {hand!r}" raise ValueError(msg) self._hand = hand self._first_pair = 0 self._second_pair = 0 self._card_values, self._card_suit = self._internal_state() self._hand_type = self._get_hand_type() self._high_card = self._card_values[0] @property def hand(self): """Returns the self hand""" return self._hand def compare_with(self, other: PokerHand) -> str: """ Determines the outcome of comparing self hand with other hand. Returns the output as 'Win', 'Loss', 'Tie' according to the rules of Texas Hold'em. Here are some examples: >>> player = PokerHand("2H 3H 4H 5H 6H") # Stright flush >>> opponent = PokerHand("KS AS TS QS JS") # Royal flush >>> player.compare_with(opponent) 'Loss' >>> player = PokerHand("2S AH 2H AS AC") # Full house >>> opponent = PokerHand("2H 3H 5H 6H 7H") # Flush >>> player.compare_with(opponent) 'Win' >>> player = PokerHand("2S AH 4H 5S 6C") # High card >>> opponent = PokerHand("AD 4C 5H 6H 2C") # High card >>> player.compare_with(opponent) 'Tie' """ # Breaking the tie works on the following order of precedence: # 1. First pair (default 0) # 2. Second pair (default 0) # 3. Compare all cards in reverse order because they are sorted. # First pair and second pair will only be a non-zero value if the card # type is either from the following: # 21: Four of a kind # 20: Full house # 17: Three of a kind # 16: Two pairs # 15: One pair if self._hand_type > other._hand_type: return "Win" elif self._hand_type < other._hand_type: return "Loss" elif self._first_pair == other._first_pair: if self._second_pair == other._second_pair: return self._compare_cards(other) else: return "Win" if self._second_pair > other._second_pair else "Loss" return "Win" if self._first_pair > other._first_pair else "Loss" # This function is not part of the problem, I did it just for fun def hand_name(self) -> str: """ Return the name of the hand in the following format: 'hand name, high card' Here are some examples: >>> PokerHand("KS AS TS QS JS").hand_name() 'Royal flush' >>> PokerHand("2D 6D 3D 4D 5D").hand_name() 'Straight flush, Six-high' >>> PokerHand("JC 6H JS JD JH").hand_name() 'Four of a kind, Jacks' >>> PokerHand("3D 2H 3H 2C 2D").hand_name() 'Full house, Twos over Threes' >>> PokerHand("2H 4D 3C AS 5S").hand_name() # Low ace 'Straight, Five-high' Source: https://en.wikipedia.org/wiki/List_of_poker_hands """ name = PokerHand._HAND_NAME[self._hand_type - 14] high = PokerHand._CARD_NAME[self._high_card] pair1 = PokerHand._CARD_NAME[self._first_pair] pair2 = PokerHand._CARD_NAME[self._second_pair] if self._hand_type in [22, 19, 18]: return name + f", {high}-high" elif self._hand_type in [21, 17, 15]: return name + f", {pair1}s" elif self._hand_type in [20, 16]: join = "over" if self._hand_type == 20 else "and" return name + f", {pair1}s {join} {pair2}s" elif self._hand_type == 23: return name else: return name + f", {high}" def _compare_cards(self, other: PokerHand) -> str: # Enumerate gives us the index as well as the element of a list for index, card_value in enumerate(self._card_values): if card_value != other._card_values[index]: return "Win" if card_value > other._card_values[index] else "Loss" return "Tie" def _get_hand_type(self) -> int: # Number representing the type of hand internally: # 23: Royal flush # 22: Straight flush # 21: Four of a kind # 20: Full house # 19: Flush # 18: Straight # 17: Three of a kind # 16: Two pairs # 15: One pair # 14: High card if self._is_flush(): if self._is_five_high_straight() or self._is_straight(): return 23 if sum(self._card_values) == 60 else 22 return 19 elif self._is_five_high_straight() or self._is_straight(): return 18 return 14 + self._is_same_kind() def _is_flush(self) -> bool: return len(self._card_suit) == 1 def _is_five_high_straight(self) -> bool: # If a card is a five high straight (low ace) change the location of # ace from the start of the list to the end. Check whether the first # element is ace or not. (Don't want to change again) # Five high straight (low ace): AH 2H 3S 4C 5D # Why use sorted here? One call to this function will mutate the list to # [5, 4, 3, 2, 14] and so for subsequent calls (which will be rare) we # need to compare the sorted version. # Refer test_multiple_calls_five_high_straight in test_poker_hand.py if sorted(self._card_values) == [2, 3, 4, 5, 14]: if self._card_values[0] == 14: # Remember, our list is sorted in reverse order ace_card = self._card_values.pop(0) self._card_values.append(ace_card) return True return False def _is_straight(self) -> bool: for i in range(4): if self._card_values[i] - self._card_values[i + 1] != 1: return False return True def _is_same_kind(self) -> int: # Kind Values for internal use: # 7: Four of a kind # 6: Full house # 3: Three of a kind # 2: Two pairs # 1: One pair # 0: False kind = val1 = val2 = 0 for i in range(4): # Compare two cards at a time, if they are same increase 'kind', # add the value of the card to val1, if it is repeating again we # will add 2 to 'kind' as there are now 3 cards with same value. # If we get card of different value than val1, we will do the same # thing with val2 if self._card_values[i] == self._card_values[i + 1]: if not val1: val1 = self._card_values[i] kind += 1 elif val1 == self._card_values[i]: kind += 2 elif not val2: val2 = self._card_values[i] kind += 1 elif val2 == self._card_values[i]: kind += 2 # For consistency in hand type (look at note in _get_hand_type function) kind = kind + 2 if kind in [4, 5] else kind # first meaning first pair to compare in 'compare_with' first = max(val1, val2) second = min(val1, val2) # If it's full house (three count pair + two count pair), make sure # first pair is three count and if not then switch them both. if kind == 6 and self._card_values.count(first) != 3: first, second = second, first self._first_pair = first self._second_pair = second return kind def _internal_state(self) -> tuple[list[int], set[str]]: # Internal representation of hand as a list of card values and # a set of card suit trans: dict = {"T": "10", "J": "11", "Q": "12", "K": "13", "A": "14"} new_hand = self._hand.translate(str.maketrans(trans)).split() card_values = [int(card[:-1]) for card in new_hand] card_suit = {card[-1] for card in new_hand} return sorted(card_values, reverse=True), card_suit def __repr__(self): return f'{self.__class__}("{self._hand}")' def __str__(self): return self._hand # Rich comparison operators (used in list.sort() and sorted() builtin functions) # Note that this is not part of the problem but another extra feature where # if you have a list of PokerHand objects, you can sort them just through # the builtin functions. def __eq__(self, other): if isinstance(other, PokerHand): return self.compare_with(other) == "Tie" return NotImplemented def __lt__(self, other): if isinstance(other, PokerHand): return self.compare_with(other) == "Loss" return NotImplemented def __le__(self, other): if isinstance(other, PokerHand): return self < other or self == other return NotImplemented def __gt__(self, other): if isinstance(other, PokerHand): return not self < other and self != other return NotImplemented def __ge__(self, other): if isinstance(other, PokerHand): return not self < other return NotImplemented def __hash__(self): return object.__hash__(self) def solution() -> int: # Solution for problem number 54 from Project Euler # Input from poker_hands.txt file answer = 0 script_dir = os.path.abspath(os.path.dirname(__file__)) poker_hands = os.path.join(script_dir, "poker_hands.txt") with open(poker_hands) as file_hand: for line in file_hand: player_hand = line[:14].strip() opponent_hand = line[15:].strip() player, opponent = PokerHand(player_hand), PokerHand(opponent_hand) output = player.compare_with(opponent) if output == "Win": answer += 1 return answer if __name__ == "__main__": solution()
""" Problem: https://projecteuler.net/problem=54 In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way: High Card: Highest value card. One Pair: Two cards of the same value. Two Pairs: Two different pairs. Three of a Kind: Three cards of the same value. Straight: All cards are consecutive values. Flush: All cards of the same suit. Full House: Three of a kind and a pair. Four of a Kind: Four cards of the same value. Straight Flush: All cards are consecutive values of same suit. Royal Flush: Ten, Jack, Queen, King, Ace, in same suit. The cards are valued in the order: 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace. If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives. But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared; if the highest cards tie then the next highest cards are compared, and so on. The file, poker.txt, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1's cards and the last five are Player 2's cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player's hand is in no specific order, and in each hand there is a clear winner. How many hands does Player 1 win? Resources used: https://en.wikipedia.org/wiki/Texas_hold_%27em https://en.wikipedia.org/wiki/List_of_poker_hands Similar problem on codewars: https://www.codewars.com/kata/ranking-poker-hands https://www.codewars.com/kata/sortable-poker-hands """ from __future__ import annotations import os class PokerHand: """Create an object representing a Poker Hand based on an input of a string which represents the best 5-card combination from the player's hand and board cards. Attributes: (read-only) hand: a string representing the hand consisting of five cards Methods: compare_with(opponent): takes in player's hand (self) and opponent's hand (opponent) and compares both hands according to the rules of Texas Hold'em. Returns one of 3 strings (Win, Loss, Tie) based on whether player's hand is better than the opponent's hand. hand_name(): Returns a string made up of two parts: hand name and high card. Supported operators: Rich comparison operators: <, >, <=, >=, ==, != Supported built-in methods and functions: list.sort(), sorted() """ _HAND_NAME = ( "High card", "One pair", "Two pairs", "Three of a kind", "Straight", "Flush", "Full house", "Four of a kind", "Straight flush", "Royal flush", ) _CARD_NAME = ( "", # placeholder as tuples are zero-indexed "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace", ) def __init__(self, hand: str) -> None: """ Initialize hand. Hand should of type str and should contain only five cards each separated by a space. The cards should be of the following format: [card value][card suit] The first character is the value of the card: 2, 3, 4, 5, 6, 7, 8, 9, T(en), J(ack), Q(ueen), K(ing), A(ce) The second character represents the suit: S(pades), H(earts), D(iamonds), C(lubs) For example: "6S 4C KC AS TH" """ if not isinstance(hand, str): msg = f"Hand should be of type 'str': {hand!r}" raise TypeError(msg) # split removes duplicate whitespaces so no need of strip if len(hand.split(" ")) != 5: msg = f"Hand should contain only 5 cards: {hand!r}" raise ValueError(msg) self._hand = hand self._first_pair = 0 self._second_pair = 0 self._card_values, self._card_suit = self._internal_state() self._hand_type = self._get_hand_type() self._high_card = self._card_values[0] @property def hand(self): """Returns the self hand""" return self._hand def compare_with(self, other: PokerHand) -> str: """ Determines the outcome of comparing self hand with other hand. Returns the output as 'Win', 'Loss', 'Tie' according to the rules of Texas Hold'em. Here are some examples: >>> player = PokerHand("2H 3H 4H 5H 6H") # Stright flush >>> opponent = PokerHand("KS AS TS QS JS") # Royal flush >>> player.compare_with(opponent) 'Loss' >>> player = PokerHand("2S AH 2H AS AC") # Full house >>> opponent = PokerHand("2H 3H 5H 6H 7H") # Flush >>> player.compare_with(opponent) 'Win' >>> player = PokerHand("2S AH 4H 5S 6C") # High card >>> opponent = PokerHand("AD 4C 5H 6H 2C") # High card >>> player.compare_with(opponent) 'Tie' """ # Breaking the tie works on the following order of precedence: # 1. First pair (default 0) # 2. Second pair (default 0) # 3. Compare all cards in reverse order because they are sorted. # First pair and second pair will only be a non-zero value if the card # type is either from the following: # 21: Four of a kind # 20: Full house # 17: Three of a kind # 16: Two pairs # 15: One pair if self._hand_type > other._hand_type: return "Win" elif self._hand_type < other._hand_type: return "Loss" elif self._first_pair == other._first_pair: if self._second_pair == other._second_pair: return self._compare_cards(other) else: return "Win" if self._second_pair > other._second_pair else "Loss" return "Win" if self._first_pair > other._first_pair else "Loss" # This function is not part of the problem, I did it just for fun def hand_name(self) -> str: """ Return the name of the hand in the following format: 'hand name, high card' Here are some examples: >>> PokerHand("KS AS TS QS JS").hand_name() 'Royal flush' >>> PokerHand("2D 6D 3D 4D 5D").hand_name() 'Straight flush, Six-high' >>> PokerHand("JC 6H JS JD JH").hand_name() 'Four of a kind, Jacks' >>> PokerHand("3D 2H 3H 2C 2D").hand_name() 'Full house, Twos over Threes' >>> PokerHand("2H 4D 3C AS 5S").hand_name() # Low ace 'Straight, Five-high' Source: https://en.wikipedia.org/wiki/List_of_poker_hands """ name = PokerHand._HAND_NAME[self._hand_type - 14] high = PokerHand._CARD_NAME[self._high_card] pair1 = PokerHand._CARD_NAME[self._first_pair] pair2 = PokerHand._CARD_NAME[self._second_pair] if self._hand_type in [22, 19, 18]: return name + f", {high}-high" elif self._hand_type in [21, 17, 15]: return name + f", {pair1}s" elif self._hand_type in [20, 16]: join = "over" if self._hand_type == 20 else "and" return name + f", {pair1}s {join} {pair2}s" elif self._hand_type == 23: return name else: return name + f", {high}" def _compare_cards(self, other: PokerHand) -> str: # Enumerate gives us the index as well as the element of a list for index, card_value in enumerate(self._card_values): if card_value != other._card_values[index]: return "Win" if card_value > other._card_values[index] else "Loss" return "Tie" def _get_hand_type(self) -> int: # Number representing the type of hand internally: # 23: Royal flush # 22: Straight flush # 21: Four of a kind # 20: Full house # 19: Flush # 18: Straight # 17: Three of a kind # 16: Two pairs # 15: One pair # 14: High card if self._is_flush(): if self._is_five_high_straight() or self._is_straight(): return 23 if sum(self._card_values) == 60 else 22 return 19 elif self._is_five_high_straight() or self._is_straight(): return 18 return 14 + self._is_same_kind() def _is_flush(self) -> bool: return len(self._card_suit) == 1 def _is_five_high_straight(self) -> bool: # If a card is a five high straight (low ace) change the location of # ace from the start of the list to the end. Check whether the first # element is ace or not. (Don't want to change again) # Five high straight (low ace): AH 2H 3S 4C 5D # Why use sorted here? One call to this function will mutate the list to # [5, 4, 3, 2, 14] and so for subsequent calls (which will be rare) we # need to compare the sorted version. # Refer test_multiple_calls_five_high_straight in test_poker_hand.py if sorted(self._card_values) == [2, 3, 4, 5, 14]: if self._card_values[0] == 14: # Remember, our list is sorted in reverse order ace_card = self._card_values.pop(0) self._card_values.append(ace_card) return True return False def _is_straight(self) -> bool: for i in range(4): if self._card_values[i] - self._card_values[i + 1] != 1: return False return True def _is_same_kind(self) -> int: # Kind Values for internal use: # 7: Four of a kind # 6: Full house # 3: Three of a kind # 2: Two pairs # 1: One pair # 0: False kind = val1 = val2 = 0 for i in range(4): # Compare two cards at a time, if they are same increase 'kind', # add the value of the card to val1, if it is repeating again we # will add 2 to 'kind' as there are now 3 cards with same value. # If we get card of different value than val1, we will do the same # thing with val2 if self._card_values[i] == self._card_values[i + 1]: if not val1: val1 = self._card_values[i] kind += 1 elif val1 == self._card_values[i]: kind += 2 elif not val2: val2 = self._card_values[i] kind += 1 elif val2 == self._card_values[i]: kind += 2 # For consistency in hand type (look at note in _get_hand_type function) kind = kind + 2 if kind in [4, 5] else kind # first meaning first pair to compare in 'compare_with' first = max(val1, val2) second = min(val1, val2) # If it's full house (three count pair + two count pair), make sure # first pair is three count and if not then switch them both. if kind == 6 and self._card_values.count(first) != 3: first, second = second, first self._first_pair = first self._second_pair = second return kind def _internal_state(self) -> tuple[list[int], set[str]]: # Internal representation of hand as a list of card values and # a set of card suit trans: dict = {"T": "10", "J": "11", "Q": "12", "K": "13", "A": "14"} new_hand = self._hand.translate(str.maketrans(trans)).split() card_values = [int(card[:-1]) for card in new_hand] card_suit = {card[-1] for card in new_hand} return sorted(card_values, reverse=True), card_suit def __repr__(self): return f'{self.__class__}("{self._hand}")' def __str__(self): return self._hand # Rich comparison operators (used in list.sort() and sorted() builtin functions) # Note that this is not part of the problem but another extra feature where # if you have a list of PokerHand objects, you can sort them just through # the builtin functions. def __eq__(self, other): if isinstance(other, PokerHand): return self.compare_with(other) == "Tie" return NotImplemented def __lt__(self, other): if isinstance(other, PokerHand): return self.compare_with(other) == "Loss" return NotImplemented def __le__(self, other): if isinstance(other, PokerHand): return self < other or self == other return NotImplemented def __gt__(self, other): if isinstance(other, PokerHand): return not self < other and self != other return NotImplemented def __ge__(self, other): if isinstance(other, PokerHand): return not self < other return NotImplemented def __hash__(self): return object.__hash__(self) def solution() -> int: # Solution for problem number 54 from Project Euler # Input from poker_hands.txt file answer = 0 script_dir = os.path.abspath(os.path.dirname(__file__)) poker_hands = os.path.join(script_dir, "poker_hands.txt") with open(poker_hands) as file_hand: for line in file_hand: player_hand = line[:14].strip() opponent_hand = line[15:].strip() player, opponent = PokerHand(player_hand), PokerHand(opponent_hand) output = player.compare_with(opponent) if output == "Win": answer += 1 return answer if __name__ == "__main__": solution()
1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
[tool.ruff] ignore = [ # `ruff rule S101` for a description of that rule "ARG001", # Unused function argument `amount` -- FIX ME? "B904", # Within an `except` clause, raise exceptions with `raise ... from err` -- FIX ME "B905", # `zip()` without an explicit `strict=` parameter -- FIX ME "DTZ001", # The use of `datetime.datetime()` without `tzinfo` argument is not allowed -- FIX ME "DTZ005", # The use of `datetime.datetime.now()` without `tzinfo` argument is not allowed -- FIX ME "E741", # Ambiguous variable name 'l' -- FIX ME "EM101", # Exception must not use a string literal, assign to variable first "EXE001", # Shebang is present but file is not executable" -- FIX ME "G004", # Logging statement uses f-string "ICN001", # `matplotlib.pyplot` should be imported as `plt` -- FIX ME "INP001", # File `x/y/z.py` is part of an implicit namespace package. Add an `__init__.py`. -- FIX ME "N999", # Invalid module name -- FIX ME "NPY002", # Replace legacy `np.random.choice` call with `np.random.Generator` -- FIX ME "PGH003", # Use specific rule codes when ignoring type issues -- FIX ME "PLC1901", # `{}` can be simplified to `{}` as an empty string is falsey "PLR5501", # Consider using `elif` instead of `else` -- FIX ME "PLW0120", # `else` clause on loop without a `break` statement -- FIX ME "PLW060", # Using global for `{name}` but no assignment is done -- DO NOT FIX "PLW2901", # PLW2901: Redefined loop variable -- FIX ME "RUF00", # Ambiguous unicode character and other rules "RUF100", # Unused `noqa` directive -- FIX ME "S101", # Use of `assert` detected -- DO NOT FIX "S105", # Possible hardcoded password: 'password' "S113", # Probable use of requests call without timeout -- FIX ME "S311", # Standard pseudo-random generators are not suitable for cryptographic purposes -- FIX ME "SIM102", # Use a single `if` statement instead of nested `if` statements -- FIX ME "SLF001", # Private member accessed: `_Iterator` -- FIX ME "UP038", # Use `X | Y` in `{}` call instead of `(X, Y)` -- DO NOT FIX ] select = [ # https://beta.ruff.rs/docs/rules "A", # flake8-builtins "ARG", # flake8-unused-arguments "ASYNC", # flake8-async "B", # flake8-bugbear "BLE", # flake8-blind-except "C4", # flake8-comprehensions "C90", # McCabe cyclomatic complexity "DTZ", # flake8-datetimez "E", # pycodestyle "EM", # flake8-errmsg "EXE", # flake8-executable "F", # Pyflakes "FA", # flake8-future-annotations "FLY", # flynt "G", # flake8-logging-format "I", # isort "ICN", # flake8-import-conventions "INP", # flake8-no-pep420 "INT", # flake8-gettext "N", # pep8-naming "NPY", # NumPy-specific rules "PGH", # pygrep-hooks "PIE", # flake8-pie "PL", # Pylint "PYI", # flake8-pyi "RSE", # flake8-raise "RUF", # Ruff-specific rules "S", # flake8-bandit "SIM", # flake8-simplify "SLF", # flake8-self "T10", # flake8-debugger "TD", # flake8-todos "TID", # flake8-tidy-imports "UP", # pyupgrade "W", # pycodestyle "YTT", # flake8-2020 # "ANN", # flake8-annotations # FIX ME? # "COM", # flake8-commas # "D", # pydocstyle -- FIX ME? # "DJ", # flake8-django # "ERA", # eradicate -- DO NOT FIX # "FBT", # flake8-boolean-trap # FIX ME # "ISC", # flake8-implicit-str-concat # FIX ME # "PD", # pandas-vet # "PT", # flake8-pytest-style # "PTH", # flake8-use-pathlib # FIX ME # "Q", # flake8-quotes # "RET", # flake8-return # FIX ME? # "T20", # flake8-print # "TCH", # flake8-type-checking # "TRY", # tryceratops ] show-source = true target-version = "py311" [tool.ruff.mccabe] # DO NOT INCREASE THIS VALUE max-complexity = 17 # default: 10 [tool.ruff.per-file-ignores] "arithmetic_analysis/newton_raphson.py" = ["PGH001"] "audio_filters/show_response.py" = ["ARG002"] "data_structures/binary_tree/binary_search_tree_recursive.py" = ["BLE001"] "data_structures/binary_tree/treap.py" = ["SIM114"] "data_structures/hashing/hash_table.py" = ["ARG002"] "data_structures/hashing/quadratic_probing.py" = ["ARG002"] "data_structures/hashing/tests/test_hash_map.py" = ["BLE001"] "data_structures/heap/max_heap.py" = ["SIM114"] "graphs/minimum_spanning_tree_prims.py" = ["SIM114"] "hashes/enigma_machine.py" = ["BLE001"] "machine_learning/decision_tree.py" = ["SIM114"] "machine_learning/linear_discriminant_analysis.py" = ["ARG005"] "machine_learning/sequential_minimum_optimization.py" = ["SIM115"] "matrix/sherman_morrison.py" = ["SIM103", "SIM114"] "physics/newtons_second_law_of_motion.py" = ["BLE001"] "project_euler/problem_099/sol1.py" = ["SIM115"] "sorts/external_sort.py" = ["SIM115"] [tool.ruff.pylint] # DO NOT INCREASE THESE VALUES allow-magic-value-types = ["float", "int", "str"] max-args = 10 # default: 5 max-branches = 20 # default: 12 max-returns = 8 # default: 6 max-statements = 88 # default: 50 [tool.pytest.ini_options] markers = [ "mat_ops: mark a test as utilizing matrix operations.", ] addopts = [ "--durations=10", "--doctest-modules", "--showlocals", ] [tool.coverage.report] omit = [".env/*"] sort = "Cover" [tool.codespell] ignore-words-list = "3rt,ans,crate,damon,fo,followings,hist,iff,kwanza,mater,secant,som,sur,tim,zar" skip = "./.*,*.json,ciphers/prehistoric_men.txt,project_euler/problem_022/p022_names.txt,pyproject.toml,strings/dictionary.txt,strings/words.txt"
[tool.ruff] ignore = [ # `ruff rule S101` for a description of that rule "ARG001", # Unused function argument `amount` -- FIX ME? "B904", # Within an `except` clause, raise exceptions with `raise ... from err` -- FIX ME "B905", # `zip()` without an explicit `strict=` parameter -- FIX ME "DTZ001", # The use of `datetime.datetime()` without `tzinfo` argument is not allowed -- FIX ME "DTZ005", # The use of `datetime.datetime.now()` without `tzinfo` argument is not allowed -- FIX ME "E741", # Ambiguous variable name 'l' -- FIX ME "EM101", # Exception must not use a string literal, assign to variable first "EXE001", # Shebang is present but file is not executable" -- FIX ME "G004", # Logging statement uses f-string "ICN001", # `matplotlib.pyplot` should be imported as `plt` -- FIX ME "INP001", # File `x/y/z.py` is part of an implicit namespace package. Add an `__init__.py`. -- FIX ME "N999", # Invalid module name -- FIX ME "NPY002", # Replace legacy `np.random.choice` call with `np.random.Generator` -- FIX ME "PGH003", # Use specific rule codes when ignoring type issues -- FIX ME "PLC1901", # `{}` can be simplified to `{}` as an empty string is falsey "PLR5501", # Consider using `elif` instead of `else` -- FIX ME "PLW0120", # `else` clause on loop without a `break` statement -- FIX ME "PLW060", # Using global for `{name}` but no assignment is done -- DO NOT FIX "PLW2901", # PLW2901: Redefined loop variable -- FIX ME "RUF00", # Ambiguous unicode character and other rules "RUF100", # Unused `noqa` directive -- FIX ME "S101", # Use of `assert` detected -- DO NOT FIX "S105", # Possible hardcoded password: 'password' "S113", # Probable use of requests call without timeout -- FIX ME "S311", # Standard pseudo-random generators are not suitable for cryptographic purposes -- FIX ME "SIM102", # Use a single `if` statement instead of nested `if` statements -- FIX ME "SLF001", # Private member accessed: `_Iterator` -- FIX ME "UP038", # Use `X | Y` in `{}` call instead of `(X, Y)` -- DO NOT FIX ] select = [ # https://beta.ruff.rs/docs/rules "A", # flake8-builtins "ARG", # flake8-unused-arguments "ASYNC", # flake8-async "B", # flake8-bugbear "BLE", # flake8-blind-except "C4", # flake8-comprehensions "C90", # McCabe cyclomatic complexity "DTZ", # flake8-datetimez "E", # pycodestyle "EM", # flake8-errmsg "EXE", # flake8-executable "F", # Pyflakes "FA", # flake8-future-annotations "FLY", # flynt "G", # flake8-logging-format "I", # isort "ICN", # flake8-import-conventions "INP", # flake8-no-pep420 "INT", # flake8-gettext "N", # pep8-naming "NPY", # NumPy-specific rules "PGH", # pygrep-hooks "PIE", # flake8-pie "PL", # Pylint "PYI", # flake8-pyi "RSE", # flake8-raise "RUF", # Ruff-specific rules "S", # flake8-bandit "SIM", # flake8-simplify "SLF", # flake8-self "T10", # flake8-debugger "TD", # flake8-todos "TID", # flake8-tidy-imports "UP", # pyupgrade "W", # pycodestyle "YTT", # flake8-2020 # "ANN", # flake8-annotations # FIX ME? # "COM", # flake8-commas # "D", # pydocstyle -- FIX ME? # "DJ", # flake8-django # "ERA", # eradicate -- DO NOT FIX # "FBT", # flake8-boolean-trap # FIX ME # "ISC", # flake8-implicit-str-concat # FIX ME # "PD", # pandas-vet # "PT", # flake8-pytest-style # "PTH", # flake8-use-pathlib # FIX ME # "Q", # flake8-quotes # "RET", # flake8-return # FIX ME? # "T20", # flake8-print # "TCH", # flake8-type-checking # "TRY", # tryceratops ] show-source = true target-version = "py311" [tool.ruff.mccabe] # DO NOT INCREASE THIS VALUE max-complexity = 17 # default: 10 [tool.ruff.per-file-ignores] "arithmetic_analysis/newton_raphson.py" = ["PGH001"] "audio_filters/show_response.py" = ["ARG002"] "data_structures/binary_tree/binary_search_tree_recursive.py" = ["BLE001"] "data_structures/binary_tree/treap.py" = ["SIM114"] "data_structures/hashing/hash_table.py" = ["ARG002"] "data_structures/hashing/quadratic_probing.py" = ["ARG002"] "data_structures/hashing/tests/test_hash_map.py" = ["BLE001"] "data_structures/heap/max_heap.py" = ["SIM114"] "graphs/minimum_spanning_tree_prims.py" = ["SIM114"] "hashes/enigma_machine.py" = ["BLE001"] "machine_learning/decision_tree.py" = ["SIM114"] "machine_learning/linear_discriminant_analysis.py" = ["ARG005"] "machine_learning/sequential_minimum_optimization.py" = ["SIM115"] "matrix/sherman_morrison.py" = ["SIM103", "SIM114"] "other/l*u_cache.py" = ["RUF012"] "physics/newtons_second_law_of_motion.py" = ["BLE001"] "project_euler/problem_099/sol1.py" = ["SIM115"] "sorts/external_sort.py" = ["SIM115"] [tool.ruff.pylint] # DO NOT INCREASE THESE VALUES allow-magic-value-types = ["float", "int", "str"] max-args = 10 # default: 5 max-branches = 20 # default: 12 max-returns = 8 # default: 6 max-statements = 88 # default: 50 [tool.pytest.ini_options] markers = [ "mat_ops: mark a test as utilizing matrix operations.", ] addopts = [ "--durations=10", "--doctest-modules", "--showlocals", ] [tool.coverage.report] omit = [".env/*"] sort = "Cover" [tool.codespell] ignore-words-list = "3rt,ans,crate,damon,fo,followings,hist,iff,kwanza,mater,secant,som,sur,tim,zar" skip = "./.*,*.json,ciphers/prehistoric_men.txt,project_euler/problem_022/p022_names.txt,pyproject.toml,strings/dictionary.txt,strings/words.txt"
1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def _get(k): return getitem, k def _set(k, v): return setitem, k, v def _del(k): return delitem, k def _run_operation(obj, fun, *args): try: return fun(obj, *args), None except Exception as e: return None, e _add_items = ( _set("key_a", "val_a"), _set("key_b", "val_b"), ) _overwrite_items = [ _set("key_a", "val_a"), _set("key_a", "val_b"), ] _delete_items = [ _set("key_a", "val_a"), _set("key_b", "val_b"), _del("key_a"), _del("key_b"), _set("key_a", "val_a"), _del("key_a"), ] _access_absent_items = [ _get("key_a"), _del("key_a"), _set("key_a", "val_a"), _del("key_a"), _del("key_a"), _get("key_a"), ] _add_with_resize_up = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] _add_with_resize_down = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set("key_a", "val_b"), ] @pytest.mark.parametrize( "operations", ( pytest.param(_add_items, id="add items"), pytest.param(_overwrite_items, id="overwrite items"), pytest.param(_delete_items, id="delete items"), pytest.param(_access_absent_items, id="access absent items"), pytest.param(_add_with_resize_up, id="add with resize up"), pytest.param(_add_with_resize_down, id="add with resize down"), ), ) def test_hash_map_is_the_same_as_dict(operations): my = HashMap(initial_block_size=4) py = {} for _, (fun, *args) in enumerate(operations): my_res, my_exc = _run_operation(my, fun, *args) py_res, py_exc = _run_operation(py, fun, *args) assert my_res == py_res assert str(my_exc) == str(py_exc) assert set(py) == set(my) assert len(py) == len(my) assert set(my.items()) == set(py.items()) def test_no_new_methods_was_added_to_api(): def is_public(name: str) -> bool: return not name.startswith("_") dict_public_names = {name for name in dir({}) if is_public(name)} hash_public_names = {name for name in dir(HashMap()) if is_public(name)} assert dict_public_names > hash_public_names
from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def _get(k): return getitem, k def _set(k, v): return setitem, k, v def _del(k): return delitem, k def _run_operation(obj, fun, *args): try: return fun(obj, *args), None except Exception as e: return None, e _add_items = ( _set("key_a", "val_a"), _set("key_b", "val_b"), ) _overwrite_items = [ _set("key_a", "val_a"), _set("key_a", "val_b"), ] _delete_items = [ _set("key_a", "val_a"), _set("key_b", "val_b"), _del("key_a"), _del("key_b"), _set("key_a", "val_a"), _del("key_a"), ] _access_absent_items = [ _get("key_a"), _del("key_a"), _set("key_a", "val_a"), _del("key_a"), _del("key_a"), _get("key_a"), ] _add_with_resize_up = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] _add_with_resize_down = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set("key_a", "val_b"), ] @pytest.mark.parametrize( "operations", ( pytest.param(_add_items, id="add items"), pytest.param(_overwrite_items, id="overwrite items"), pytest.param(_delete_items, id="delete items"), pytest.param(_access_absent_items, id="access absent items"), pytest.param(_add_with_resize_up, id="add with resize up"), pytest.param(_add_with_resize_down, id="add with resize down"), ), ) def test_hash_map_is_the_same_as_dict(operations): my = HashMap(initial_block_size=4) py = {} for _, (fun, *args) in enumerate(operations): my_res, my_exc = _run_operation(my, fun, *args) py_res, py_exc = _run_operation(py, fun, *args) assert my_res == py_res assert str(my_exc) == str(py_exc) assert set(py) == set(my) assert len(py) == len(my) assert set(my.items()) == set(py.items()) def test_no_new_methods_was_added_to_api(): def is_public(name: str) -> bool: return not name.startswith("_") dict_public_names = {name for name in dir({}) if is_public(name)} hash_public_names = {name for name in dir(HashMap()) if is_public(name)} assert dict_public_names > hash_public_names
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
from __future__ import annotations import math class SegmentTree: def __init__(self, size: int) -> None: self.size = size # approximate the overall size of segment tree with given value self.segment_tree = [0 for i in range(0, 4 * size)] # create array to store lazy update self.lazy = [0 for i in range(0, 4 * size)] self.flag = [0 for i in range(0, 4 * size)] # flag for lazy update def left(self, idx: int) -> int: """ >>> segment_tree = SegmentTree(15) >>> segment_tree.left(1) 2 >>> segment_tree.left(2) 4 >>> segment_tree.left(12) 24 """ return idx * 2 def right(self, idx: int) -> int: """ >>> segment_tree = SegmentTree(15) >>> segment_tree.right(1) 3 >>> segment_tree.right(2) 5 >>> segment_tree.right(12) 25 """ return idx * 2 + 1 def build( self, idx: int, left_element: int, right_element: int, a: list[int] ) -> None: if left_element == right_element: self.segment_tree[idx] = a[left_element - 1] else: mid = (left_element + right_element) // 2 self.build(self.left(idx), left_element, mid, a) self.build(self.right(idx), mid + 1, right_element, a) self.segment_tree[idx] = max( self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)] ) def update( self, idx: int, left_element: int, right_element: int, a: int, b: int, val: int ) -> bool: """ update with O(lg n) (Normal segment tree without lazy update will take O(nlg n) for each update) update(1, 1, size, a, b, v) for update val v to [a,b] """ if self.flag[idx] is True: self.segment_tree[idx] = self.lazy[idx] self.flag[idx] = False if left_element != right_element: self.lazy[self.left(idx)] = self.lazy[idx] self.lazy[self.right(idx)] = self.lazy[idx] self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: self.segment_tree[idx] = val if left_element != right_element: self.lazy[self.left(idx)] = val self.lazy[self.right(idx)] = val self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True return True mid = (left_element + right_element) // 2 self.update(self.left(idx), left_element, mid, a, b, val) self.update(self.right(idx), mid + 1, right_element, a, b, val) self.segment_tree[idx] = max( self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)] ) return True # query with O(lg n) def query( self, idx: int, left_element: int, right_element: int, a: int, b: int ) -> int | float: """ query(1, 1, size, a, b) for query max of [a,b] >>> A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] >>> segment_tree = SegmentTree(15) >>> segment_tree.build(1, 1, 15, A) >>> segment_tree.query(1, 1, 15, 4, 6) 7 >>> segment_tree.query(1, 1, 15, 7, 11) 14 >>> segment_tree.query(1, 1, 15, 7, 12) 15 """ if self.flag[idx] is True: self.segment_tree[idx] = self.lazy[idx] self.flag[idx] = False if left_element != right_element: self.lazy[self.left(idx)] = self.lazy[idx] self.lazy[self.right(idx)] = self.lazy[idx] self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] mid = (left_element + right_element) // 2 q1 = self.query(self.left(idx), left_element, mid, a, b) q2 = self.query(self.right(idx), mid + 1, right_element, a, b) return max(q1, q2) def __str__(self) -> str: return str([self.query(1, 1, self.size, i, i) for i in range(1, self.size + 1)]) if __name__ == "__main__": A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] size = 15 segt = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
from __future__ import annotations import math class SegmentTree: def __init__(self, size: int) -> None: self.size = size # approximate the overall size of segment tree with given value self.segment_tree = [0 for i in range(0, 4 * size)] # create array to store lazy update self.lazy = [0 for i in range(0, 4 * size)] self.flag = [0 for i in range(0, 4 * size)] # flag for lazy update def left(self, idx: int) -> int: """ >>> segment_tree = SegmentTree(15) >>> segment_tree.left(1) 2 >>> segment_tree.left(2) 4 >>> segment_tree.left(12) 24 """ return idx * 2 def right(self, idx: int) -> int: """ >>> segment_tree = SegmentTree(15) >>> segment_tree.right(1) 3 >>> segment_tree.right(2) 5 >>> segment_tree.right(12) 25 """ return idx * 2 + 1 def build( self, idx: int, left_element: int, right_element: int, a: list[int] ) -> None: if left_element == right_element: self.segment_tree[idx] = a[left_element - 1] else: mid = (left_element + right_element) // 2 self.build(self.left(idx), left_element, mid, a) self.build(self.right(idx), mid + 1, right_element, a) self.segment_tree[idx] = max( self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)] ) def update( self, idx: int, left_element: int, right_element: int, a: int, b: int, val: int ) -> bool: """ update with O(lg n) (Normal segment tree without lazy update will take O(nlg n) for each update) update(1, 1, size, a, b, v) for update val v to [a,b] """ if self.flag[idx] is True: self.segment_tree[idx] = self.lazy[idx] self.flag[idx] = False if left_element != right_element: self.lazy[self.left(idx)] = self.lazy[idx] self.lazy[self.right(idx)] = self.lazy[idx] self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: self.segment_tree[idx] = val if left_element != right_element: self.lazy[self.left(idx)] = val self.lazy[self.right(idx)] = val self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True return True mid = (left_element + right_element) // 2 self.update(self.left(idx), left_element, mid, a, b, val) self.update(self.right(idx), mid + 1, right_element, a, b, val) self.segment_tree[idx] = max( self.segment_tree[self.left(idx)], self.segment_tree[self.right(idx)] ) return True # query with O(lg n) def query( self, idx: int, left_element: int, right_element: int, a: int, b: int ) -> int | float: """ query(1, 1, size, a, b) for query max of [a,b] >>> A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] >>> segment_tree = SegmentTree(15) >>> segment_tree.build(1, 1, 15, A) >>> segment_tree.query(1, 1, 15, 4, 6) 7 >>> segment_tree.query(1, 1, 15, 7, 11) 14 >>> segment_tree.query(1, 1, 15, 7, 12) 15 """ if self.flag[idx] is True: self.segment_tree[idx] = self.lazy[idx] self.flag[idx] = False if left_element != right_element: self.lazy[self.left(idx)] = self.lazy[idx] self.lazy[self.right(idx)] = self.lazy[idx] self.flag[self.left(idx)] = True self.flag[self.right(idx)] = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] mid = (left_element + right_element) // 2 q1 = self.query(self.left(idx), left_element, mid, a, b) q2 = self.query(self.right(idx), mid + 1, right_element, a, b) return max(q1, q2) def __str__(self) -> str: return str([self.query(1, 1, self.size, i, i) for i in range(1, self.size + 1)]) if __name__ == "__main__": A = [1, 2, -4, 7, 3, -5, 6, 11, -20, 9, 14, 15, 5, 2, -8] size = 15 segt = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 11)) print(segt.query(1, 1, size, 7, 12)) segt.update(1, 1, size, 1, 3, 111) print(segt.query(1, 1, size, 1, 15)) segt.update(1, 1, size, 7, 8, 235) print(segt)
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
import unittest import numpy as np def schur_complement( mat_a: np.ndarray, mat_b: np.ndarray, mat_c: np.ndarray, pseudo_inv: np.ndarray | None = None, ) -> np.ndarray: """ Schur complement of a symmetric matrix X given as a 2x2 block matrix consisting of matrices A, B and C. Matrix A must be quadratic and non-singular. In case A is singular, a pseudo-inverse may be provided using the pseudo_inv argument. Link to Wiki: https://en.wikipedia.org/wiki/Schur_complement See also Convex Optimization – Boyd and Vandenberghe, A.5.5 >>> import numpy as np >>> a = np.array([[1, 2], [2, 1]]) >>> b = np.array([[0, 3], [3, 0]]) >>> c = np.array([[2, 1], [6, 3]]) >>> schur_complement(a, b, c) array([[ 5., -5.], [ 0., 6.]]) """ shape_a = np.shape(mat_a) shape_b = np.shape(mat_b) shape_c = np.shape(mat_c) if shape_a[0] != shape_b[0]: msg = ( "Expected the same number of rows for A and B. " f"Instead found A of size {shape_a} and B of size {shape_b}" ) raise ValueError(msg) if shape_b[1] != shape_c[1]: msg = ( "Expected the same number of columns for B and C. " f"Instead found B of size {shape_b} and C of size {shape_c}" ) raise ValueError(msg) a_inv = pseudo_inv if a_inv is None: try: a_inv = np.linalg.inv(mat_a) except np.linalg.LinAlgError: raise ValueError( "Input matrix A is not invertible. Cannot compute Schur complement." ) return mat_c - mat_b.T @ a_inv @ mat_b class TestSchurComplement(unittest.TestCase): def test_schur_complement(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1], [6, 3]]) s = schur_complement(a, b, c) input_matrix = np.block([[a, b], [b.T, c]]) det_x = np.linalg.det(input_matrix) det_a = np.linalg.det(a) det_s = np.linalg.det(s) self.assertAlmostEqual(det_x, det_a * det_s) def test_improper_a_b_dimensions(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1], [6, 3]]) with self.assertRaises(ValueError): schur_complement(a, b, c) def test_improper_b_c_dimensions(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1, 3], [6, 3, 5]]) with self.assertRaises(ValueError): schur_complement(a, b, c) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
import unittest import numpy as np def schur_complement( mat_a: np.ndarray, mat_b: np.ndarray, mat_c: np.ndarray, pseudo_inv: np.ndarray | None = None, ) -> np.ndarray: """ Schur complement of a symmetric matrix X given as a 2x2 block matrix consisting of matrices A, B and C. Matrix A must be quadratic and non-singular. In case A is singular, a pseudo-inverse may be provided using the pseudo_inv argument. Link to Wiki: https://en.wikipedia.org/wiki/Schur_complement See also Convex Optimization – Boyd and Vandenberghe, A.5.5 >>> import numpy as np >>> a = np.array([[1, 2], [2, 1]]) >>> b = np.array([[0, 3], [3, 0]]) >>> c = np.array([[2, 1], [6, 3]]) >>> schur_complement(a, b, c) array([[ 5., -5.], [ 0., 6.]]) """ shape_a = np.shape(mat_a) shape_b = np.shape(mat_b) shape_c = np.shape(mat_c) if shape_a[0] != shape_b[0]: msg = ( "Expected the same number of rows for A and B. " f"Instead found A of size {shape_a} and B of size {shape_b}" ) raise ValueError(msg) if shape_b[1] != shape_c[1]: msg = ( "Expected the same number of columns for B and C. " f"Instead found B of size {shape_b} and C of size {shape_c}" ) raise ValueError(msg) a_inv = pseudo_inv if a_inv is None: try: a_inv = np.linalg.inv(mat_a) except np.linalg.LinAlgError: raise ValueError( "Input matrix A is not invertible. Cannot compute Schur complement." ) return mat_c - mat_b.T @ a_inv @ mat_b class TestSchurComplement(unittest.TestCase): def test_schur_complement(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1], [6, 3]]) s = schur_complement(a, b, c) input_matrix = np.block([[a, b], [b.T, c]]) det_x = np.linalg.det(input_matrix) det_a = np.linalg.det(a) det_s = np.linalg.det(s) self.assertAlmostEqual(det_x, det_a * det_s) def test_improper_a_b_dimensions(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1], [6, 3]]) with self.assertRaises(ValueError): schur_complement(a, b, c) def test_improper_b_c_dimensions(self) -> None: a = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) b = np.array([[0, 3], [3, 0], [2, 3]]) c = np.array([[2, 1, 3], [6, 3, 5]]) with self.assertRaises(ValueError): schur_complement(a, b, c) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
# https://en.wikipedia.org/wiki/Simulated_annealing import math import random from typing import Any from .hill_climbing import SearchProblem def simulated_annealing( search_prob, find_max: bool = True, max_x: float = math.inf, min_x: float = -math.inf, max_y: float = math.inf, min_y: float = -math.inf, visualization: bool = False, start_temperate: float = 100, rate_of_decrease: float = 0.01, threshold_temp: float = 1, ) -> Any: """ Implementation of the simulated annealing algorithm. We start with a given state, find all its neighbors. Pick a random neighbor, if that neighbor improves the solution, we move in that direction, if that neighbor does not improve the solution, we generate a random real number between 0 and 1, if the number is within a certain range (calculated using temperature) we move in that direction, else we pick another neighbor randomly and repeat the process. Args: search_prob: The search state at the start. find_max: If True, the algorithm should find the minimum else the minimum. max_x, min_x, max_y, min_y: the maximum and minimum bounds of x and y. visualization: If True, a matplotlib graph is displayed. start_temperate: the initial temperate of the system when the program starts. rate_of_decrease: the rate at which the temperate decreases in each iteration. threshold_temp: the threshold temperature below which we end the search Returns a search state having the maximum (or minimum) score. """ search_end = False current_state = search_prob current_temp = start_temperate scores = [] iterations = 0 best_state = None while not search_end: current_score = current_state.score() if best_state is None or current_score > best_state.score(): best_state = current_state scores.append(current_score) iterations += 1 next_state = None neighbors = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to index = random.randint(0, len(neighbors) - 1) # picking a random neighbor picked_neighbor = neighbors.pop(index) change = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: change = change * -1 # in case we are finding minimum if change > 0: # improves the solution next_state = picked_neighbor else: probability = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability next_state = picked_neighbor current_temp = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor search_end = True else: current_state = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(iterations), scores) plt.xlabel("Iterations") plt.ylabel("Function values") plt.show() return best_state if __name__ == "__main__": def test_f1(x, y): return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1) local_min = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " f"and 50 > y > - 5 found via hill climbing: {local_min.score()}" ) # starting the problem with initial coordinates (12, 47) prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1) local_min = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " f"and 50 > y > - 5 found via hill climbing: {local_min.score()}" ) def test_f2(x, y): return (3 * x**2) - (6 * y) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) local_min = simulated_annealing(prob, find_max=False, visualization=True) print( "The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: " f"{local_min.score()}" ) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) local_min = simulated_annealing(prob, find_max=True, visualization=True) print( "The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: " f"{local_min.score()}" )
# https://en.wikipedia.org/wiki/Simulated_annealing import math import random from typing import Any from .hill_climbing import SearchProblem def simulated_annealing( search_prob, find_max: bool = True, max_x: float = math.inf, min_x: float = -math.inf, max_y: float = math.inf, min_y: float = -math.inf, visualization: bool = False, start_temperate: float = 100, rate_of_decrease: float = 0.01, threshold_temp: float = 1, ) -> Any: """ Implementation of the simulated annealing algorithm. We start with a given state, find all its neighbors. Pick a random neighbor, if that neighbor improves the solution, we move in that direction, if that neighbor does not improve the solution, we generate a random real number between 0 and 1, if the number is within a certain range (calculated using temperature) we move in that direction, else we pick another neighbor randomly and repeat the process. Args: search_prob: The search state at the start. find_max: If True, the algorithm should find the minimum else the minimum. max_x, min_x, max_y, min_y: the maximum and minimum bounds of x and y. visualization: If True, a matplotlib graph is displayed. start_temperate: the initial temperate of the system when the program starts. rate_of_decrease: the rate at which the temperate decreases in each iteration. threshold_temp: the threshold temperature below which we end the search Returns a search state having the maximum (or minimum) score. """ search_end = False current_state = search_prob current_temp = start_temperate scores = [] iterations = 0 best_state = None while not search_end: current_score = current_state.score() if best_state is None or current_score > best_state.score(): best_state = current_state scores.append(current_score) iterations += 1 next_state = None neighbors = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to index = random.randint(0, len(neighbors) - 1) # picking a random neighbor picked_neighbor = neighbors.pop(index) change = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: change = change * -1 # in case we are finding minimum if change > 0: # improves the solution next_state = picked_neighbor else: probability = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability next_state = picked_neighbor current_temp = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor search_end = True else: current_state = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(iterations), scores) plt.xlabel("Iterations") plt.ylabel("Function values") plt.show() return best_state if __name__ == "__main__": def test_f1(x, y): return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1) local_min = simulated_annealing( prob, find_max=False, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " f"and 50 > y > - 5 found via hill climbing: {local_min.score()}" ) # starting the problem with initial coordinates (12, 47) prob = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_f1) local_min = simulated_annealing( prob, find_max=True, max_x=100, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " f"and 50 > y > - 5 found via hill climbing: {local_min.score()}" ) def test_f2(x, y): return (3 * x**2) - (6 * y) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) local_min = simulated_annealing(prob, find_max=False, visualization=True) print( "The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: " f"{local_min.score()}" ) prob = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_f1) local_min = simulated_annealing(prob, find_max=True, visualization=True) print( "The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: " f"{local_min.score()}" )
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
""" A Stack using a linked list like structure """ from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar T = TypeVar("T") class Node(Generic[T]): def __init__(self, data: T): self.data = data self.next: Node[T] | None = None def __str__(self) -> str: return f"{self.data}" class LinkedStack(Generic[T]): """ Linked List Stack implementing push (to top), pop (from top) and is_empty >>> stack = LinkedStack() >>> stack.is_empty() True >>> stack.push(5) >>> stack.push(9) >>> stack.push('python') >>> stack.is_empty() False >>> stack.pop() 'python' >>> stack.push('algorithms') >>> stack.pop() 'algorithms' >>> stack.pop() 9 >>> stack.pop() 5 >>> stack.is_empty() True >>> stack.pop() Traceback (most recent call last): ... IndexError: pop from empty stack """ def __init__(self) -> None: self.top: Node[T] | None = None def __iter__(self) -> Iterator[T]: node = self.top while node: yield node.data node = node.next def __str__(self) -> str: """ >>> stack = LinkedStack() >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> str(stack) 'a->b->c' """ return "->".join([str(item) for item in self]) def __len__(self) -> int: """ >>> stack = LinkedStack() >>> len(stack) == 0 True >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> len(stack) == 3 True """ return len(tuple(iter(self))) def is_empty(self) -> bool: """ >>> stack = LinkedStack() >>> stack.is_empty() True >>> stack.push(1) >>> stack.is_empty() False """ return self.top is None def push(self, item: T) -> None: """ >>> stack = LinkedStack() >>> stack.push("Python") >>> stack.push("Java") >>> stack.push("C") >>> str(stack) 'C->Java->Python' """ node = Node(item) if not self.is_empty(): node.next = self.top self.top = node def pop(self) -> T: """ >>> stack = LinkedStack() >>> stack.pop() Traceback (most recent call last): ... IndexError: pop from empty stack >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> stack.pop() == 'a' True >>> stack.pop() == 'b' True >>> stack.pop() == 'c' True """ if self.is_empty(): raise IndexError("pop from empty stack") assert isinstance(self.top, Node) pop_node = self.top self.top = self.top.next return pop_node.data def peek(self) -> T: """ >>> stack = LinkedStack() >>> stack.push("Java") >>> stack.push("C") >>> stack.push("Python") >>> stack.peek() 'Python' """ if self.is_empty(): raise IndexError("peek from empty stack") assert self.top is not None return self.top.data def clear(self) -> None: """ >>> stack = LinkedStack() >>> stack.push("Java") >>> stack.push("C") >>> stack.push("Python") >>> str(stack) 'Python->C->Java' >>> stack.clear() >>> len(stack) == 0 True """ self.top = None if __name__ == "__main__": from doctest import testmod testmod()
""" A Stack using a linked list like structure """ from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar T = TypeVar("T") class Node(Generic[T]): def __init__(self, data: T): self.data = data self.next: Node[T] | None = None def __str__(self) -> str: return f"{self.data}" class LinkedStack(Generic[T]): """ Linked List Stack implementing push (to top), pop (from top) and is_empty >>> stack = LinkedStack() >>> stack.is_empty() True >>> stack.push(5) >>> stack.push(9) >>> stack.push('python') >>> stack.is_empty() False >>> stack.pop() 'python' >>> stack.push('algorithms') >>> stack.pop() 'algorithms' >>> stack.pop() 9 >>> stack.pop() 5 >>> stack.is_empty() True >>> stack.pop() Traceback (most recent call last): ... IndexError: pop from empty stack """ def __init__(self) -> None: self.top: Node[T] | None = None def __iter__(self) -> Iterator[T]: node = self.top while node: yield node.data node = node.next def __str__(self) -> str: """ >>> stack = LinkedStack() >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> str(stack) 'a->b->c' """ return "->".join([str(item) for item in self]) def __len__(self) -> int: """ >>> stack = LinkedStack() >>> len(stack) == 0 True >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> len(stack) == 3 True """ return len(tuple(iter(self))) def is_empty(self) -> bool: """ >>> stack = LinkedStack() >>> stack.is_empty() True >>> stack.push(1) >>> stack.is_empty() False """ return self.top is None def push(self, item: T) -> None: """ >>> stack = LinkedStack() >>> stack.push("Python") >>> stack.push("Java") >>> stack.push("C") >>> str(stack) 'C->Java->Python' """ node = Node(item) if not self.is_empty(): node.next = self.top self.top = node def pop(self) -> T: """ >>> stack = LinkedStack() >>> stack.pop() Traceback (most recent call last): ... IndexError: pop from empty stack >>> stack.push("c") >>> stack.push("b") >>> stack.push("a") >>> stack.pop() == 'a' True >>> stack.pop() == 'b' True >>> stack.pop() == 'c' True """ if self.is_empty(): raise IndexError("pop from empty stack") assert isinstance(self.top, Node) pop_node = self.top self.top = self.top.next return pop_node.data def peek(self) -> T: """ >>> stack = LinkedStack() >>> stack.push("Java") >>> stack.push("C") >>> stack.push("Python") >>> stack.peek() 'Python' """ if self.is_empty(): raise IndexError("peek from empty stack") assert self.top is not None return self.top.data def clear(self) -> None: """ >>> stack = LinkedStack() >>> stack.push("Java") >>> stack.push("C") >>> stack.push("Python") >>> str(stack) 'Python->C->Java' >>> stack.clear() >>> len(stack) == 0 True """ self.top = None if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
""" Program to encode and decode Baconian or Bacon's Cipher Wikipedia reference : https://en.wikipedia.org/wiki/Bacon%27s_cipher """ encode_dict = { "a": "AAAAA", "b": "AAAAB", "c": "AAABA", "d": "AAABB", "e": "AABAA", "f": "AABAB", "g": "AABBA", "h": "AABBB", "i": "ABAAA", "j": "BBBAA", "k": "ABAAB", "l": "ABABA", "m": "ABABB", "n": "ABBAA", "o": "ABBAB", "p": "ABBBA", "q": "ABBBB", "r": "BAAAA", "s": "BAAAB", "t": "BAABA", "u": "BAABB", "v": "BBBAB", "w": "BABAA", "x": "BABAB", "y": "BABBA", "z": "BABBB", " ": " ", } decode_dict = {value: key for key, value in encode_dict.items()} def encode(word: str) -> str: """ Encodes to Baconian cipher >>> encode("hello") 'AABBBAABAAABABAABABAABBAB' >>> encode("hello world") 'AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB' >>> encode("hello world!") Traceback (most recent call last): ... Exception: encode() accepts only letters of the alphabet and spaces """ encoded = "" for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception("encode() accepts only letters of the alphabet and spaces") return encoded def decode(coded: str) -> str: """ Decodes from Baconian cipher >>> decode("AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB") 'hello world' >>> decode("AABBBAABAAABABAABABAABBAB") 'hello' >>> decode("AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB!") Traceback (most recent call last): ... Exception: decode() accepts only 'A', 'B' and spaces """ if set(coded) - {"A", "B", " "} != set(): raise Exception("decode() accepts only 'A', 'B' and spaces") decoded = "" for word in coded.split(): while len(word) != 0: decoded += decode_dict[word[:5]] word = word[5:] decoded += " " return decoded.strip() if __name__ == "__main__": from doctest import testmod testmod()
""" Program to encode and decode Baconian or Bacon's Cipher Wikipedia reference : https://en.wikipedia.org/wiki/Bacon%27s_cipher """ encode_dict = { "a": "AAAAA", "b": "AAAAB", "c": "AAABA", "d": "AAABB", "e": "AABAA", "f": "AABAB", "g": "AABBA", "h": "AABBB", "i": "ABAAA", "j": "BBBAA", "k": "ABAAB", "l": "ABABA", "m": "ABABB", "n": "ABBAA", "o": "ABBAB", "p": "ABBBA", "q": "ABBBB", "r": "BAAAA", "s": "BAAAB", "t": "BAABA", "u": "BAABB", "v": "BBBAB", "w": "BABAA", "x": "BABAB", "y": "BABBA", "z": "BABBB", " ": " ", } decode_dict = {value: key for key, value in encode_dict.items()} def encode(word: str) -> str: """ Encodes to Baconian cipher >>> encode("hello") 'AABBBAABAAABABAABABAABBAB' >>> encode("hello world") 'AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB' >>> encode("hello world!") Traceback (most recent call last): ... Exception: encode() accepts only letters of the alphabet and spaces """ encoded = "" for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception("encode() accepts only letters of the alphabet and spaces") return encoded def decode(coded: str) -> str: """ Decodes from Baconian cipher >>> decode("AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB") 'hello world' >>> decode("AABBBAABAAABABAABABAABBAB") 'hello' >>> decode("AABBBAABAAABABAABABAABBAB BABAAABBABBAAAAABABAAAABB!") Traceback (most recent call last): ... Exception: decode() accepts only 'A', 'B' and spaces """ if set(coded) - {"A", "B", " "} != set(): raise Exception("decode() accepts only 'A', 'B' and spaces") decoded = "" for word in coded.split(): while len(word) != 0: decoded += decode_dict[word[:5]] word = word[5:] decoded += " " return decoded.strip() if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
from __future__ import annotations from string import ascii_letters def encrypt(input_string: str, key: int, alphabet: str | None = None) -> str: """ encrypt ======= Encodes a given string with the caesar cipher and returns the encoded message Parameters: ----------- * input_string: the plain-text that needs to be encoded * key: the number of letters to shift the message by Optional: * alphabet (None): the alphabet used to encode the cipher, if not specified, the standard english alphabet with upper and lowercase letters is used Returns: * A string containing the encoded cipher-text More on the caesar cipher ========================= The caesar cipher is named after Julius Caesar who used it when sending secret military messages to his troops. This is a simple substitution cipher where every character in the plain-text is shifted by a certain number known as the "key" or "shift". Example: Say we have the following message: "Hello, captain" And our alphabet is made up of lower and uppercase letters: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" And our shift is "2" We can then encode the message, one letter at a time. "H" would become "J", since "J" is two letters away, and so on. If the shift is ever two large, or our letter is at the end of the alphabet, we just start at the beginning ("Z" would shift to "a" then "b" and so on). Our final message would be "Jgnnq, ecrvckp" Further reading =============== * https://en.m.wikipedia.org/wiki/Caesar_cipher Doctests ======== >>> encrypt('The quick brown fox jumps over the lazy dog', 8) 'bpm yCqks jzwEv nwF rCuxA wDmz Bpm tiHG lwo' >>> encrypt('A very large key', 8000) 's nWjq dSjYW cWq' >>> encrypt('a lowercase alphabet', 5, 'abcdefghijklmnopqrstuvwxyz') 'f qtbjwhfxj fqumfgjy' """ # Set default alphabet to lower and upper case english chars alpha = alphabet or ascii_letters # The final result string result = "" for character in input_string: if character not in alpha: # Append without encryption if character is not in the alphabet result += character else: # Get the index of the new key and make sure it isn't too large new_key = (alpha.index(character) + key) % len(alpha) # Append the encoded character to the alphabet result += alpha[new_key] return result def decrypt(input_string: str, key: int, alphabet: str | None = None) -> str: """ decrypt ======= Decodes a given string of cipher-text and returns the decoded plain-text Parameters: ----------- * input_string: the cipher-text that needs to be decoded * key: the number of letters to shift the message backwards by to decode Optional: * alphabet (None): the alphabet used to decode the cipher, if not specified, the standard english alphabet with upper and lowercase letters is used Returns: * A string containing the decoded plain-text More on the caesar cipher ========================= The caesar cipher is named after Julius Caesar who used it when sending secret military messages to his troops. This is a simple substitution cipher where very character in the plain-text is shifted by a certain number known as the "key" or "shift". Please keep in mind, here we will be focused on decryption. Example: Say we have the following cipher-text: "Jgnnq, ecrvckp" And our alphabet is made up of lower and uppercase letters: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" And our shift is "2" To decode the message, we would do the same thing as encoding, but in reverse. The first letter, "J" would become "H" (remember: we are decoding) because "H" is two letters in reverse (to the left) of "J". We would continue doing this. A letter like "a" would shift back to the end of the alphabet, and would become "Z" or "Y" and so on. Our final message would be "Hello, captain" Further reading =============== * https://en.m.wikipedia.org/wiki/Caesar_cipher Doctests ======== >>> decrypt('bpm yCqks jzwEv nwF rCuxA wDmz Bpm tiHG lwo', 8) 'The quick brown fox jumps over the lazy dog' >>> decrypt('s nWjq dSjYW cWq', 8000) 'A very large key' >>> decrypt('f qtbjwhfxj fqumfgjy', 5, 'abcdefghijklmnopqrstuvwxyz') 'a lowercase alphabet' """ # Turn on decode mode by making the key negative key *= -1 return encrypt(input_string, key, alphabet) def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str]: """ brute_force =========== Returns all the possible combinations of keys and the decoded strings in the form of a dictionary Parameters: ----------- * input_string: the cipher-text that needs to be used during brute-force Optional: * alphabet: (None): the alphabet used to decode the cipher, if not specified, the standard english alphabet with upper and lowercase letters is used More about brute force ====================== Brute force is when a person intercepts a message or password, not knowing the key and tries every single combination. This is easy with the caesar cipher since there are only all the letters in the alphabet. The more complex the cipher, the larger amount of time it will take to do brute force Ex: Say we have a 5 letter alphabet (abcde), for simplicity and we intercepted the following message: "dbc" we could then just write out every combination: ecd... and so on, until we reach a combination that makes sense: "cab" Further reading =============== * https://en.wikipedia.org/wiki/Brute_force Doctests ======== >>> brute_force("jFyuMy xIH'N vLONy zILwy Gy!")[20] "Please don't brute force me!" >>> brute_force(1) Traceback (most recent call last): TypeError: 'int' object is not iterable """ # Set default alphabet to lower and upper case english chars alpha = alphabet or ascii_letters # To store data on all the combinations brute_force_data = {} # Cycle through each combination for key in range(1, len(alpha) + 1): # Decrypt the message and store the result in the data brute_force_data[key] = decrypt(input_string, key, alpha) return brute_force_data if __name__ == "__main__": while True: print(f'\n{"-" * 10}\n Menu\n{"-" * 10}') print(*["1.Encrypt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep="\n") # get user input choice = input("\nWhat would you like to do?: ").strip() or "4" # run functions based on what the user chose if choice not in ("1", "2", "3", "4"): print("Invalid choice, please enter a valid choice") elif choice == "1": input_string = input("Please enter the string to be encrypted: ") key = int(input("Please enter off-set: ").strip()) print(encrypt(input_string, key)) elif choice == "2": input_string = input("Please enter the string to be decrypted: ") key = int(input("Please enter off-set: ").strip()) print(decrypt(input_string, key)) elif choice == "3": input_string = input("Please enter the string to be decrypted: ") brute_force_data = brute_force(input_string) for key, value in brute_force_data.items(): print(f"Key: {key} | Message: {value}") elif choice == "4": print("Goodbye.") break
from __future__ import annotations from string import ascii_letters def encrypt(input_string: str, key: int, alphabet: str | None = None) -> str: """ encrypt ======= Encodes a given string with the caesar cipher and returns the encoded message Parameters: ----------- * input_string: the plain-text that needs to be encoded * key: the number of letters to shift the message by Optional: * alphabet (None): the alphabet used to encode the cipher, if not specified, the standard english alphabet with upper and lowercase letters is used Returns: * A string containing the encoded cipher-text More on the caesar cipher ========================= The caesar cipher is named after Julius Caesar who used it when sending secret military messages to his troops. This is a simple substitution cipher where every character in the plain-text is shifted by a certain number known as the "key" or "shift". Example: Say we have the following message: "Hello, captain" And our alphabet is made up of lower and uppercase letters: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" And our shift is "2" We can then encode the message, one letter at a time. "H" would become "J", since "J" is two letters away, and so on. If the shift is ever two large, or our letter is at the end of the alphabet, we just start at the beginning ("Z" would shift to "a" then "b" and so on). Our final message would be "Jgnnq, ecrvckp" Further reading =============== * https://en.m.wikipedia.org/wiki/Caesar_cipher Doctests ======== >>> encrypt('The quick brown fox jumps over the lazy dog', 8) 'bpm yCqks jzwEv nwF rCuxA wDmz Bpm tiHG lwo' >>> encrypt('A very large key', 8000) 's nWjq dSjYW cWq' >>> encrypt('a lowercase alphabet', 5, 'abcdefghijklmnopqrstuvwxyz') 'f qtbjwhfxj fqumfgjy' """ # Set default alphabet to lower and upper case english chars alpha = alphabet or ascii_letters # The final result string result = "" for character in input_string: if character not in alpha: # Append without encryption if character is not in the alphabet result += character else: # Get the index of the new key and make sure it isn't too large new_key = (alpha.index(character) + key) % len(alpha) # Append the encoded character to the alphabet result += alpha[new_key] return result def decrypt(input_string: str, key: int, alphabet: str | None = None) -> str: """ decrypt ======= Decodes a given string of cipher-text and returns the decoded plain-text Parameters: ----------- * input_string: the cipher-text that needs to be decoded * key: the number of letters to shift the message backwards by to decode Optional: * alphabet (None): the alphabet used to decode the cipher, if not specified, the standard english alphabet with upper and lowercase letters is used Returns: * A string containing the decoded plain-text More on the caesar cipher ========================= The caesar cipher is named after Julius Caesar who used it when sending secret military messages to his troops. This is a simple substitution cipher where very character in the plain-text is shifted by a certain number known as the "key" or "shift". Please keep in mind, here we will be focused on decryption. Example: Say we have the following cipher-text: "Jgnnq, ecrvckp" And our alphabet is made up of lower and uppercase letters: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" And our shift is "2" To decode the message, we would do the same thing as encoding, but in reverse. The first letter, "J" would become "H" (remember: we are decoding) because "H" is two letters in reverse (to the left) of "J". We would continue doing this. A letter like "a" would shift back to the end of the alphabet, and would become "Z" or "Y" and so on. Our final message would be "Hello, captain" Further reading =============== * https://en.m.wikipedia.org/wiki/Caesar_cipher Doctests ======== >>> decrypt('bpm yCqks jzwEv nwF rCuxA wDmz Bpm tiHG lwo', 8) 'The quick brown fox jumps over the lazy dog' >>> decrypt('s nWjq dSjYW cWq', 8000) 'A very large key' >>> decrypt('f qtbjwhfxj fqumfgjy', 5, 'abcdefghijklmnopqrstuvwxyz') 'a lowercase alphabet' """ # Turn on decode mode by making the key negative key *= -1 return encrypt(input_string, key, alphabet) def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str]: """ brute_force =========== Returns all the possible combinations of keys and the decoded strings in the form of a dictionary Parameters: ----------- * input_string: the cipher-text that needs to be used during brute-force Optional: * alphabet: (None): the alphabet used to decode the cipher, if not specified, the standard english alphabet with upper and lowercase letters is used More about brute force ====================== Brute force is when a person intercepts a message or password, not knowing the key and tries every single combination. This is easy with the caesar cipher since there are only all the letters in the alphabet. The more complex the cipher, the larger amount of time it will take to do brute force Ex: Say we have a 5 letter alphabet (abcde), for simplicity and we intercepted the following message: "dbc" we could then just write out every combination: ecd... and so on, until we reach a combination that makes sense: "cab" Further reading =============== * https://en.wikipedia.org/wiki/Brute_force Doctests ======== >>> brute_force("jFyuMy xIH'N vLONy zILwy Gy!")[20] "Please don't brute force me!" >>> brute_force(1) Traceback (most recent call last): TypeError: 'int' object is not iterable """ # Set default alphabet to lower and upper case english chars alpha = alphabet or ascii_letters # To store data on all the combinations brute_force_data = {} # Cycle through each combination for key in range(1, len(alpha) + 1): # Decrypt the message and store the result in the data brute_force_data[key] = decrypt(input_string, key, alpha) return brute_force_data if __name__ == "__main__": while True: print(f'\n{"-" * 10}\n Menu\n{"-" * 10}') print(*["1.Encrypt", "2.Decrypt", "3.BruteForce", "4.Quit"], sep="\n") # get user input choice = input("\nWhat would you like to do?: ").strip() or "4" # run functions based on what the user chose if choice not in ("1", "2", "3", "4"): print("Invalid choice, please enter a valid choice") elif choice == "1": input_string = input("Please enter the string to be encrypted: ") key = int(input("Please enter off-set: ").strip()) print(encrypt(input_string, key)) elif choice == "2": input_string = input("Please enter the string to be decrypted: ") key = int(input("Please enter off-set: ").strip()) print(decrypt(input_string, key)) elif choice == "3": input_string = input("Please enter the string to be decrypted: ") brute_force_data = brute_force(input_string) for key, value in brute_force_data.items(): print(f"Key: {key} | Message: {value}") elif choice == "4": print("Goodbye.") break
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
from __future__ import annotations def solve_maze(maze: list[list[int]]) -> bool: """ This method solves the "rat in maze" problem. In this problem we have some n by n matrix, a start point and an end point. We want to go from the start to the end. In this matrix zeroes represent walls and ones paths we can use. Parameters : maze(2D matrix) : maze Returns: Return: True if the maze has a solution or False if it does not. >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [1, 0, 1, 0, 1], ... [0, 0, 1, 0, 0], ... [1, 0, 0, 1, 0]] >>> solve_maze(maze) [1, 0, 0, 0, 0] [1, 1, 1, 1, 0] [0, 0, 0, 1, 0] [0, 0, 0, 1, 1] [0, 0, 0, 0, 1] True >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0]] >>> solve_maze(maze) [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 1, 1, 1, 1] True >>> maze = [[0, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze) [1, 1, 1] [0, 0, 1] [0, 0, 1] True >>> maze = [[0, 1, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze) No solution exists! False >>> maze = [[0, 1], ... [1, 0]] >>> solve_maze(maze) No solution exists! False """ size = len(maze) # We need to create solution object to save path. solutions = [[0 for _ in range(size)] for _ in range(size)] solved = run_maze(maze, 0, 0, solutions) if solved: print("\n".join(str(row) for row in solutions)) else: print("No solution exists!") return solved def run_maze(maze: list[list[int]], i: int, j: int, solutions: list[list[int]]) -> bool: """ This method is recursive starting from (i, j) and going in one of four directions: up, down, left, right. If a path is found to destination it returns True otherwise it returns False. Parameters: maze(2D matrix) : maze i, j : coordinates of matrix solutions(2D matrix) : solutions Returns: Boolean if path is found True, Otherwise False. """ size = len(maze) # Final check point. if i == j == (size - 1): solutions[i][j] = 1 return True lower_flag = (not i < 0) and (not j < 0) # Check lower bounds upper_flag = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. block_flag = (not solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited solutions[i][j] = 1 # check for directions if ( run_maze(maze, i + 1, j, solutions) or run_maze(maze, i, j + 1, solutions) or run_maze(maze, i - 1, j, solutions) or run_maze(maze, i, j - 1, solutions) ): return True solutions[i][j] = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
from __future__ import annotations def solve_maze(maze: list[list[int]]) -> bool: """ This method solves the "rat in maze" problem. In this problem we have some n by n matrix, a start point and an end point. We want to go from the start to the end. In this matrix zeroes represent walls and ones paths we can use. Parameters : maze(2D matrix) : maze Returns: Return: True if the maze has a solution or False if it does not. >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [1, 0, 1, 0, 1], ... [0, 0, 1, 0, 0], ... [1, 0, 0, 1, 0]] >>> solve_maze(maze) [1, 0, 0, 0, 0] [1, 1, 1, 1, 0] [0, 0, 0, 1, 0] [0, 0, 0, 1, 1] [0, 0, 0, 0, 1] True >>> maze = [[0, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0]] >>> solve_maze(maze) [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 0, 0, 0, 0] [1, 1, 1, 1, 1] True >>> maze = [[0, 0, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze) [1, 1, 1] [0, 0, 1] [0, 0, 1] True >>> maze = [[0, 1, 0], ... [0, 1, 0], ... [1, 0, 0]] >>> solve_maze(maze) No solution exists! False >>> maze = [[0, 1], ... [1, 0]] >>> solve_maze(maze) No solution exists! False """ size = len(maze) # We need to create solution object to save path. solutions = [[0 for _ in range(size)] for _ in range(size)] solved = run_maze(maze, 0, 0, solutions) if solved: print("\n".join(str(row) for row in solutions)) else: print("No solution exists!") return solved def run_maze(maze: list[list[int]], i: int, j: int, solutions: list[list[int]]) -> bool: """ This method is recursive starting from (i, j) and going in one of four directions: up, down, left, right. If a path is found to destination it returns True otherwise it returns False. Parameters: maze(2D matrix) : maze i, j : coordinates of matrix solutions(2D matrix) : solutions Returns: Boolean if path is found True, Otherwise False. """ size = len(maze) # Final check point. if i == j == (size - 1): solutions[i][j] = 1 return True lower_flag = (not i < 0) and (not j < 0) # Check lower bounds upper_flag = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. block_flag = (not solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited solutions[i][j] = 1 # check for directions if ( run_maze(maze, i + 1, j, solutions) or run_maze(maze, i, j + 1, solutions) or run_maze(maze, i - 1, j, solutions) or run_maze(maze, i, j - 1, solutions) ): return True solutions[i][j] = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
def multiplicative_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> multiplicative_persistence(217) 2 >>> multiplicative_persistence(-1) Traceback (most recent call last): ... ValueError: multiplicative_persistence() does not accept negative values >>> multiplicative_persistence("long number") Traceback (most recent call last): ... ValueError: multiplicative_persistence() only accepts integral values """ if not isinstance(num, int): raise ValueError("multiplicative_persistence() only accepts integral values") if num < 0: raise ValueError("multiplicative_persistence() does not accept negative values") steps = 0 num_string = str(num) while len(num_string) != 1: numbers = [int(i) for i in num_string] total = 1 for i in range(0, len(numbers)): total *= numbers[i] num_string = str(total) steps += 1 return steps def additive_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> additive_persistence(199) 3 >>> additive_persistence(-1) Traceback (most recent call last): ... ValueError: additive_persistence() does not accept negative values >>> additive_persistence("long number") Traceback (most recent call last): ... ValueError: additive_persistence() only accepts integral values """ if not isinstance(num, int): raise ValueError("additive_persistence() only accepts integral values") if num < 0: raise ValueError("additive_persistence() does not accept negative values") steps = 0 num_string = str(num) while len(num_string) != 1: numbers = [int(i) for i in num_string] total = 0 for i in range(0, len(numbers)): total += numbers[i] num_string = str(total) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
def multiplicative_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> multiplicative_persistence(217) 2 >>> multiplicative_persistence(-1) Traceback (most recent call last): ... ValueError: multiplicative_persistence() does not accept negative values >>> multiplicative_persistence("long number") Traceback (most recent call last): ... ValueError: multiplicative_persistence() only accepts integral values """ if not isinstance(num, int): raise ValueError("multiplicative_persistence() only accepts integral values") if num < 0: raise ValueError("multiplicative_persistence() does not accept negative values") steps = 0 num_string = str(num) while len(num_string) != 1: numbers = [int(i) for i in num_string] total = 1 for i in range(0, len(numbers)): total *= numbers[i] num_string = str(total) steps += 1 return steps def additive_persistence(num: int) -> int: """ Return the persistence of a given number. https://en.wikipedia.org/wiki/Persistence_of_a_number >>> additive_persistence(199) 3 >>> additive_persistence(-1) Traceback (most recent call last): ... ValueError: additive_persistence() does not accept negative values >>> additive_persistence("long number") Traceback (most recent call last): ... ValueError: additive_persistence() only accepts integral values """ if not isinstance(num, int): raise ValueError("additive_persistence() only accepts integral values") if num < 0: raise ValueError("additive_persistence() does not accept negative values") steps = 0 num_string = str(num) while len(num_string) != 1: numbers = [int(i) for i in num_string] total = 0 for i in range(0, len(numbers)): total += numbers[i] num_string = str(total) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
""" Algorithm that merges two sorted linked lists into one sorted linked list. """ from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1) test_data_even = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class Node: data: int next_node: Node | None class SortedLinkedList: def __init__(self, ints: Iterable[int]) -> None: self.head: Node | None = None for i in sorted(ints, reverse=True): self.head = Node(i, self.head) def __iter__(self) -> Iterator[int]: """ >>> tuple(SortedLinkedList(test_data_odd)) == tuple(sorted(test_data_odd)) True >>> tuple(SortedLinkedList(test_data_even)) == tuple(sorted(test_data_even)) True """ node = self.head while node: yield node.data node = node.next_node def __len__(self) -> int: """ >>> for i in range(3): ... len(SortedLinkedList(range(i))) == i True True True >>> len(SortedLinkedList(test_data_odd)) 8 """ return sum(1 for _ in self) def __str__(self) -> str: """ >>> str(SortedLinkedList([])) '' >>> str(SortedLinkedList(test_data_odd)) '-11 -> -1 -> 0 -> 1 -> 3 -> 5 -> 7 -> 9' >>> str(SortedLinkedList(test_data_even)) '-2 -> 0 -> 2 -> 3 -> 4 -> 6 -> 8 -> 10' """ return " -> ".join([str(node) for node in self]) def merge_lists( sll_one: SortedLinkedList, sll_two: SortedLinkedList ) -> SortedLinkedList: """ >>> SSL = SortedLinkedList >>> merged = merge_lists(SSL(test_data_odd), SSL(test_data_even)) >>> len(merged) 16 >>> str(merged) '-11 -> -2 -> -1 -> 0 -> 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10' >>> list(merged) == list(sorted(test_data_odd + test_data_even)) True """ return SortedLinkedList(list(sll_one) + list(sll_two)) if __name__ == "__main__": import doctest doctest.testmod() SSL = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
""" Algorithm that merges two sorted linked lists into one sorted linked list. """ from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass test_data_odd = (3, 9, -11, 0, 7, 5, 1, -1) test_data_even = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class Node: data: int next_node: Node | None class SortedLinkedList: def __init__(self, ints: Iterable[int]) -> None: self.head: Node | None = None for i in sorted(ints, reverse=True): self.head = Node(i, self.head) def __iter__(self) -> Iterator[int]: """ >>> tuple(SortedLinkedList(test_data_odd)) == tuple(sorted(test_data_odd)) True >>> tuple(SortedLinkedList(test_data_even)) == tuple(sorted(test_data_even)) True """ node = self.head while node: yield node.data node = node.next_node def __len__(self) -> int: """ >>> for i in range(3): ... len(SortedLinkedList(range(i))) == i True True True >>> len(SortedLinkedList(test_data_odd)) 8 """ return sum(1 for _ in self) def __str__(self) -> str: """ >>> str(SortedLinkedList([])) '' >>> str(SortedLinkedList(test_data_odd)) '-11 -> -1 -> 0 -> 1 -> 3 -> 5 -> 7 -> 9' >>> str(SortedLinkedList(test_data_even)) '-2 -> 0 -> 2 -> 3 -> 4 -> 6 -> 8 -> 10' """ return " -> ".join([str(node) for node in self]) def merge_lists( sll_one: SortedLinkedList, sll_two: SortedLinkedList ) -> SortedLinkedList: """ >>> SSL = SortedLinkedList >>> merged = merge_lists(SSL(test_data_odd), SSL(test_data_even)) >>> len(merged) 16 >>> str(merged) '-11 -> -2 -> -1 -> 0 -> 0 -> 1 -> 2 -> 3 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10' >>> list(merged) == list(sorted(test_data_odd + test_data_even)) True """ return SortedLinkedList(list(sll_one) + list(sll_two)) if __name__ == "__main__": import doctest doctest.testmod() SSL = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
""" Isolate the Decimal part of a Number https://stackoverflow.com/questions/3886402/how-to-get-numbers-after-decimal-point """ def decimal_isolate(number: float, digit_amount: int) -> float: """ Isolates the decimal part of a number. If digitAmount > 0 round to that decimal place, else print the entire decimal. >>> decimal_isolate(1.53, 0) 0.53 >>> decimal_isolate(35.345, 1) 0.3 >>> decimal_isolate(35.345, 2) 0.34 >>> decimal_isolate(35.345, 3) 0.345 >>> decimal_isolate(-14.789, 3) -0.789 >>> decimal_isolate(0, 2) 0 >>> decimal_isolate(-14.123, 1) -0.1 >>> decimal_isolate(-14.123, 2) -0.12 >>> decimal_isolate(-14.123, 3) -0.123 """ if digit_amount > 0: return round(number - int(number), digit_amount) return number - int(number) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
""" Isolate the Decimal part of a Number https://stackoverflow.com/questions/3886402/how-to-get-numbers-after-decimal-point """ def decimal_isolate(number: float, digit_amount: int) -> float: """ Isolates the decimal part of a number. If digitAmount > 0 round to that decimal place, else print the entire decimal. >>> decimal_isolate(1.53, 0) 0.53 >>> decimal_isolate(35.345, 1) 0.3 >>> decimal_isolate(35.345, 2) 0.34 >>> decimal_isolate(35.345, 3) 0.345 >>> decimal_isolate(-14.789, 3) -0.789 >>> decimal_isolate(0, 2) 0 >>> decimal_isolate(-14.123, 1) -0.1 >>> decimal_isolate(-14.123, 2) -0.12 >>> decimal_isolate(-14.123, 3) -0.123 """ if digit_amount > 0: return round(number - int(number), digit_amount) return number - int(number) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
""" Three distinct points are plotted at random on a Cartesian plane, for which -1000 ≤ x, y ≤ 1000, such that a triangle is formed. Consider the following two triangles: A(-340,495), B(-153,-910), C(835,-947) X(-175,41), Y(-421,-714), Z(574,-645) It can be verified that triangle ABC contains the origin, whereas triangle XYZ does not. Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the coordinates of one thousand "random" triangles, find the number of triangles for which the interior contains the origin. NOTE: The first two examples in the file represent the triangles in the example given above. """ from __future__ import annotations from pathlib import Path def vector_product(point1: tuple[int, int], point2: tuple[int, int]) -> int: """ Return the 2-d vector product of two vectors. >>> vector_product((1, 2), (-5, 0)) 10 >>> vector_product((3, 1), (6, 10)) 24 """ return point1[0] * point2[1] - point1[1] * point2[0] def contains_origin(x1: int, y1: int, x2: int, y2: int, x3: int, y3: int) -> bool: """ Check if the triangle given by the points A(x1, y1), B(x2, y2), C(x3, y3) contains the origin. >>> contains_origin(-340, 495, -153, -910, 835, -947) True >>> contains_origin(-175, 41, -421, -714, 574, -645) False """ point_a: tuple[int, int] = (x1, y1) point_a_to_b: tuple[int, int] = (x2 - x1, y2 - y1) point_a_to_c: tuple[int, int] = (x3 - x1, y3 - y1) a: float = -vector_product(point_a, point_a_to_b) / vector_product( point_a_to_c, point_a_to_b ) b: float = +vector_product(point_a, point_a_to_c) / vector_product( point_a_to_c, point_a_to_b ) return a > 0 and b > 0 and a + b < 1 def solution(filename: str = "p102_triangles.txt") -> int: """ Find the number of triangles whose interior contains the origin. >>> solution("test_triangles.txt") 1 """ data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8") triangles: list[list[int]] = [] for line in data.strip().split("\n"): triangles.append([int(number) for number in line.split(",")]) ret: int = 0 triangle: list[int] for triangle in triangles: ret += contains_origin(*triangle) return ret if __name__ == "__main__": print(f"{solution() = }")
""" Three distinct points are plotted at random on a Cartesian plane, for which -1000 ≤ x, y ≤ 1000, such that a triangle is formed. Consider the following two triangles: A(-340,495), B(-153,-910), C(835,-947) X(-175,41), Y(-421,-714), Z(574,-645) It can be verified that triangle ABC contains the origin, whereas triangle XYZ does not. Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the coordinates of one thousand "random" triangles, find the number of triangles for which the interior contains the origin. NOTE: The first two examples in the file represent the triangles in the example given above. """ from __future__ import annotations from pathlib import Path def vector_product(point1: tuple[int, int], point2: tuple[int, int]) -> int: """ Return the 2-d vector product of two vectors. >>> vector_product((1, 2), (-5, 0)) 10 >>> vector_product((3, 1), (6, 10)) 24 """ return point1[0] * point2[1] - point1[1] * point2[0] def contains_origin(x1: int, y1: int, x2: int, y2: int, x3: int, y3: int) -> bool: """ Check if the triangle given by the points A(x1, y1), B(x2, y2), C(x3, y3) contains the origin. >>> contains_origin(-340, 495, -153, -910, 835, -947) True >>> contains_origin(-175, 41, -421, -714, 574, -645) False """ point_a: tuple[int, int] = (x1, y1) point_a_to_b: tuple[int, int] = (x2 - x1, y2 - y1) point_a_to_c: tuple[int, int] = (x3 - x1, y3 - y1) a: float = -vector_product(point_a, point_a_to_b) / vector_product( point_a_to_c, point_a_to_b ) b: float = +vector_product(point_a, point_a_to_c) / vector_product( point_a_to_c, point_a_to_b ) return a > 0 and b > 0 and a + b < 1 def solution(filename: str = "p102_triangles.txt") -> int: """ Find the number of triangles whose interior contains the origin. >>> solution("test_triangles.txt") 1 """ data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8") triangles: list[list[int]] = [] for line in data.strip().split("\n"): triangles.append([int(number) for number in line.split(",")]) ret: int = 0 triangle: list[int] for triangle in triangles: ret += contains_origin(*triangle) return ret if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
def binary_recursive(decimal: int) -> str: """ Take a positive integer value and return its binary equivalent. >>> binary_recursive(1000) '1111101000' >>> binary_recursive("72") '1001000' >>> binary_recursive("number") Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: 'number' """ decimal = int(decimal) if decimal in (0, 1): # Exit cases for the recursion return str(decimal) div, mod = divmod(decimal, 2) return binary_recursive(div) + str(mod) def main(number: str) -> str: """ Take an integer value and raise ValueError for wrong inputs, call the function above and return the output with prefix "0b" & "-0b" for positive and negative integers respectively. >>> main(0) '0b0' >>> main(40) '0b101000' >>> main(-40) '-0b101000' >>> main(40.8) Traceback (most recent call last): ... ValueError: Input value is not an integer >>> main("forty") Traceback (most recent call last): ... ValueError: Input value is not an integer """ number = str(number).strip() if not number: raise ValueError("No input value was provided") negative = "-" if number.startswith("-") else "" number = number.lstrip("-") if not number.isnumeric(): raise ValueError("Input value is not an integer") return f"{negative}0b{binary_recursive(int(number))}" if __name__ == "__main__": from doctest import testmod testmod()
def binary_recursive(decimal: int) -> str: """ Take a positive integer value and return its binary equivalent. >>> binary_recursive(1000) '1111101000' >>> binary_recursive("72") '1001000' >>> binary_recursive("number") Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: 'number' """ decimal = int(decimal) if decimal in (0, 1): # Exit cases for the recursion return str(decimal) div, mod = divmod(decimal, 2) return binary_recursive(div) + str(mod) def main(number: str) -> str: """ Take an integer value and raise ValueError for wrong inputs, call the function above and return the output with prefix "0b" & "-0b" for positive and negative integers respectively. >>> main(0) '0b0' >>> main(40) '0b101000' >>> main(-40) '-0b101000' >>> main(40.8) Traceback (most recent call last): ... ValueError: Input value is not an integer >>> main("forty") Traceback (most recent call last): ... ValueError: Input value is not an integer """ number = str(number).strip() if not number: raise ValueError("No input value was provided") negative = "-" if number.startswith("-") else "" number = number.lstrip("-") if not number.isnumeric(): raise ValueError("Input value is not an integer") return f"{negative}0b{binary_recursive(int(number))}" if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
""" Finding the peak of a unimodal list using divide and conquer. A unimodal array is defined as follows: array is increasing up to index p, then decreasing afterwards. (for p >= 1) An obvious solution can be performed in O(n), to find the maximum of the array. (From Kleinberg and Tardos. Algorithm Design. Addison Wesley 2006: Chapter 5 Solved Exercise 1) """ from __future__ import annotations def peak(lst: list[int]) -> int: """ Return the peak value of `lst`. >>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1]) 5 >>> peak([1, 10, 9, 8, 7, 6, 5, 4]) 10 >>> peak([1, 9, 8, 7]) 9 >>> peak([1, 2, 3, 4, 5, 6, 7, 0]) 7 >>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2]) 4 """ # middle index m = len(lst) // 2 # choose the middle 3 elements three = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m]) == 2: m -= 1 return peak(lst[m:]) # decreasing else: if len(lst[:m]) == 2: m += 1 return peak(lst[:m]) if __name__ == "__main__": import doctest doctest.testmod()
""" Finding the peak of a unimodal list using divide and conquer. A unimodal array is defined as follows: array is increasing up to index p, then decreasing afterwards. (for p >= 1) An obvious solution can be performed in O(n), to find the maximum of the array. (From Kleinberg and Tardos. Algorithm Design. Addison Wesley 2006: Chapter 5 Solved Exercise 1) """ from __future__ import annotations def peak(lst: list[int]) -> int: """ Return the peak value of `lst`. >>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1]) 5 >>> peak([1, 10, 9, 8, 7, 6, 5, 4]) 10 >>> peak([1, 9, 8, 7]) 9 >>> peak([1, 2, 3, 4, 5, 6, 7, 0]) 7 >>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2]) 4 """ # middle index m = len(lst) // 2 # choose the middle 3 elements three = lst[m - 1 : m + 2] # if middle element is peak if three[1] > three[0] and three[1] > three[2]: return three[1] # if increasing, recurse on right elif three[0] < three[2]: if len(lst[:m]) == 2: m -= 1 return peak(lst[m:]) # decreasing else: if len(lst[:m]) == 2: m += 1 return peak(lst[:m]) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
from __future__ import annotations import requests def get_hackernews_story(story_id: str) -> dict: url = f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(url).json() def hackernews_top_stories(max_stories: int = 10) -> list[dict]: """ Get the top max_stories posts from HackerNews - https://news.ycombinator.com/ """ url = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty" story_ids = requests.get(url).json()[:max_stories] return [get_hackernews_story(story_id) for story_id in story_ids] def hackernews_top_stories_as_markdown(max_stories: int = 10) -> str: stories = hackernews_top_stories(max_stories) return "\n".join("* [{title}]({url})".format(**story) for story in stories) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
from __future__ import annotations import requests def get_hackernews_story(story_id: str) -> dict: url = f"https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty" return requests.get(url).json() def hackernews_top_stories(max_stories: int = 10) -> list[dict]: """ Get the top max_stories posts from HackerNews - https://news.ycombinator.com/ """ url = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty" story_ids = requests.get(url).json()[:max_stories] return [get_hackernews_story(story_id) for story_id in story_ids] def hackernews_top_stories_as_markdown(max_stories: int = 10) -> str: stories = hackernews_top_stories(max_stories) return "\n".join("* [{title}]({url})".format(**story) for story in stories) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
""" https://en.wikipedia.org/wiki/Shellsort#Pseudocode """ def shell_sort(collection): """Pure implementation of shell sort algorithm in Python :param collection: Some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending >>> shell_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> shell_sort([]) [] >>> shell_sort([-2, -5, -45]) [-45, -5, -2] """ # Marcin Ciura's gap sequence gaps = [701, 301, 132, 57, 23, 10, 4, 1] for gap in gaps: for i in range(gap, len(collection)): insert_value = collection[i] j = i while j >= gap and collection[j - gap] > insert_value: collection[j] = collection[j - gap] j -= gap if j != i: collection[j] = insert_value return collection if __name__ == "__main__": from doctest import testmod testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(shell_sort(unsorted))
""" https://en.wikipedia.org/wiki/Shellsort#Pseudocode """ def shell_sort(collection): """Pure implementation of shell sort algorithm in Python :param collection: Some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending >>> shell_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> shell_sort([]) [] >>> shell_sort([-2, -5, -45]) [-45, -5, -2] """ # Marcin Ciura's gap sequence gaps = [701, 301, 132, 57, 23, 10, 4, 1] for gap in gaps: for i in range(gap, len(collection)): insert_value = collection[i] j = i while j >= gap and collection[j - gap] > insert_value: collection[j] = collection[j - gap] j -= gap if j != i: collection[j] = insert_value return collection if __name__ == "__main__": from doctest import testmod testmod() user_input = input("Enter numbers separated by a comma:\n").strip() unsorted = [int(item) for item in user_input.split(",")] print(shell_sort(unsorted))
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
from sys import maxsize def max_sub_array_sum(a: list, size: int = 0): """ >>> max_sub_array_sum([-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7]) -3 """ size = size or len(a) max_so_far = -maxsize - 1 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] max_so_far = max(max_so_far, max_ending_here) max_ending_here = max(max_ending_here, 0) return max_so_far if __name__ == "__main__": a = [-13, -3, -25, -20, 1, -16, -23, -12, -5, -22, -15, -4, -7] print(("Maximum contiguous sum is", max_sub_array_sum(a, len(a))))
from sys import maxsize def max_sub_array_sum(a: list, size: int = 0): """ >>> max_sub_array_sum([-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7]) -3 """ size = size or len(a) max_so_far = -maxsize - 1 max_ending_here = 0 for i in range(0, size): max_ending_here = max_ending_here + a[i] max_so_far = max(max_so_far, max_ending_here) max_ending_here = max(max_ending_here, 0) return max_so_far if __name__ == "__main__": a = [-13, -3, -25, -20, 1, -16, -23, -12, -5, -22, -15, -4, -7] print(("Maximum contiguous sum is", max_sub_array_sum(a, len(a))))
-1
TheAlgorithms/Python
8,802
Dijkstra algorithm with binary grid
This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
linushenkel
"2023-06-07T17:52:08Z"
"2023-06-22T11:49:09Z"
07e68128883b84fb7e342c6bce88863a05fbbf62
5b0890bd833eb85c58fae9afc4984d520e7e2ad6
Dijkstra algorithm with binary grid. This script implements the Dijkstra algorithm on a binary grid. The input grid (matrix) consists of 0s and 1s, where 1 represents a walkable node and 0 represents an obstacle. The algorithm finds the shortest path from a start node to a destination node. The diagonal movement can be allowed or disallowed. This version of the Dijkstra algorithm can be usefull in video game development or in special machine movement.
""" Amicable Numbers Problem 21 Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. """ from math import sqrt def sum_of_divisors(n: int) -> int: total = 0 for i in range(1, int(sqrt(n) + 1)): if n % i == 0 and i != sqrt(n): total += i + n // i elif i == sqrt(n): total += i return total - n def solution(n: int = 10000) -> int: """Returns the sum of all the amicable numbers under n. >>> solution(10000) 31626 >>> solution(5000) 8442 >>> solution(1000) 504 >>> solution(100) 0 >>> solution(50) 0 """ total = sum( i for i in range(1, n) if sum_of_divisors(sum_of_divisors(i)) == i and sum_of_divisors(i) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
""" Amicable Numbers Problem 21 Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. """ from math import sqrt def sum_of_divisors(n: int) -> int: total = 0 for i in range(1, int(sqrt(n) + 1)): if n % i == 0 and i != sqrt(n): total += i + n // i elif i == sqrt(n): total += i return total - n def solution(n: int = 10000) -> int: """Returns the sum of all the amicable numbers under n. >>> solution(10000) 31626 >>> solution(5000) 8442 >>> solution(1000) 504 >>> solution(100) 0 >>> solution(50) 0 """ total = sum( i for i in range(1, n) if sum_of_divisors(sum_of_divisors(i)) == i and sum_of_divisors(i) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
-1