repo_name
stringclasses 1
value | pr_number
int64 4.12k
11.2k
| pr_title
stringlengths 9
107
| pr_description
stringlengths 107
5.48k
| author
stringlengths 4
18
| date_created
unknown | date_merged
unknown | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 118
5.52k
| before_content
stringlengths 0
7.93M
| after_content
stringlengths 0
7.93M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Python 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 | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| [core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
[remote "origin"]
url = https://github.com/TheAlgorithms/Python.git
fetch = +refs/heads/*:refs/remotes/origin/*
gh-resolved = base
[branch "master"]
remote = origin
merge = refs/heads/master
| [core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
[remote "origin"]
url = https://github.com/TheAlgorithms/Python.git
fetch = +refs/heads/*:refs/remotes/origin/*
gh-resolved = base
[branch "master"]
remote = origin
merge = refs/heads/master
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 1: https://projecteuler.net/problem=1
Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def solution(n: int = 1000) -> int:
"""
Returns the sum of all the multiples of 3 or 5 below n.
>>> solution(3)
0
>>> solution(4)
3
>>> solution(10)
23
>>> solution(600)
83700
"""
result = 0
for i in range(n):
if i % 3 == 0:
result += i
elif i % 5 == 0:
result += i
return result
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 1: https://projecteuler.net/problem=1
Multiples of 3 and 5
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def solution(n: int = 1000) -> int:
"""
Returns the sum of all the multiples of 3 or 5 below n.
>>> solution(3)
0
>>> solution(4)
3
>>> solution(10)
23
>>> solution(600)
83700
"""
result = 0
for i in range(n):
if i % 3 == 0:
result += i
elif i % 5 == 0:
result += i
return result
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 75: https://projecteuler.net/problem=75
It turns out that 12 cm is the smallest length of wire that can be bent to form an
integer sided right angle triangle in exactly one way, but there are many more examples.
12 cm: (3,4,5)
24 cm: (6,8,10)
30 cm: (5,12,13)
36 cm: (9,12,15)
40 cm: (8,15,17)
48 cm: (12,16,20)
In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided
right angle triangle, and other lengths allow more than one solution to be found; for
example, using 120 cm it is possible to form exactly three different integer sided
right angle triangles.
120 cm: (30,40,50), (20,48,52), (24,45,51)
Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can
exactly one integer sided right angle triangle be formed?
Solution: we generate all pythagorean triples using Euclid's formula and
keep track of the frequencies of the perimeters.
Reference: https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple
"""
from collections import defaultdict
from math import gcd
from typing import DefaultDict
def solution(limit: int = 1500000) -> int:
"""
Return the number of values of L <= limit such that a wire of length L can be
formmed into an integer sided right angle triangle in exactly one way.
>>> solution(50)
6
>>> solution(1000)
112
>>> solution(50000)
5502
"""
frequencies: DefaultDict = defaultdict(int)
euclid_m = 2
while 2 * euclid_m * (euclid_m + 1) <= limit:
for euclid_n in range((euclid_m % 2) + 1, euclid_m, 2):
if gcd(euclid_m, euclid_n) > 1:
continue
primitive_perimeter = 2 * euclid_m * (euclid_m + euclid_n)
for perimeter in range(primitive_perimeter, limit + 1, primitive_perimeter):
frequencies[perimeter] += 1
euclid_m += 1
return sum(1 for frequency in frequencies.values() if frequency == 1)
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 75: https://projecteuler.net/problem=75
It turns out that 12 cm is the smallest length of wire that can be bent to form an
integer sided right angle triangle in exactly one way, but there are many more examples.
12 cm: (3,4,5)
24 cm: (6,8,10)
30 cm: (5,12,13)
36 cm: (9,12,15)
40 cm: (8,15,17)
48 cm: (12,16,20)
In contrast, some lengths of wire, like 20 cm, cannot be bent to form an integer sided
right angle triangle, and other lengths allow more than one solution to be found; for
example, using 120 cm it is possible to form exactly three different integer sided
right angle triangles.
120 cm: (30,40,50), (20,48,52), (24,45,51)
Given that L is the length of the wire, for how many values of L ≤ 1,500,000 can
exactly one integer sided right angle triangle be formed?
Solution: we generate all pythagorean triples using Euclid's formula and
keep track of the frequencies of the perimeters.
Reference: https://en.wikipedia.org/wiki/Pythagorean_triple#Generating_a_triple
"""
from collections import defaultdict
from math import gcd
from typing import DefaultDict
def solution(limit: int = 1500000) -> int:
"""
Return the number of values of L <= limit such that a wire of length L can be
formmed into an integer sided right angle triangle in exactly one way.
>>> solution(50)
6
>>> solution(1000)
112
>>> solution(50000)
5502
"""
frequencies: DefaultDict = defaultdict(int)
euclid_m = 2
while 2 * euclid_m * (euclid_m + 1) <= limit:
for euclid_n in range((euclid_m % 2) + 1, euclid_m, 2):
if gcd(euclid_m, euclid_n) > 1:
continue
primitive_perimeter = 2 * euclid_m * (euclid_m + euclid_n)
for perimeter in range(primitive_perimeter, limit + 1, primitive_perimeter):
frequencies[perimeter] += 1
euclid_m += 1
return sum(1 for frequency in frequencies.values() if frequency == 1)
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| def reverse_long_words(sentence: str) -> str:
"""
Reverse all words that are longer than 4 characters in a sentence.
>>> reverse_long_words("Hey wollef sroirraw")
'Hey fellow warriors'
>>> reverse_long_words("nohtyP is nohtyP")
'Python is Python'
>>> reverse_long_words("1 12 123 1234 54321 654321")
'1 12 123 1234 12345 123456'
"""
return " ".join(
"".join(word[::-1]) if len(word) > 4 else word for word in sentence.split()
)
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_long_words("Hey wollef sroirraw"))
| def reverse_long_words(sentence: str) -> str:
"""
Reverse all words that are longer than 4 characters in a sentence.
>>> reverse_long_words("Hey wollef sroirraw")
'Hey fellow warriors'
>>> reverse_long_words("nohtyP is nohtyP")
'Python is Python'
>>> reverse_long_words("1 12 123 1234 54321 654321")
'1 12 123 1234 12345 123456'
"""
return " ".join(
"".join(word[::-1]) if len(word) > 4 else word for word in sentence.split()
)
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_long_words("Hey wollef sroirraw"))
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """ Convert Base 10 (Decimal) Values to Hexadecimal Representations """
# set decimal value for each hexadecimal digit
values = {
0: "0",
1: "1",
2: "2",
3: "3",
4: "4",
5: "5",
6: "6",
7: "7",
8: "8",
9: "9",
10: "a",
11: "b",
12: "c",
13: "d",
14: "e",
15: "f",
}
def decimal_to_hexadecimal(decimal: float) -> str:
"""
take integer decimal value, return hexadecimal representation as str beginning
with 0x
>>> decimal_to_hexadecimal(5)
'0x5'
>>> decimal_to_hexadecimal(15)
'0xf'
>>> decimal_to_hexadecimal(37)
'0x25'
>>> decimal_to_hexadecimal(255)
'0xff'
>>> decimal_to_hexadecimal(4096)
'0x1000'
>>> decimal_to_hexadecimal(999098)
'0xf3eba'
>>> # negatives work too
>>> decimal_to_hexadecimal(-256)
'-0x100'
>>> # floats are acceptable if equivalent to an int
>>> decimal_to_hexadecimal(17.0)
'0x11'
>>> # other floats will error
>>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AssertionError
>>> # strings will error as well
>>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AssertionError
>>> # results are the same when compared to Python's default hex function
>>> decimal_to_hexadecimal(-256) == hex(-256)
True
"""
assert type(decimal) in (int, float) and decimal == int(decimal)
decimal = int(decimal)
hexadecimal = ""
negative = False
if decimal < 0:
negative = True
decimal *= -1
while decimal > 0:
decimal, remainder = divmod(decimal, 16)
hexadecimal = values[remainder] + hexadecimal
hexadecimal = "0x" + hexadecimal
if negative:
hexadecimal = "-" + hexadecimal
return hexadecimal
if __name__ == "__main__":
import doctest
doctest.testmod()
| """ Convert Base 10 (Decimal) Values to Hexadecimal Representations """
# set decimal value for each hexadecimal digit
values = {
0: "0",
1: "1",
2: "2",
3: "3",
4: "4",
5: "5",
6: "6",
7: "7",
8: "8",
9: "9",
10: "a",
11: "b",
12: "c",
13: "d",
14: "e",
15: "f",
}
def decimal_to_hexadecimal(decimal: float) -> str:
"""
take integer decimal value, return hexadecimal representation as str beginning
with 0x
>>> decimal_to_hexadecimal(5)
'0x5'
>>> decimal_to_hexadecimal(15)
'0xf'
>>> decimal_to_hexadecimal(37)
'0x25'
>>> decimal_to_hexadecimal(255)
'0xff'
>>> decimal_to_hexadecimal(4096)
'0x1000'
>>> decimal_to_hexadecimal(999098)
'0xf3eba'
>>> # negatives work too
>>> decimal_to_hexadecimal(-256)
'-0x100'
>>> # floats are acceptable if equivalent to an int
>>> decimal_to_hexadecimal(17.0)
'0x11'
>>> # other floats will error
>>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AssertionError
>>> # strings will error as well
>>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AssertionError
>>> # results are the same when compared to Python's default hex function
>>> decimal_to_hexadecimal(-256) == hex(-256)
True
"""
assert type(decimal) in (int, float) and decimal == int(decimal)
decimal = int(decimal)
hexadecimal = ""
negative = False
if decimal < 0:
negative = True
decimal *= -1
while decimal > 0:
decimal, remainder = divmod(decimal, 16)
hexadecimal = values[remainder] + hexadecimal
hexadecimal = "0x" + hexadecimal
if negative:
hexadecimal = "-" + hexadecimal
return hexadecimal
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/bin/sh
#
# An example hook script to prepare a packed repository for use over
# dumb transports.
#
# To enable this hook, rename this file to "post-update".
exec git update-server-info
| #!/bin/sh
#
# An example hook script to prepare a packed repository for use over
# dumb transports.
#
# To enable this hook, rename this file to "post-update".
exec git update-server-info
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Just to check
"""
def add(a, b):
"""
>>> add(2, 2)
4
>>> add(2, -2)
0
"""
return a + b
if __name__ == "__main__":
a = 5
b = 6
print(f"The sum of {a} + {b} is {add(a, b)}")
| """
Just to check
"""
def add(a, b):
"""
>>> add(2, 2)
4
>>> add(2, -2)
0
"""
return a + b
if __name__ == "__main__":
a = 5
b = 6
print(f"The sum of {a} + {b} is {add(a, b)}")
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Problem 15: https://projecteuler.net/problem=15
Starting in the top left corner of a 2×2 grid, and only being able to move to
the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
"""
from math import factorial
def solution(n: int = 20) -> int:
"""
Returns the number of paths possible in a n x n grid starting at top left
corner going to bottom right corner and being able to move right and down
only.
>>> solution(25)
126410606437752
>>> solution(23)
8233430727600
>>> solution(20)
137846528820
>>> solution(15)
155117520
>>> solution(1)
2
"""
n = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1,
# 2, 3,...
k = n // 2
return int(factorial(n) / (factorial(k) * factorial(n - k)))
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
print(solution(20))
else:
try:
n = int(sys.argv[1])
print(solution(n))
except ValueError:
print("Invalid entry - please enter a number.")
| """
Problem 15: https://projecteuler.net/problem=15
Starting in the top left corner of a 2×2 grid, and only being able to move to
the right and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
"""
from math import factorial
def solution(n: int = 20) -> int:
"""
Returns the number of paths possible in a n x n grid starting at top left
corner going to bottom right corner and being able to move right and down
only.
>>> solution(25)
126410606437752
>>> solution(23)
8233430727600
>>> solution(20)
137846528820
>>> solution(15)
155117520
>>> solution(1)
2
"""
n = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1,
# 2, 3,...
k = n // 2
return int(factorial(n) / (factorial(k) * factorial(n - k)))
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
print(solution(20))
else:
try:
n = int(sys.argv[1])
print(solution(n))
except ValueError:
print("Invalid entry - please enter a number.")
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
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: 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
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.
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=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: 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
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.
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=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 | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Author : Syed Faizan ( 3rd Year IIIT Pune )
Github : faizan2700
Purpose : You have one function f(x) which takes float integer and returns
float you have to integrate the function in limits a to b.
The approximation proposed by Thomas Simpsons in 1743 is one way to calculate
integration.
( read article : https://cp-algorithms.com/num_methods/simpson-integration.html )
simpson_integration() takes function,lower_limit=a,upper_limit=b,precision and
returns the integration of function in given limit.
"""
# constants
# the more the number of steps the more accurate
N_STEPS = 1000
def f(x: float) -> float:
return x * x
"""
Summary of Simpson Approximation :
By simpsons integration :
1. integration of fxdx with limit a to b is =
f(x0) + 4 * f(x1) + 2 * f(x2) + 4 * f(x3) + 2 * f(x4)..... + f(xn)
where x0 = a
xi = a + i * h
xn = b
"""
def simpson_integration(function, a: float, b: float, precision: int = 4) -> float:
"""
Args:
function : the function which's integration is desired
a : the lower limit of integration
b : upper limit of integration
precision : precision of the result,error required default is 4
Returns:
result : the value of the approximated integration of function in range a to b
Raises:
AssertionError: function is not callable
AssertionError: a is not float or integer
AssertionError: function should return float or integer
AssertionError: b is not float or integer
AssertionError: precision is not positive integer
>>> simpson_integration(lambda x : x*x,1,2,3)
2.333
>>> simpson_integration(lambda x : x*x,'wrong_input',2,3)
Traceback (most recent call last):
...
AssertionError: a should be float or integer your input : wrong_input
>>> simpson_integration(lambda x : x*x,1,'wrong_input',3)
Traceback (most recent call last):
...
AssertionError: b should be float or integer your input : wrong_input
>>> simpson_integration(lambda x : x*x,1,2,'wrong_input')
Traceback (most recent call last):
...
AssertionError: precision should be positive integer your input : wrong_input
>>> simpson_integration('wrong_input',2,3,4)
Traceback (most recent call last):
...
AssertionError: the function(object) passed should be callable your input : ...
>>> simpson_integration(lambda x : x*x,3.45,3.2,1)
-2.8
>>> simpson_integration(lambda x : x*x,3.45,3.2,0)
Traceback (most recent call last):
...
AssertionError: precision should be positive integer your input : 0
>>> simpson_integration(lambda x : x*x,3.45,3.2,-1)
Traceback (most recent call last):
...
AssertionError: precision should be positive integer your input : -1
"""
assert callable(
function
), f"the function(object) passed should be callable your input : {function}"
assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}"
assert isinstance(function(a), (float, int)), (
"the function should return integer or float return type of your function, "
f"{type(a)}"
)
assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}"
assert (
isinstance(precision, int) and precision > 0
), f"precision should be positive integer your input : {precision}"
# just applying the formula of simpson for approximate integration written in
# mentioned article in first comment of this file and above this function
h = (b - a) / N_STEPS
result = function(a) + function(b)
for i in range(1, N_STEPS):
a1 = a + h * i
result += function(a1) * (4 if i % 2 else 2)
result *= h / 3
return round(result, precision)
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Author : Syed Faizan ( 3rd Year IIIT Pune )
Github : faizan2700
Purpose : You have one function f(x) which takes float integer and returns
float you have to integrate the function in limits a to b.
The approximation proposed by Thomas Simpsons in 1743 is one way to calculate
integration.
( read article : https://cp-algorithms.com/num_methods/simpson-integration.html )
simpson_integration() takes function,lower_limit=a,upper_limit=b,precision and
returns the integration of function in given limit.
"""
# constants
# the more the number of steps the more accurate
N_STEPS = 1000
def f(x: float) -> float:
return x * x
"""
Summary of Simpson Approximation :
By simpsons integration :
1. integration of fxdx with limit a to b is =
f(x0) + 4 * f(x1) + 2 * f(x2) + 4 * f(x3) + 2 * f(x4)..... + f(xn)
where x0 = a
xi = a + i * h
xn = b
"""
def simpson_integration(function, a: float, b: float, precision: int = 4) -> float:
"""
Args:
function : the function which's integration is desired
a : the lower limit of integration
b : upper limit of integration
precision : precision of the result,error required default is 4
Returns:
result : the value of the approximated integration of function in range a to b
Raises:
AssertionError: function is not callable
AssertionError: a is not float or integer
AssertionError: function should return float or integer
AssertionError: b is not float or integer
AssertionError: precision is not positive integer
>>> simpson_integration(lambda x : x*x,1,2,3)
2.333
>>> simpson_integration(lambda x : x*x,'wrong_input',2,3)
Traceback (most recent call last):
...
AssertionError: a should be float or integer your input : wrong_input
>>> simpson_integration(lambda x : x*x,1,'wrong_input',3)
Traceback (most recent call last):
...
AssertionError: b should be float or integer your input : wrong_input
>>> simpson_integration(lambda x : x*x,1,2,'wrong_input')
Traceback (most recent call last):
...
AssertionError: precision should be positive integer your input : wrong_input
>>> simpson_integration('wrong_input',2,3,4)
Traceback (most recent call last):
...
AssertionError: the function(object) passed should be callable your input : ...
>>> simpson_integration(lambda x : x*x,3.45,3.2,1)
-2.8
>>> simpson_integration(lambda x : x*x,3.45,3.2,0)
Traceback (most recent call last):
...
AssertionError: precision should be positive integer your input : 0
>>> simpson_integration(lambda x : x*x,3.45,3.2,-1)
Traceback (most recent call last):
...
AssertionError: precision should be positive integer your input : -1
"""
assert callable(
function
), f"the function(object) passed should be callable your input : {function}"
assert isinstance(a, (float, int)), f"a should be float or integer your input : {a}"
assert isinstance(function(a), (float, int)), (
"the function should return integer or float return type of your function, "
f"{type(a)}"
)
assert isinstance(b, (float, int)), f"b should be float or integer your input : {b}"
assert (
isinstance(precision, int) and precision > 0
), f"precision should be positive integer your input : {precision}"
# just applying the formula of simpson for approximate integration written in
# mentioned article in first comment of this file and above this function
h = (b - a) / N_STEPS
result = function(a) + function(b)
for i in range(1, N_STEPS):
a1 = a + h * i
result += function(a1) * (4 if i % 2 else 2)
result *= h / 3
return round(result, precision)
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
By starting at the top of the triangle below and moving to adjacent numbers on
the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
"""
import os
def solution():
"""
Finds the maximum total in a triangle as described by the problem statement
above.
>>> solution()
1074
"""
script_dir = os.path.dirname(os.path.realpath(__file__))
triangle = os.path.join(script_dir, "triangle.txt")
with open(triangle) as f:
triangle = f.readlines()
a = [[int(y) for y in x.rstrip("\r\n").split(" ")] for x in triangle]
for i in range(1, len(a)):
for j in range(len(a[i])):
if j != len(a[i - 1]):
number1 = a[i - 1][j]
else:
number1 = 0
if j > 0:
number2 = a[i - 1][j - 1]
else:
number2 = 0
a[i][j] += max(number1, number2)
return max(a[-1])
if __name__ == "__main__":
print(solution())
| """
By starting at the top of the triangle below and moving to adjacent numbers on
the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23
"""
import os
def solution():
"""
Finds the maximum total in a triangle as described by the problem statement
above.
>>> solution()
1074
"""
script_dir = os.path.dirname(os.path.realpath(__file__))
triangle = os.path.join(script_dir, "triangle.txt")
with open(triangle) as f:
triangle = f.readlines()
a = [[int(y) for y in x.rstrip("\r\n").split(" ")] for x in triangle]
for i in range(1, len(a)):
for j in range(len(a[i])):
if j != len(a[i - 1]):
number1 = a[i - 1][j]
else:
number1 = 0
if j > 0:
number2 = a[i - 1][j - 1]
else:
number2 = 0
a[i][j] += max(number1, number2)
return max(a[-1])
if __name__ == "__main__":
print(solution())
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/bin/sh
# An example hook script to verify what is about to be pushed. Called by "git
# push" after it has checked the remote status, but before anything has been
# pushed. If this script exits with a non-zero status nothing will be pushed.
#
# This hook is called with the following parameters:
#
# $1 -- Name of the remote to which the push is being done
# $2 -- URL to which the push is being done
#
# If pushing without using a named remote those arguments will be equal.
#
# Information about the commits which are being pushed is supplied as lines to
# the standard input in the form:
#
# <local ref> <local sha1> <remote ref> <remote sha1>
#
# This sample shows how to prevent push of commits where the log message starts
# with "WIP" (work in progress).
remote="$1"
url="$2"
z40=0000000000000000000000000000000000000000
while read local_ref local_sha remote_ref remote_sha
do
if [ "$local_sha" = $z40 ]
then
# Handle delete
:
else
if [ "$remote_sha" = $z40 ]
then
# New branch, examine all commits
range="$local_sha"
else
# Update to existing branch, examine new commits
range="$remote_sha..$local_sha"
fi
# Check for WIP commit
commit=`git rev-list -n 1 --grep '^WIP' "$range"`
if [ -n "$commit" ]
then
echo >&2 "Found WIP commit in $local_ref, not pushing"
exit 1
fi
fi
done
exit 0
| #!/bin/sh
# An example hook script to verify what is about to be pushed. Called by "git
# push" after it has checked the remote status, but before anything has been
# pushed. If this script exits with a non-zero status nothing will be pushed.
#
# This hook is called with the following parameters:
#
# $1 -- Name of the remote to which the push is being done
# $2 -- URL to which the push is being done
#
# If pushing without using a named remote those arguments will be equal.
#
# Information about the commits which are being pushed is supplied as lines to
# the standard input in the form:
#
# <local ref> <local sha1> <remote ref> <remote sha1>
#
# This sample shows how to prevent push of commits where the log message starts
# with "WIP" (work in progress).
remote="$1"
url="$2"
z40=0000000000000000000000000000000000000000
while read local_ref local_sha remote_ref remote_sha
do
if [ "$local_sha" = $z40 ]
then
# Handle delete
:
else
if [ "$remote_sha" = $z40 ]
then
# New branch, examine all commits
range="$local_sha"
else
# Update to existing branch, examine new commits
range="$remote_sha..$local_sha"
fi
# Check for WIP commit
commit=`git rev-list -n 1 --grep '^WIP' "$range"`
if [ -n "$commit" ]
then
echo >&2 "Found WIP commit in $local_ref, not pushing"
exit 1
fi
fi
done
exit 0
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| 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 interactTreap(root: Node | None, args: str) -> Node | None:
"""
Commands:
+ value to add value into treap
- value to erase all nodes with value
>>> root = interactTreap(None, "+1")
>>> inorder(root)
1,
>>> root = interactTreap(root, "+3 +5 +17 +19 +2 +16 +4 +0")
>>> inorder(root)
0,1,2,3,4,5,16,17,19,
>>> root = interactTreap(root, "+4 +4 +4")
>>> inorder(root)
0,1,2,3,4,4,4,4,5,16,17,19,
>>> root = interactTreap(root, "-0")
>>> inorder(root)
1,2,3,4,4,4,4,5,16,17,19,
>>> root = interactTreap(root, "-4")
>>> inorder(root)
1,2,3,5,16,17,19,
>>> root = interactTreap(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 = interactTreap(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 interactTreap(root: Node | None, args: str) -> Node | None:
"""
Commands:
+ value to add value into treap
- value to erase all nodes with value
>>> root = interactTreap(None, "+1")
>>> inorder(root)
1,
>>> root = interactTreap(root, "+3 +5 +17 +19 +2 +16 +4 +0")
>>> inorder(root)
0,1,2,3,4,5,16,17,19,
>>> root = interactTreap(root, "+4 +4 +4")
>>> inorder(root)
0,1,2,3,4,4,4,4,5,16,17,19,
>>> root = interactTreap(root, "-0")
>>> inorder(root)
1,2,3,4,4,4,4,5,16,17,19,
>>> root = interactTreap(root, "-4")
>>> inorder(root)
1,2,3,5,16,17,19,
>>> root = interactTreap(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 = interactTreap(root, args)
print(root)
args = input()
print("good by!")
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
This is to show simple COVID19 info fetching from worldometers site using lxml
* The main motivation to use lxml in place of bs4 is that it is faster and therefore
more convenient to use in Python web projects (e.g. Django or Flask-based)
"""
from collections import namedtuple
import requests
from lxml import html # type: ignore
covid_data = namedtuple("covid_data", "cases deaths recovered")
def covid_stats(url: str = "https://www.worldometers.info/coronavirus/") -> covid_data:
xpath_str = '//div[@class = "maincounter-number"]/span/text()'
return covid_data(*html.fromstring(requests.get(url).content).xpath(xpath_str))
fmt = """Total COVID-19 cases in the world: {}
Total deaths due to COVID-19 in the world: {}
Total COVID-19 patients recovered in the world: {}"""
print(fmt.format(*covid_stats()))
| """
This is to show simple COVID19 info fetching from worldometers site using lxml
* The main motivation to use lxml in place of bs4 is that it is faster and therefore
more convenient to use in Python web projects (e.g. Django or Flask-based)
"""
from collections import namedtuple
import requests
from lxml import html # type: ignore
covid_data = namedtuple("covid_data", "cases deaths recovered")
def covid_stats(url: str = "https://www.worldometers.info/coronavirus/") -> covid_data:
xpath_str = '//div[@class = "maincounter-number"]/span/text()'
return covid_data(*html.fromstring(requests.get(url).content).xpath(xpath_str))
fmt = """Total COVID-19 cases in the world: {}
Total deaths due to COVID-19 in the world: {}
Total COVID-19 patients recovered in the world: {}"""
print(fmt.format(*covid_stats()))
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import math
def rearrange(bitString32):
"""[summary]
Regroups the given binary string.
Arguments:
bitString32 {[string]} -- [32 bit binary]
Raises:
ValueError -- [if the given string not are 32 bit binary string]
Returns:
[string] -- [32 bit binary string]
>>> rearrange('1234567890abcdfghijklmnopqrstuvw')
'pqrstuvwhijklmno90abcdfg12345678'
"""
if len(bitString32) != 32:
raise ValueError("Need length 32")
newString = ""
for i in [3, 2, 1, 0]:
newString += bitString32[8 * i : 8 * i + 8]
return newString
def reformatHex(i):
"""[summary]
Converts the given integer into 8-digit hex number.
Arguments:
i {[int]} -- [integer]
>>> reformatHex(666)
'9a020000'
"""
hexrep = format(i, "08x")
thing = ""
for i in [3, 2, 1, 0]:
thing += hexrep[2 * i : 2 * i + 2]
return thing
def pad(bitString):
"""[summary]
Fills up the binary string to a 512 bit binary string
Arguments:
bitString {[string]} -- [binary string]
Returns:
[string] -- [binary string]
"""
startLength = len(bitString)
bitString += "1"
while len(bitString) % 512 != 448:
bitString += "0"
lastPart = format(startLength, "064b")
bitString += rearrange(lastPart[32:]) + rearrange(lastPart[:32])
return bitString
def getBlock(bitString):
"""[summary]
Iterator:
Returns by each call a list of length 16 with the 32 bit
integer blocks.
Arguments:
bitString {[string]} -- [binary string >= 512]
"""
currPos = 0
while currPos < len(bitString):
currPart = bitString[currPos : currPos + 512]
mySplits = []
for i in range(16):
mySplits.append(int(rearrange(currPart[32 * i : 32 * i + 32]), 2))
yield mySplits
currPos += 512
def not32(i):
"""
>>> not32(34)
4294967261
"""
i_str = format(i, "032b")
new_str = ""
for c in i_str:
new_str += "1" if c == "0" else "0"
return int(new_str, 2)
def sum32(a, b):
return (a + b) % 2**32
def leftrot32(i, s):
return (i << s) ^ (i >> (32 - s))
def md5me(testString):
"""[summary]
Returns a 32-bit hash code of the string 'testString'
Arguments:
testString {[string]} -- [message]
"""
bs = ""
for i in testString:
bs += format(ord(i), "08b")
bs = pad(bs)
tvals = [int(2**32 * abs(math.sin(i + 1))) for i in range(64)]
a0 = 0x67452301
b0 = 0xEFCDAB89
c0 = 0x98BADCFE
d0 = 0x10325476
s = [
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
]
for m in getBlock(bs):
A = a0
B = b0
C = c0
D = d0
for i in range(64):
if i <= 15:
# f = (B & C) | (not32(B) & D)
f = D ^ (B & (C ^ D))
g = i
elif i <= 31:
# f = (D & B) | (not32(D) & C)
f = C ^ (D & (B ^ C))
g = (5 * i + 1) % 16
elif i <= 47:
f = B ^ C ^ D
g = (3 * i + 5) % 16
else:
f = C ^ (B | not32(D))
g = (7 * i) % 16
dtemp = D
D = C
C = B
B = sum32(B, leftrot32((A + f + tvals[i] + m[g]) % 2**32, s[i]))
A = dtemp
a0 = sum32(a0, A)
b0 = sum32(b0, B)
c0 = sum32(c0, C)
d0 = sum32(d0, D)
digest = reformatHex(a0) + reformatHex(b0) + reformatHex(c0) + reformatHex(d0)
return digest
def test():
assert md5me("") == "d41d8cd98f00b204e9800998ecf8427e"
assert (
md5me("The quick brown fox jumps over the lazy dog")
== "9e107d9d372bb6826bd81d3542a419d6"
)
print("Success.")
if __name__ == "__main__":
test()
import doctest
doctest.testmod()
| import math
def rearrange(bitString32):
"""[summary]
Regroups the given binary string.
Arguments:
bitString32 {[string]} -- [32 bit binary]
Raises:
ValueError -- [if the given string not are 32 bit binary string]
Returns:
[string] -- [32 bit binary string]
>>> rearrange('1234567890abcdfghijklmnopqrstuvw')
'pqrstuvwhijklmno90abcdfg12345678'
"""
if len(bitString32) != 32:
raise ValueError("Need length 32")
newString = ""
for i in [3, 2, 1, 0]:
newString += bitString32[8 * i : 8 * i + 8]
return newString
def reformatHex(i):
"""[summary]
Converts the given integer into 8-digit hex number.
Arguments:
i {[int]} -- [integer]
>>> reformatHex(666)
'9a020000'
"""
hexrep = format(i, "08x")
thing = ""
for i in [3, 2, 1, 0]:
thing += hexrep[2 * i : 2 * i + 2]
return thing
def pad(bitString):
"""[summary]
Fills up the binary string to a 512 bit binary string
Arguments:
bitString {[string]} -- [binary string]
Returns:
[string] -- [binary string]
"""
startLength = len(bitString)
bitString += "1"
while len(bitString) % 512 != 448:
bitString += "0"
lastPart = format(startLength, "064b")
bitString += rearrange(lastPart[32:]) + rearrange(lastPart[:32])
return bitString
def getBlock(bitString):
"""[summary]
Iterator:
Returns by each call a list of length 16 with the 32 bit
integer blocks.
Arguments:
bitString {[string]} -- [binary string >= 512]
"""
currPos = 0
while currPos < len(bitString):
currPart = bitString[currPos : currPos + 512]
mySplits = []
for i in range(16):
mySplits.append(int(rearrange(currPart[32 * i : 32 * i + 32]), 2))
yield mySplits
currPos += 512
def not32(i):
"""
>>> not32(34)
4294967261
"""
i_str = format(i, "032b")
new_str = ""
for c in i_str:
new_str += "1" if c == "0" else "0"
return int(new_str, 2)
def sum32(a, b):
return (a + b) % 2**32
def leftrot32(i, s):
return (i << s) ^ (i >> (32 - s))
def md5me(testString):
"""[summary]
Returns a 32-bit hash code of the string 'testString'
Arguments:
testString {[string]} -- [message]
"""
bs = ""
for i in testString:
bs += format(ord(i), "08b")
bs = pad(bs)
tvals = [int(2**32 * abs(math.sin(i + 1))) for i in range(64)]
a0 = 0x67452301
b0 = 0xEFCDAB89
c0 = 0x98BADCFE
d0 = 0x10325476
s = [
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
7,
12,
17,
22,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
5,
9,
14,
20,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
4,
11,
16,
23,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
6,
10,
15,
21,
]
for m in getBlock(bs):
A = a0
B = b0
C = c0
D = d0
for i in range(64):
if i <= 15:
# f = (B & C) | (not32(B) & D)
f = D ^ (B & (C ^ D))
g = i
elif i <= 31:
# f = (D & B) | (not32(D) & C)
f = C ^ (D & (B ^ C))
g = (5 * i + 1) % 16
elif i <= 47:
f = B ^ C ^ D
g = (3 * i + 5) % 16
else:
f = C ^ (B | not32(D))
g = (7 * i) % 16
dtemp = D
D = C
C = B
B = sum32(B, leftrot32((A + f + tvals[i] + m[g]) % 2**32, s[i]))
A = dtemp
a0 = sum32(a0, A)
b0 = sum32(b0, B)
c0 = sum32(c0, C)
d0 = sum32(d0, D)
digest = reformatHex(a0) + reformatHex(b0) + reformatHex(c0) + reformatHex(d0)
return digest
def test():
assert md5me("") == "d41d8cd98f00b204e9800998ecf8427e"
assert (
md5me("The quick brown fox jumps over the lazy dog")
== "9e107d9d372bb6826bd81d3542a419d6"
)
print("Success.")
if __name__ == "__main__":
test()
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """ A Queue using a linked list like structure """
from __future__ import annotations
from typing import Any, Iterator
class Node:
def __init__(self, data: Any) -> None:
self.data: Any = data
self.next: Node | None = None
def __str__(self) -> str:
return f"{self.data}"
class LinkedQueue:
"""
>>> queue = LinkedQueue()
>>> queue.is_empty()
True
>>> queue.put(5)
>>> queue.put(9)
>>> queue.put('python')
>>> queue.is_empty();
False
>>> queue.get()
5
>>> queue.put('algorithms')
>>> queue.get()
9
>>> queue.get()
'python'
>>> queue.get()
'algorithms'
>>> queue.is_empty()
True
>>> queue.get()
Traceback (most recent call last):
...
IndexError: dequeue from empty queue
"""
def __init__(self) -> None:
self.front: Node | None = None
self.rear: Node | None = None
def __iter__(self) -> Iterator[Any]:
node = self.front
while node:
yield node.data
node = node.next
def __len__(self) -> int:
"""
>>> queue = LinkedQueue()
>>> for i in range(1, 6):
... queue.put(i)
>>> len(queue)
5
>>> for i in range(1, 6):
... assert len(queue) == 6 - i
... _ = queue.get()
>>> len(queue)
0
"""
return len(tuple(iter(self)))
def __str__(self) -> str:
"""
>>> queue = LinkedQueue()
>>> for i in range(1, 4):
... queue.put(i)
>>> queue.put("Python")
>>> queue.put(3.14)
>>> queue.put(True)
>>> str(queue)
'1 <- 2 <- 3 <- Python <- 3.14 <- True'
"""
return " <- ".join(str(item) for item in self)
def is_empty(self) -> bool:
"""
>>> queue = LinkedQueue()
>>> queue.is_empty()
True
>>> for i in range(1, 6):
... queue.put(i)
>>> queue.is_empty()
False
"""
return len(self) == 0
def put(self, item: Any) -> None:
"""
>>> queue = LinkedQueue()
>>> queue.get()
Traceback (most recent call last):
...
IndexError: dequeue from empty queue
>>> for i in range(1, 6):
... queue.put(i)
>>> str(queue)
'1 <- 2 <- 3 <- 4 <- 5'
"""
node = Node(item)
if self.is_empty():
self.front = self.rear = node
else:
assert isinstance(self.rear, Node)
self.rear.next = node
self.rear = node
def get(self) -> Any:
"""
>>> queue = LinkedQueue()
>>> queue.get()
Traceback (most recent call last):
...
IndexError: dequeue from empty queue
>>> queue = LinkedQueue()
>>> for i in range(1, 6):
... queue.put(i)
>>> for i in range(1, 6):
... assert queue.get() == i
>>> len(queue)
0
"""
if self.is_empty():
raise IndexError("dequeue from empty queue")
assert isinstance(self.front, Node)
node = self.front
self.front = self.front.next
if self.front is None:
self.rear = None
return node.data
def clear(self) -> None:
"""
>>> queue = LinkedQueue()
>>> for i in range(1, 6):
... queue.put(i)
>>> queue.clear()
>>> len(queue)
0
>>> str(queue)
''
"""
self.front = self.rear = None
if __name__ == "__main__":
from doctest import testmod
testmod()
| """ A Queue using a linked list like structure """
from __future__ import annotations
from typing import Any, Iterator
class Node:
def __init__(self, data: Any) -> None:
self.data: Any = data
self.next: Node | None = None
def __str__(self) -> str:
return f"{self.data}"
class LinkedQueue:
"""
>>> queue = LinkedQueue()
>>> queue.is_empty()
True
>>> queue.put(5)
>>> queue.put(9)
>>> queue.put('python')
>>> queue.is_empty();
False
>>> queue.get()
5
>>> queue.put('algorithms')
>>> queue.get()
9
>>> queue.get()
'python'
>>> queue.get()
'algorithms'
>>> queue.is_empty()
True
>>> queue.get()
Traceback (most recent call last):
...
IndexError: dequeue from empty queue
"""
def __init__(self) -> None:
self.front: Node | None = None
self.rear: Node | None = None
def __iter__(self) -> Iterator[Any]:
node = self.front
while node:
yield node.data
node = node.next
def __len__(self) -> int:
"""
>>> queue = LinkedQueue()
>>> for i in range(1, 6):
... queue.put(i)
>>> len(queue)
5
>>> for i in range(1, 6):
... assert len(queue) == 6 - i
... _ = queue.get()
>>> len(queue)
0
"""
return len(tuple(iter(self)))
def __str__(self) -> str:
"""
>>> queue = LinkedQueue()
>>> for i in range(1, 4):
... queue.put(i)
>>> queue.put("Python")
>>> queue.put(3.14)
>>> queue.put(True)
>>> str(queue)
'1 <- 2 <- 3 <- Python <- 3.14 <- True'
"""
return " <- ".join(str(item) for item in self)
def is_empty(self) -> bool:
"""
>>> queue = LinkedQueue()
>>> queue.is_empty()
True
>>> for i in range(1, 6):
... queue.put(i)
>>> queue.is_empty()
False
"""
return len(self) == 0
def put(self, item: Any) -> None:
"""
>>> queue = LinkedQueue()
>>> queue.get()
Traceback (most recent call last):
...
IndexError: dequeue from empty queue
>>> for i in range(1, 6):
... queue.put(i)
>>> str(queue)
'1 <- 2 <- 3 <- 4 <- 5'
"""
node = Node(item)
if self.is_empty():
self.front = self.rear = node
else:
assert isinstance(self.rear, Node)
self.rear.next = node
self.rear = node
def get(self) -> Any:
"""
>>> queue = LinkedQueue()
>>> queue.get()
Traceback (most recent call last):
...
IndexError: dequeue from empty queue
>>> queue = LinkedQueue()
>>> for i in range(1, 6):
... queue.put(i)
>>> for i in range(1, 6):
... assert queue.get() == i
>>> len(queue)
0
"""
if self.is_empty():
raise IndexError("dequeue from empty queue")
assert isinstance(self.front, Node)
node = self.front
self.front = self.front.next
if self.front is None:
self.rear = None
return node.data
def clear(self) -> None:
"""
>>> queue = LinkedQueue()
>>> for i in range(1, 6):
... queue.put(i)
>>> queue.clear()
>>> len(queue)
0
>>> str(queue)
''
"""
self.front = self.rear = None
if __name__ == "__main__":
from doctest import testmod
testmod()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/python
""" Author: OMKAR PATHAK """
class Graph:
def __init__(self):
self.vertex = {}
# for printing the Graph vertices
def print_graph(self) -> None:
print(self.vertex)
for i in self.vertex:
print(i, " -> ", " -> ".join([str(j) for j in self.vertex[i]]))
# for adding the edge between two vertices
def add_edge(self, from_vertex: int, to_vertex: int) -> None:
# check if vertex is already present,
if from_vertex in self.vertex:
self.vertex[from_vertex].append(to_vertex)
else:
# else make a new vertex
self.vertex[from_vertex] = [to_vertex]
def dfs(self) -> None:
# visited array for storing already visited nodes
visited = [False] * len(self.vertex)
# call the recursive helper function
for i in range(len(self.vertex)):
if not visited[i]:
self.dfs_recursive(i, visited)
def dfs_recursive(self, start_vertex: int, visited: list) -> None:
# mark start vertex as visited
visited[start_vertex] = True
print(start_vertex, end=" ")
# Recur for all the vertices that are adjacent to this node
for i in self.vertex:
if not visited[i]:
self.dfs_recursive(i, visited)
if __name__ == "__main__":
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)
g.print_graph()
print("DFS:")
g.dfs()
# OUTPUT:
# 0 -> 1 -> 2
# 1 -> 2
# 2 -> 0 -> 3
# 3 -> 3
# DFS:
# 0 1 2 3
| #!/usr/bin/python
""" Author: OMKAR PATHAK """
class Graph:
def __init__(self):
self.vertex = {}
# for printing the Graph vertices
def print_graph(self) -> None:
print(self.vertex)
for i in self.vertex:
print(i, " -> ", " -> ".join([str(j) for j in self.vertex[i]]))
# for adding the edge between two vertices
def add_edge(self, from_vertex: int, to_vertex: int) -> None:
# check if vertex is already present,
if from_vertex in self.vertex:
self.vertex[from_vertex].append(to_vertex)
else:
# else make a new vertex
self.vertex[from_vertex] = [to_vertex]
def dfs(self) -> None:
# visited array for storing already visited nodes
visited = [False] * len(self.vertex)
# call the recursive helper function
for i in range(len(self.vertex)):
if not visited[i]:
self.dfs_recursive(i, visited)
def dfs_recursive(self, start_vertex: int, visited: list) -> None:
# mark start vertex as visited
visited[start_vertex] = True
print(start_vertex, end=" ")
# Recur for all the vertices that are adjacent to this node
for i in self.vertex:
if not visited[i]:
self.dfs_recursive(i, visited)
if __name__ == "__main__":
g = Graph()
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.add_edge(3, 3)
g.print_graph()
print("DFS:")
g.dfs()
# OUTPUT:
# 0 -> 1 -> 2
# 1 -> 2
# 2 -> 0 -> 3
# 3 -> 3
# DFS:
# 0 1 2 3
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
This is pure Python implementation of fibonacci search.
Resources used:
https://en.wikipedia.org/wiki/Fibonacci_search_technique
For doctests run following command:
python3 -m doctest -v fibonacci_search.py
For manual testing run:
python3 fibonacci_search.py
"""
from functools import lru_cache
@lru_cache
def fibonacci(k: int) -> int:
"""Finds fibonacci number in index k.
Parameters
----------
k :
Index of fibonacci.
Returns
-------
int
Fibonacci number in position k.
>>> fibonacci(0)
0
>>> fibonacci(2)
1
>>> fibonacci(5)
5
>>> fibonacci(15)
610
>>> fibonacci('a')
Traceback (most recent call last):
TypeError: k must be an integer.
>>> fibonacci(-5)
Traceback (most recent call last):
ValueError: k integer must be greater or equal to zero.
"""
if not isinstance(k, int):
raise TypeError("k must be an integer.")
if k < 0:
raise ValueError("k integer must be greater or equal to zero.")
if k == 0:
return 0
elif k == 1:
return 1
else:
return fibonacci(k - 1) + fibonacci(k - 2)
def fibonacci_search(arr: list, val: int) -> int:
"""A pure Python implementation of a fibonacci search algorithm.
Parameters
----------
arr
List of sorted elements.
val
Element to search in list.
Returns
-------
int
The index of the element in the array.
-1 if the element is not found.
>>> fibonacci_search([4, 5, 6, 7], 4)
0
>>> fibonacci_search([4, 5, 6, 7], -10)
-1
>>> fibonacci_search([-18, 2], -18)
0
>>> fibonacci_search([5], 5)
0
>>> fibonacci_search(['a', 'c', 'd'], 'c')
1
>>> fibonacci_search(['a', 'c', 'd'], 'f')
-1
>>> fibonacci_search([], 1)
-1
>>> fibonacci_search([.1, .4 , 7], .4)
1
>>> fibonacci_search([], 9)
-1
>>> fibonacci_search(list(range(100)), 63)
63
>>> fibonacci_search(list(range(100)), 99)
99
>>> fibonacci_search(list(range(-100, 100, 3)), -97)
1
>>> fibonacci_search(list(range(-100, 100, 3)), 0)
-1
>>> fibonacci_search(list(range(-100, 100, 5)), 0)
20
>>> fibonacci_search(list(range(-100, 100, 5)), 95)
39
"""
len_list = len(arr)
# Find m such that F_m >= n where F_i is the i_th fibonacci number.
i = 0
while True:
if fibonacci(i) >= len_list:
fibb_k = i
break
i += 1
offset = 0
while fibb_k > 0:
index_k = min(
offset + fibonacci(fibb_k - 1), len_list - 1
) # Prevent out of range
item_k_1 = arr[index_k]
if item_k_1 == val:
return index_k
elif val < item_k_1:
fibb_k -= 1
elif val > item_k_1:
offset += fibonacci(fibb_k - 1)
fibb_k -= 2
else:
return -1
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
This is pure Python implementation of fibonacci search.
Resources used:
https://en.wikipedia.org/wiki/Fibonacci_search_technique
For doctests run following command:
python3 -m doctest -v fibonacci_search.py
For manual testing run:
python3 fibonacci_search.py
"""
from functools import lru_cache
@lru_cache
def fibonacci(k: int) -> int:
"""Finds fibonacci number in index k.
Parameters
----------
k :
Index of fibonacci.
Returns
-------
int
Fibonacci number in position k.
>>> fibonacci(0)
0
>>> fibonacci(2)
1
>>> fibonacci(5)
5
>>> fibonacci(15)
610
>>> fibonacci('a')
Traceback (most recent call last):
TypeError: k must be an integer.
>>> fibonacci(-5)
Traceback (most recent call last):
ValueError: k integer must be greater or equal to zero.
"""
if not isinstance(k, int):
raise TypeError("k must be an integer.")
if k < 0:
raise ValueError("k integer must be greater or equal to zero.")
if k == 0:
return 0
elif k == 1:
return 1
else:
return fibonacci(k - 1) + fibonacci(k - 2)
def fibonacci_search(arr: list, val: int) -> int:
"""A pure Python implementation of a fibonacci search algorithm.
Parameters
----------
arr
List of sorted elements.
val
Element to search in list.
Returns
-------
int
The index of the element in the array.
-1 if the element is not found.
>>> fibonacci_search([4, 5, 6, 7], 4)
0
>>> fibonacci_search([4, 5, 6, 7], -10)
-1
>>> fibonacci_search([-18, 2], -18)
0
>>> fibonacci_search([5], 5)
0
>>> fibonacci_search(['a', 'c', 'd'], 'c')
1
>>> fibonacci_search(['a', 'c', 'd'], 'f')
-1
>>> fibonacci_search([], 1)
-1
>>> fibonacci_search([.1, .4 , 7], .4)
1
>>> fibonacci_search([], 9)
-1
>>> fibonacci_search(list(range(100)), 63)
63
>>> fibonacci_search(list(range(100)), 99)
99
>>> fibonacci_search(list(range(-100, 100, 3)), -97)
1
>>> fibonacci_search(list(range(-100, 100, 3)), 0)
-1
>>> fibonacci_search(list(range(-100, 100, 5)), 0)
20
>>> fibonacci_search(list(range(-100, 100, 5)), 95)
39
"""
len_list = len(arr)
# Find m such that F_m >= n where F_i is the i_th fibonacci number.
i = 0
while True:
if fibonacci(i) >= len_list:
fibb_k = i
break
i += 1
offset = 0
while fibb_k > 0:
index_k = min(
offset + fibonacci(fibb_k - 1), len_list - 1
) # Prevent out of range
item_k_1 = arr[index_k]
if item_k_1 == val:
return index_k
elif val < item_k_1:
fibb_k -= 1
elif val > item_k_1:
offset += fibonacci(fibb_k - 1)
fibb_k -= 2
else:
return -1
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # https://en.wikipedia.org/wiki/Coulomb%27s_law
from __future__ import annotations
COULOMBS_CONSTANT = 8.988e9 # units = N * m^s * C^-2
def couloumbs_law(
force: float, charge1: float, charge2: float, distance: float
) -> dict[str, float]:
"""
Apply Coulomb's Law on any three given values. These can be force, charge1,
charge2, or distance, and then in a Python dict return name/value pair of
the zero value.
Coulomb's Law states that the magnitude of the electrostatic force of
attraction or repulsion between two point charges is directly proportional
to the product of the magnitudes of charges and inversely proportional to
the square of the distance between them.
Reference
----------
Coulomb (1785) "Premier mémoire sur l’électricité et le magnétisme,"
Histoire de l’Académie Royale des Sciences, pp. 569–577.
Parameters
----------
force : float with units in Newtons
charge1 : float with units in Coulombs
charge2 : float with units in Coulombs
distance : float with units in meters
Returns
-------
result : dict name/value pair of the zero value
>>> couloumbs_law(force=0, charge1=3, charge2=5, distance=2000)
{'force': 33705.0}
>>> couloumbs_law(force=10, charge1=3, charge2=5, distance=0)
{'distance': 116112.01488218177}
>>> couloumbs_law(force=10, charge1=0, charge2=5, distance=2000)
{'charge1': 0.0008900756564307966}
>>> couloumbs_law(force=0, charge1=0, charge2=5, distance=2000)
Traceback (most recent call last):
...
ValueError: One and only one argument must be 0
>>> couloumbs_law(force=0, charge1=3, charge2=5, distance=-2000)
Traceback (most recent call last):
...
ValueError: Distance cannot be negative
"""
charge_product = abs(charge1 * charge2)
if (force, charge1, charge2, distance).count(0) != 1:
raise ValueError("One and only one argument must be 0")
if distance < 0:
raise ValueError("Distance cannot be negative")
if force == 0:
force = COULOMBS_CONSTANT * charge_product / (distance**2)
return {"force": force}
elif charge1 == 0:
charge1 = abs(force) * (distance**2) / (COULOMBS_CONSTANT * charge2)
return {"charge1": charge1}
elif charge2 == 0:
charge2 = abs(force) * (distance**2) / (COULOMBS_CONSTANT * charge1)
return {"charge2": charge2}
elif distance == 0:
distance = (COULOMBS_CONSTANT * charge_product / abs(force)) ** 0.5
return {"distance": distance}
raise ValueError("Exactly one argument must be 0")
if __name__ == "__main__":
import doctest
doctest.testmod()
| # https://en.wikipedia.org/wiki/Coulomb%27s_law
from __future__ import annotations
COULOMBS_CONSTANT = 8.988e9 # units = N * m^s * C^-2
def couloumbs_law(
force: float, charge1: float, charge2: float, distance: float
) -> dict[str, float]:
"""
Apply Coulomb's Law on any three given values. These can be force, charge1,
charge2, or distance, and then in a Python dict return name/value pair of
the zero value.
Coulomb's Law states that the magnitude of the electrostatic force of
attraction or repulsion between two point charges is directly proportional
to the product of the magnitudes of charges and inversely proportional to
the square of the distance between them.
Reference
----------
Coulomb (1785) "Premier mémoire sur l’électricité et le magnétisme,"
Histoire de l’Académie Royale des Sciences, pp. 569–577.
Parameters
----------
force : float with units in Newtons
charge1 : float with units in Coulombs
charge2 : float with units in Coulombs
distance : float with units in meters
Returns
-------
result : dict name/value pair of the zero value
>>> couloumbs_law(force=0, charge1=3, charge2=5, distance=2000)
{'force': 33705.0}
>>> couloumbs_law(force=10, charge1=3, charge2=5, distance=0)
{'distance': 116112.01488218177}
>>> couloumbs_law(force=10, charge1=0, charge2=5, distance=2000)
{'charge1': 0.0008900756564307966}
>>> couloumbs_law(force=0, charge1=0, charge2=5, distance=2000)
Traceback (most recent call last):
...
ValueError: One and only one argument must be 0
>>> couloumbs_law(force=0, charge1=3, charge2=5, distance=-2000)
Traceback (most recent call last):
...
ValueError: Distance cannot be negative
"""
charge_product = abs(charge1 * charge2)
if (force, charge1, charge2, distance).count(0) != 1:
raise ValueError("One and only one argument must be 0")
if distance < 0:
raise ValueError("Distance cannot be negative")
if force == 0:
force = COULOMBS_CONSTANT * charge_product / (distance**2)
return {"force": force}
elif charge1 == 0:
charge1 = abs(force) * (distance**2) / (COULOMBS_CONSTANT * charge2)
return {"charge1": charge1}
elif charge2 == 0:
charge2 = abs(force) * (distance**2) / (COULOMBS_CONSTANT * charge1)
return {"charge2": charge2}
elif distance == 0:
distance = (COULOMBS_CONSTANT * charge_product / abs(force)) ** 0.5
return {"distance": distance}
raise ValueError("Exactly one argument must be 0")
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # The objective of this GitHub Action is to update the DIRECTORY.md file (if needed)
# when doing a git push
name: directory_writer
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1 # v1, NOT v2 or v3
- uses: actions/setup-python@v4
with:
python-version: 3.x
- name: Write DIRECTORY.md
run: |
scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md
git config --global user.name github-actions
git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com'
git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY
- name: Update DIRECTORY.md
run: |
git add DIRECTORY.md
git commit -am "updating DIRECTORY.md" || true
git push --force origin HEAD:$GITHUB_REF || true
| # The objective of this GitHub Action is to update the DIRECTORY.md file (if needed)
# when doing a git push
name: directory_writer
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1 # v1, NOT v2 or v3
- uses: actions/setup-python@v4
with:
python-version: 3.x
- name: Write DIRECTORY.md
run: |
scripts/build_directory_md.py 2>&1 | tee DIRECTORY.md
git config --global user.name github-actions
git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com'
git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY
- name: Update DIRECTORY.md
run: |
git add DIRECTORY.md
git commit -am "updating DIRECTORY.md" || true
git push --force origin HEAD:$GITHUB_REF || true
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Minimalist file that allows pytest to find and run the Test unittest. For details, see:
http://doc.pytest.org/en/latest/goodpractices.html#conventions-for-python-test-discovery
"""
from .prime_check import Test
Test()
| """
Minimalist file that allows pytest to find and run the Test unittest. For details, see:
http://doc.pytest.org/en/latest/goodpractices.html#conventions-for-python-test-discovery
"""
from .prime_check import Test
Test()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from typing import Callable
import numpy as np
def euler_modified(
ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float
) -> np.array:
"""
Calculate solution at each step to an ODE using Euler's Modified Method
The Euler Method is straightforward to implement, but can't give accurate solutions.
So, some changes were proposed to improve accuracy.
https://en.wikipedia.org/wiki/Euler_method
Arguments:
ode_func -- The ode as a function of x and y
y0 -- the initial value for y
x0 -- the initial value for x
stepsize -- the increment value for x
x_end -- the end value for x
>>> # the exact solution is math.exp(x)
>>> def f1(x, y):
... return -2*x*(y**2)
>>> y = euler_modified(f1, 1.0, 0.0, 0.2, 1.0)
>>> y[-1]
0.503338255442106
>>> import math
>>> def f2(x, y):
... return -2*y + (x**3)*math.exp(-2*x)
>>> y = euler_modified(f2, 1.0, 0.0, 0.1, 0.3)
>>> y[-1]
0.5525976431951775
"""
N = int(np.ceil((x_end - x0) / step_size))
y = np.zeros((N + 1,))
y[0] = y0
x = x0
for k in range(N):
y_get = y[k] + step_size * ode_func(x, y[k])
y[k + 1] = y[k] + (
(step_size / 2) * (ode_func(x, y[k]) + ode_func(x + step_size, y_get))
)
x += step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
| from typing import Callable
import numpy as np
def euler_modified(
ode_func: Callable, y0: float, x0: float, step_size: float, x_end: float
) -> np.array:
"""
Calculate solution at each step to an ODE using Euler's Modified Method
The Euler Method is straightforward to implement, but can't give accurate solutions.
So, some changes were proposed to improve accuracy.
https://en.wikipedia.org/wiki/Euler_method
Arguments:
ode_func -- The ode as a function of x and y
y0 -- the initial value for y
x0 -- the initial value for x
stepsize -- the increment value for x
x_end -- the end value for x
>>> # the exact solution is math.exp(x)
>>> def f1(x, y):
... return -2*x*(y**2)
>>> y = euler_modified(f1, 1.0, 0.0, 0.2, 1.0)
>>> y[-1]
0.503338255442106
>>> import math
>>> def f2(x, y):
... return -2*y + (x**3)*math.exp(-2*x)
>>> y = euler_modified(f2, 1.0, 0.0, 0.1, 0.3)
>>> y[-1]
0.5525976431951775
"""
N = int(np.ceil((x_end - x0) / step_size))
y = np.zeros((N + 1,))
y[0] = y0
x = x0
for k in range(N):
y_get = y[k] + step_size * ode_func(x, y[k])
y[k + 1] = y[k] + (
(step_size / 2) * (ode_func(x, y[k]) + ode_func(x + step_size, y_get))
)
x += step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Check if three points are collinear in 3D.
In short, the idea is that we are able to create a triangle using three points,
and the area of that triangle can determine if the three points are collinear or not.
First, we create two vectors with the same initial point from the three points,
then we will calculate the cross-product of them.
The length of the cross vector is numerically equal to the area of a parallelogram.
Finally, the area of the triangle is equal to half of the area of the parallelogram.
Since we are only differentiating between zero and anything else,
we can get rid of the square root when calculating the length of the vector,
and also the division by two at the end.
From a second perspective, if the two vectors are parallel and overlapping,
we can't get a nonzero perpendicular vector,
since there will be an infinite number of orthogonal vectors.
To simplify the solution we will not calculate the length,
but we will decide directly from the vector whether it is equal to (0, 0, 0) or not.
Read More:
https://math.stackexchange.com/a/1951650
"""
Vector3d = tuple[float, float, float]
Point3d = tuple[float, float, float]
def create_vector(end_point1: Point3d, end_point2: Point3d) -> Vector3d:
"""
Pass two points to get the vector from them in the form (x, y, z).
>>> create_vector((0, 0, 0), (1, 1, 1))
(1, 1, 1)
>>> create_vector((45, 70, 24), (47, 32, 1))
(2, -38, -23)
>>> create_vector((-14, -1, -8), (-7, 6, 4))
(7, 7, 12)
"""
x = end_point2[0] - end_point1[0]
y = end_point2[1] - end_point1[1]
z = end_point2[2] - end_point1[2]
return (x, y, z)
def get_3d_vectors_cross(ab: Vector3d, ac: Vector3d) -> Vector3d:
"""
Get the cross of the two vectors AB and AC.
I used determinant of 2x2 to get the determinant of the 3x3 matrix in the process.
Read More:
https://en.wikipedia.org/wiki/Cross_product
https://en.wikipedia.org/wiki/Determinant
>>> get_3d_vectors_cross((3, 4, 7), (4, 9, 2))
(-55, 22, 11)
>>> get_3d_vectors_cross((1, 1, 1), (1, 1, 1))
(0, 0, 0)
>>> get_3d_vectors_cross((-4, 3, 0), (3, -9, -12))
(-36, -48, 27)
>>> get_3d_vectors_cross((17.67, 4.7, 6.78), (-9.5, 4.78, -19.33))
(-123.2594, 277.15110000000004, 129.11260000000001)
"""
x = ab[1] * ac[2] - ab[2] * ac[1] # *i
y = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j
z = ab[0] * ac[1] - ab[1] * ac[0] # *k
return (x, y, z)
def is_zero_vector(vector: Vector3d, accuracy: int) -> bool:
"""
Check if vector is equal to (0, 0, 0) of not.
Sine the algorithm is very accurate, we will never get a zero vector,
so we need to round the vector axis,
because we want a result that is either True or False.
In other applications, we can return a float that represents the collinearity ratio.
>>> is_zero_vector((0, 0, 0), accuracy=10)
True
>>> is_zero_vector((15, 74, 32), accuracy=10)
False
>>> is_zero_vector((-15, -74, -32), accuracy=10)
False
"""
return tuple(round(x, accuracy) for x in vector) == (0, 0, 0)
def are_collinear(a: Point3d, b: Point3d, c: Point3d, accuracy: int = 10) -> bool:
"""
Check if three points are collinear or not.
1- Create tow vectors AB and AC.
2- Get the cross vector of the tow vectors.
3- Calcolate the length of the cross vector.
4- If the length is zero then the points are collinear, else they are not.
The use of the accuracy parameter is explained in is_zero_vector docstring.
>>> are_collinear((4.802293498137402, 3.536233125455244, 0),
... (-2.186788107953106, -9.24561398001649, 7.141509524846482),
... (1.530169574640268, -2.447927606600034, 3.343487096469054))
True
>>> are_collinear((-6, -2, 6),
... (6.200213806439997, -4.930157614926678, -4.482371908289856),
... (-4.085171149525941, -2.459889509029438, 4.354787180795383))
True
>>> are_collinear((2.399001826862445, -2.452009976680793, 4.464656666157666),
... (-3.682816335934376, 5.753788986533145, 9.490993909044244),
... (1.962903518985307, 3.741415730125627, 7))
False
>>> are_collinear((1.875375340689544, -7.268426006071538, 7.358196269835993),
... (-3.546599383667157, -4.630005261513976, 3.208784032924246),
... (-2.564606140206386, 3.937845170672183, 7))
False
"""
ab = create_vector(a, b)
ac = create_vector(a, c)
return is_zero_vector(get_3d_vectors_cross(ab, ac), accuracy)
| """
Check if three points are collinear in 3D.
In short, the idea is that we are able to create a triangle using three points,
and the area of that triangle can determine if the three points are collinear or not.
First, we create two vectors with the same initial point from the three points,
then we will calculate the cross-product of them.
The length of the cross vector is numerically equal to the area of a parallelogram.
Finally, the area of the triangle is equal to half of the area of the parallelogram.
Since we are only differentiating between zero and anything else,
we can get rid of the square root when calculating the length of the vector,
and also the division by two at the end.
From a second perspective, if the two vectors are parallel and overlapping,
we can't get a nonzero perpendicular vector,
since there will be an infinite number of orthogonal vectors.
To simplify the solution we will not calculate the length,
but we will decide directly from the vector whether it is equal to (0, 0, 0) or not.
Read More:
https://math.stackexchange.com/a/1951650
"""
Vector3d = tuple[float, float, float]
Point3d = tuple[float, float, float]
def create_vector(end_point1: Point3d, end_point2: Point3d) -> Vector3d:
"""
Pass two points to get the vector from them in the form (x, y, z).
>>> create_vector((0, 0, 0), (1, 1, 1))
(1, 1, 1)
>>> create_vector((45, 70, 24), (47, 32, 1))
(2, -38, -23)
>>> create_vector((-14, -1, -8), (-7, 6, 4))
(7, 7, 12)
"""
x = end_point2[0] - end_point1[0]
y = end_point2[1] - end_point1[1]
z = end_point2[2] - end_point1[2]
return (x, y, z)
def get_3d_vectors_cross(ab: Vector3d, ac: Vector3d) -> Vector3d:
"""
Get the cross of the two vectors AB and AC.
I used determinant of 2x2 to get the determinant of the 3x3 matrix in the process.
Read More:
https://en.wikipedia.org/wiki/Cross_product
https://en.wikipedia.org/wiki/Determinant
>>> get_3d_vectors_cross((3, 4, 7), (4, 9, 2))
(-55, 22, 11)
>>> get_3d_vectors_cross((1, 1, 1), (1, 1, 1))
(0, 0, 0)
>>> get_3d_vectors_cross((-4, 3, 0), (3, -9, -12))
(-36, -48, 27)
>>> get_3d_vectors_cross((17.67, 4.7, 6.78), (-9.5, 4.78, -19.33))
(-123.2594, 277.15110000000004, 129.11260000000001)
"""
x = ab[1] * ac[2] - ab[2] * ac[1] # *i
y = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j
z = ab[0] * ac[1] - ab[1] * ac[0] # *k
return (x, y, z)
def is_zero_vector(vector: Vector3d, accuracy: int) -> bool:
"""
Check if vector is equal to (0, 0, 0) of not.
Sine the algorithm is very accurate, we will never get a zero vector,
so we need to round the vector axis,
because we want a result that is either True or False.
In other applications, we can return a float that represents the collinearity ratio.
>>> is_zero_vector((0, 0, 0), accuracy=10)
True
>>> is_zero_vector((15, 74, 32), accuracy=10)
False
>>> is_zero_vector((-15, -74, -32), accuracy=10)
False
"""
return tuple(round(x, accuracy) for x in vector) == (0, 0, 0)
def are_collinear(a: Point3d, b: Point3d, c: Point3d, accuracy: int = 10) -> bool:
"""
Check if three points are collinear or not.
1- Create tow vectors AB and AC.
2- Get the cross vector of the tow vectors.
3- Calcolate the length of the cross vector.
4- If the length is zero then the points are collinear, else they are not.
The use of the accuracy parameter is explained in is_zero_vector docstring.
>>> are_collinear((4.802293498137402, 3.536233125455244, 0),
... (-2.186788107953106, -9.24561398001649, 7.141509524846482),
... (1.530169574640268, -2.447927606600034, 3.343487096469054))
True
>>> are_collinear((-6, -2, 6),
... (6.200213806439997, -4.930157614926678, -4.482371908289856),
... (-4.085171149525941, -2.459889509029438, 4.354787180795383))
True
>>> are_collinear((2.399001826862445, -2.452009976680793, 4.464656666157666),
... (-3.682816335934376, 5.753788986533145, 9.490993909044244),
... (1.962903518985307, 3.741415730125627, 7))
False
>>> are_collinear((1.875375340689544, -7.268426006071538, 7.358196269835993),
... (-3.546599383667157, -4.630005261513976, 3.208784032924246),
... (-2.564606140206386, 3.937845170672183, 7))
False
"""
ab = create_vector(a, b)
ac = create_vector(a, c)
return is_zero_vector(get_3d_vectors_cross(ab, ac), accuracy)
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Problem 44: https://projecteuler.net/problem=44
Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten
pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference,
70 − 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference
are pentagonal and D = |Pk − Pj| is minimised; what is the value of D?
"""
def is_pentagonal(n: int) -> bool:
"""
Returns True if n is pentagonal, False otherwise.
>>> is_pentagonal(330)
True
>>> is_pentagonal(7683)
False
>>> is_pentagonal(2380)
True
"""
root = (1 + 24 * n) ** 0.5
return ((1 + root) / 6) % 1 == 0
def solution(limit: int = 5000) -> int:
"""
Returns the minimum difference of two pentagonal numbers P1 and P2 such that
P1 + P2 is pentagonal and P2 - P1 is pentagonal.
>>> solution(5000)
5482660
"""
pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)]
for i, pentagonal_i in enumerate(pentagonal_nums):
for j in range(i, len(pentagonal_nums)):
pentagonal_j = pentagonal_nums[j]
a = pentagonal_i + pentagonal_j
b = pentagonal_j - pentagonal_i
if is_pentagonal(a) and is_pentagonal(b):
return b
return -1
if __name__ == "__main__":
print(f"{solution() = }")
| """
Problem 44: https://projecteuler.net/problem=44
Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten
pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference,
70 − 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference
are pentagonal and D = |Pk − Pj| is minimised; what is the value of D?
"""
def is_pentagonal(n: int) -> bool:
"""
Returns True if n is pentagonal, False otherwise.
>>> is_pentagonal(330)
True
>>> is_pentagonal(7683)
False
>>> is_pentagonal(2380)
True
"""
root = (1 + 24 * n) ** 0.5
return ((1 + root) / 6) % 1 == 0
def solution(limit: int = 5000) -> int:
"""
Returns the minimum difference of two pentagonal numbers P1 and P2 such that
P1 + P2 is pentagonal and P2 - P1 is pentagonal.
>>> solution(5000)
5482660
"""
pentagonal_nums = [(i * (3 * i - 1)) // 2 for i in range(1, limit)]
for i, pentagonal_i in enumerate(pentagonal_nums):
for j in range(i, len(pentagonal_nums)):
pentagonal_j = pentagonal_nums[j]
a = pentagonal_i + pentagonal_j
b = pentagonal_j - pentagonal_i
if is_pentagonal(a) and is_pentagonal(b):
return b
return -1
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Eulers Totient function finds the number of relative primes of a number n from 1 to n
def totient(n: int) -> list:
is_prime = [True for i in range(n + 1)]
totients = [i - 1 for i in range(n + 1)]
primes = []
for i in range(2, n + 1):
if is_prime[i]:
primes.append(i)
for j in range(0, len(primes)):
if i * primes[j] >= n:
break
is_prime[i * primes[j]] = False
if i % primes[j] == 0:
totients[i * primes[j]] = totients[i] * primes[j]
break
totients[i * primes[j]] = totients[i] * (primes[j] - 1)
return totients
def test_totient() -> None:
"""
>>> n = 10
>>> totient_calculation = totient(n)
>>> for i in range(1, n):
... print(f"{i} has {totient_calculation[i]} relative primes.")
1 has 0 relative primes.
2 has 1 relative primes.
3 has 2 relative primes.
4 has 2 relative primes.
5 has 4 relative primes.
6 has 2 relative primes.
7 has 6 relative primes.
8 has 4 relative primes.
9 has 6 relative primes.
"""
pass
if __name__ == "__main__":
import doctest
doctest.testmod()
| # Eulers Totient function finds the number of relative primes of a number n from 1 to n
def totient(n: int) -> list:
is_prime = [True for i in range(n + 1)]
totients = [i - 1 for i in range(n + 1)]
primes = []
for i in range(2, n + 1):
if is_prime[i]:
primes.append(i)
for j in range(0, len(primes)):
if i * primes[j] >= n:
break
is_prime[i * primes[j]] = False
if i % primes[j] == 0:
totients[i * primes[j]] = totients[i] * primes[j]
break
totients[i * primes[j]] = totients[i] * (primes[j] - 1)
return totients
def test_totient() -> None:
"""
>>> n = 10
>>> totient_calculation = totient(n)
>>> for i in range(1, n):
... print(f"{i} has {totient_calculation[i]} relative primes.")
1 has 0 relative primes.
2 has 1 relative primes.
3 has 2 relative primes.
4 has 2 relative primes.
5 has 4 relative primes.
6 has 2 relative primes.
7 has 6 relative primes.
8 has 4 relative primes.
9 has 6 relative primes.
"""
pass
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # 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 | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Author: 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 | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from random import randint
from tempfile import TemporaryFile
import numpy as np
def _inPlaceQuickSort(A, start, end):
count = 0
if start < end:
pivot = randint(start, end)
temp = A[end]
A[end] = A[pivot]
A[pivot] = temp
p, count = _inPlacePartition(A, start, end)
count += _inPlaceQuickSort(A, start, p - 1)
count += _inPlaceQuickSort(A, p + 1, end)
return count
def _inPlacePartition(A, start, end):
count = 0
pivot = randint(start, end)
temp = A[end]
A[end] = A[pivot]
A[pivot] = temp
newPivotIndex = start - 1
for index in range(start, end):
count += 1
if A[index] < A[end]: # check if current val is less than pivot value
newPivotIndex = newPivotIndex + 1
temp = A[newPivotIndex]
A[newPivotIndex] = A[index]
A[index] = temp
temp = A[newPivotIndex + 1]
A[newPivotIndex + 1] = A[end]
A[end] = temp
return newPivotIndex + 1, count
outfile = TemporaryFile()
p = 100 # 1000 elements are to be sorted
mu, sigma = 0, 1 # mean and standard deviation
X = np.random.normal(mu, sigma, p)
np.save(outfile, X)
print("The array is")
print(X)
outfile.seek(0) # using the same array
M = np.load(outfile)
r = len(M) - 1
z = _inPlaceQuickSort(M, 0, r)
print(
"No of Comparisons for 100 elements selected from a standard normal distribution"
"is :"
)
print(z)
| from random import randint
from tempfile import TemporaryFile
import numpy as np
def _inPlaceQuickSort(A, start, end):
count = 0
if start < end:
pivot = randint(start, end)
temp = A[end]
A[end] = A[pivot]
A[pivot] = temp
p, count = _inPlacePartition(A, start, end)
count += _inPlaceQuickSort(A, start, p - 1)
count += _inPlaceQuickSort(A, p + 1, end)
return count
def _inPlacePartition(A, start, end):
count = 0
pivot = randint(start, end)
temp = A[end]
A[end] = A[pivot]
A[pivot] = temp
newPivotIndex = start - 1
for index in range(start, end):
count += 1
if A[index] < A[end]: # check if current val is less than pivot value
newPivotIndex = newPivotIndex + 1
temp = A[newPivotIndex]
A[newPivotIndex] = A[index]
A[index] = temp
temp = A[newPivotIndex + 1]
A[newPivotIndex + 1] = A[end]
A[end] = temp
return newPivotIndex + 1, count
outfile = TemporaryFile()
p = 100 # 1000 elements are to be sorted
mu, sigma = 0, 1 # mean and standard deviation
X = np.random.normal(mu, sigma, p)
np.save(outfile, X)
print("The array is")
print(X)
outfile.seek(0) # using the same array
M = np.load(outfile)
r = len(M) - 1
z = _inPlaceQuickSort(M, 0, r)
print(
"No of Comparisons for 100 elements selected from a standard normal distribution"
"is :"
)
print(z)
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 35
https://projecteuler.net/problem=35
Problem Statement:
The number 197 is called a circular prime because all rotations of the digits:
197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73,
79, and 97.
How many circular primes are there below one million?
To solve this problem in an efficient manner, we will first mark all the primes
below 1 million using the Seive of Eratosthenes. Then, out of all these primes,
we will rule out the numbers which contain an even digit. After this we will
generate each circular combination of the number and check if all are prime.
"""
from __future__ import annotations
seive = [True] * 1000001
i = 2
while i * i <= 1000000:
if seive[i]:
for j in range(i * i, 1000001, i):
seive[j] = False
i += 1
def is_prime(n: int) -> bool:
"""
For 2 <= n <= 1000000, return True if n is prime.
>>> is_prime(87)
False
>>> is_prime(23)
True
>>> is_prime(25363)
False
"""
return seive[n]
def contains_an_even_digit(n: int) -> bool:
"""
Return True if n contains an even digit.
>>> contains_an_even_digit(0)
True
>>> contains_an_even_digit(975317933)
False
>>> contains_an_even_digit(-245679)
True
"""
return any(digit in "02468" for digit in str(n))
def find_circular_primes(limit: int = 1000000) -> list[int]:
"""
Return circular primes below limit.
>>> len(find_circular_primes(100))
13
>>> len(find_circular_primes(1000000))
55
"""
result = [2] # result already includes the number 2.
for num in range(3, limit + 1, 2):
if is_prime(num) and not contains_an_even_digit(num):
str_num = str(num)
list_nums = [int(str_num[j:] + str_num[:j]) for j in range(len(str_num))]
if all(is_prime(i) for i in list_nums):
result.append(num)
return result
def solution() -> int:
"""
>>> solution()
55
"""
return len(find_circular_primes())
if __name__ == "__main__":
print(f"{len(find_circular_primes()) = }")
| """
Project Euler Problem 35
https://projecteuler.net/problem=35
Problem Statement:
The number 197 is called a circular prime because all rotations of the digits:
197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73,
79, and 97.
How many circular primes are there below one million?
To solve this problem in an efficient manner, we will first mark all the primes
below 1 million using the Seive of Eratosthenes. Then, out of all these primes,
we will rule out the numbers which contain an even digit. After this we will
generate each circular combination of the number and check if all are prime.
"""
from __future__ import annotations
seive = [True] * 1000001
i = 2
while i * i <= 1000000:
if seive[i]:
for j in range(i * i, 1000001, i):
seive[j] = False
i += 1
def is_prime(n: int) -> bool:
"""
For 2 <= n <= 1000000, return True if n is prime.
>>> is_prime(87)
False
>>> is_prime(23)
True
>>> is_prime(25363)
False
"""
return seive[n]
def contains_an_even_digit(n: int) -> bool:
"""
Return True if n contains an even digit.
>>> contains_an_even_digit(0)
True
>>> contains_an_even_digit(975317933)
False
>>> contains_an_even_digit(-245679)
True
"""
return any(digit in "02468" for digit in str(n))
def find_circular_primes(limit: int = 1000000) -> list[int]:
"""
Return circular primes below limit.
>>> len(find_circular_primes(100))
13
>>> len(find_circular_primes(1000000))
55
"""
result = [2] # result already includes the number 2.
for num in range(3, limit + 1, 2):
if is_prime(num) and not contains_an_even_digit(num):
str_num = str(num)
list_nums = [int(str_num[j:] + str_num[:j]) for j in range(len(str_num))]
if all(is_prime(i) for i in list_nums):
result.append(num)
return result
def solution() -> int:
"""
>>> solution()
55
"""
return len(find_circular_primes())
if __name__ == "__main__":
print(f"{len(find_circular_primes()) = }")
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Cellular Automata
Cellular automata are a way to simulate the behavior of "life", no matter if it is a robot or cell.
They usually follow simple rules but can lead to the creation of complex forms.
The most popular cellular automaton is Conway's [Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life).
* <https://en.wikipedia.org/wiki/Cellular_automaton>
* <https://mathworld.wolfram.com/ElementaryCellularAutomaton.html>
| # Cellular Automata
Cellular automata are a way to simulate the behavior of "life", no matter if it is a robot or cell.
They usually follow simple rules but can lead to the creation of complex forms.
The most popular cellular automaton is Conway's [Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life).
* <https://en.wikipedia.org/wiki/Cellular_automaton>
* <https://mathworld.wolfram.com/ElementaryCellularAutomaton.html>
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| def remove_duplicates(key: str) -> str:
"""
Removes duplicate alphabetic characters in a keyword (letter is ignored after its
first appearance).
:param key: Keyword to use
:return: String with duplicates removed
>>> remove_duplicates('Hello World!!')
'Helo Wrd'
"""
key_no_dups = ""
for ch in key:
if ch == " " or ch not in key_no_dups and ch.isalpha():
key_no_dups += ch
return key_no_dups
def create_cipher_map(key: str) -> dict[str, str]:
"""
Returns a cipher map given a keyword.
:param key: keyword to use
:return: dictionary cipher map
"""
# Create alphabet list
alphabet = [chr(i + 65) for i in range(26)]
# Remove duplicate characters from key
key = remove_duplicates(key.upper())
offset = len(key)
# First fill cipher with key characters
cipher_alphabet = {alphabet[i]: char for i, char in enumerate(key)}
# Then map remaining characters in alphabet to
# the alphabet from the beginning
for i in range(len(cipher_alphabet), 26):
char = alphabet[i - offset]
# Ensure we are not mapping letters to letters previously mapped
while char in key:
offset -= 1
char = alphabet[i - offset]
cipher_alphabet[alphabet[i]] = char
return cipher_alphabet
def encipher(message: str, cipher_map: dict[str, str]) -> str:
"""
Enciphers a message given a cipher map.
:param message: Message to encipher
:param cipher_map: Cipher map
:return: enciphered string
>>> encipher('Hello World!!', create_cipher_map('Goodbye!!'))
'CYJJM VMQJB!!'
"""
return "".join(cipher_map.get(ch, ch) for ch in message.upper())
def decipher(message: str, cipher_map: dict[str, str]) -> str:
"""
Deciphers a message given a cipher map
:param message: Message to decipher
:param cipher_map: Dictionary mapping to use
:return: Deciphered string
>>> cipher_map = create_cipher_map('Goodbye!!')
>>> decipher(encipher('Hello World!!', cipher_map), cipher_map)
'HELLO WORLD!!'
"""
# Reverse our cipher mappings
rev_cipher_map = {v: k for k, v in cipher_map.items()}
return "".join(rev_cipher_map.get(ch, ch) for ch in message.upper())
def main() -> None:
"""
Handles I/O
:return: void
"""
message = input("Enter message to encode or decode: ").strip()
key = input("Enter keyword: ").strip()
option = input("Encipher or decipher? E/D:").strip()[0].lower()
try:
func = {"e": encipher, "d": decipher}[option]
except KeyError:
raise KeyError("invalid input option")
cipher_map = create_cipher_map(key)
print(func(message, cipher_map))
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| def remove_duplicates(key: str) -> str:
"""
Removes duplicate alphabetic characters in a keyword (letter is ignored after its
first appearance).
:param key: Keyword to use
:return: String with duplicates removed
>>> remove_duplicates('Hello World!!')
'Helo Wrd'
"""
key_no_dups = ""
for ch in key:
if ch == " " or ch not in key_no_dups and ch.isalpha():
key_no_dups += ch
return key_no_dups
def create_cipher_map(key: str) -> dict[str, str]:
"""
Returns a cipher map given a keyword.
:param key: keyword to use
:return: dictionary cipher map
"""
# Create alphabet list
alphabet = [chr(i + 65) for i in range(26)]
# Remove duplicate characters from key
key = remove_duplicates(key.upper())
offset = len(key)
# First fill cipher with key characters
cipher_alphabet = {alphabet[i]: char for i, char in enumerate(key)}
# Then map remaining characters in alphabet to
# the alphabet from the beginning
for i in range(len(cipher_alphabet), 26):
char = alphabet[i - offset]
# Ensure we are not mapping letters to letters previously mapped
while char in key:
offset -= 1
char = alphabet[i - offset]
cipher_alphabet[alphabet[i]] = char
return cipher_alphabet
def encipher(message: str, cipher_map: dict[str, str]) -> str:
"""
Enciphers a message given a cipher map.
:param message: Message to encipher
:param cipher_map: Cipher map
:return: enciphered string
>>> encipher('Hello World!!', create_cipher_map('Goodbye!!'))
'CYJJM VMQJB!!'
"""
return "".join(cipher_map.get(ch, ch) for ch in message.upper())
def decipher(message: str, cipher_map: dict[str, str]) -> str:
"""
Deciphers a message given a cipher map
:param message: Message to decipher
:param cipher_map: Dictionary mapping to use
:return: Deciphered string
>>> cipher_map = create_cipher_map('Goodbye!!')
>>> decipher(encipher('Hello World!!', cipher_map), cipher_map)
'HELLO WORLD!!'
"""
# Reverse our cipher mappings
rev_cipher_map = {v: k for k, v in cipher_map.items()}
return "".join(rev_cipher_map.get(ch, ch) for ch in message.upper())
def main() -> None:
"""
Handles I/O
:return: void
"""
message = input("Enter message to encode or decode: ").strip()
key = input("Enter keyword: ").strip()
option = input("Encipher or decipher? E/D:").strip()[0].lower()
try:
func = {"e": encipher, "d": decipher}[option]
except KeyError:
raise KeyError("invalid input option")
cipher_map = create_cipher_map(key)
print(func(message, cipher_map))
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from __future__ import annotations
def double_linear_search(array: list[int], search_item: int) -> int:
"""
Iterate through the array from both sides to find the index of search_item.
:param array: the array to be searched
:param search_item: the item to be searched
:return the index of search_item, if search_item is in array, else -1
Examples:
>>> double_linear_search([1, 5, 5, 10], 1)
0
>>> double_linear_search([1, 5, 5, 10], 5)
1
>>> double_linear_search([1, 5, 5, 10], 100)
-1
>>> double_linear_search([1, 5, 5, 10], 10)
3
"""
# define the start and end index of the given array
start_ind, end_ind = 0, len(array) - 1
while start_ind <= end_ind:
if array[start_ind] == search_item:
return start_ind
elif array[end_ind] == search_item:
return end_ind
else:
start_ind += 1
end_ind -= 1
# returns -1 if search_item is not found in array
return -1
if __name__ == "__main__":
print(double_linear_search(list(range(100)), 40))
| from __future__ import annotations
def double_linear_search(array: list[int], search_item: int) -> int:
"""
Iterate through the array from both sides to find the index of search_item.
:param array: the array to be searched
:param search_item: the item to be searched
:return the index of search_item, if search_item is in array, else -1
Examples:
>>> double_linear_search([1, 5, 5, 10], 1)
0
>>> double_linear_search([1, 5, 5, 10], 5)
1
>>> double_linear_search([1, 5, 5, 10], 100)
-1
>>> double_linear_search([1, 5, 5, 10], 10)
3
"""
# define the start and end index of the given array
start_ind, end_ind = 0, len(array) - 1
while start_ind <= end_ind:
if array[start_ind] == search_item:
return start_ind
elif array[end_ind] == search_item:
return end_ind
else:
start_ind += 1
end_ind -= 1
# returns -1 if search_item is not found in array
return -1
if __name__ == "__main__":
print(double_linear_search(list(range(100)), 40))
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Frequency Finder
import string
# frequency taken from http://en.wikipedia.org/wiki/Letter_frequency
english_letter_freq = {
"E": 12.70,
"T": 9.06,
"A": 8.17,
"O": 7.51,
"I": 6.97,
"N": 6.75,
"S": 6.33,
"H": 6.09,
"R": 5.99,
"D": 4.25,
"L": 4.03,
"C": 2.78,
"U": 2.76,
"M": 2.41,
"W": 2.36,
"F": 2.23,
"G": 2.02,
"Y": 1.97,
"P": 1.93,
"B": 1.29,
"V": 0.98,
"K": 0.77,
"J": 0.15,
"X": 0.15,
"Q": 0.10,
"Z": 0.07,
}
ETAOIN = "ETAOINSHRDLCUMWFGYPBVKJXQZ"
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def get_letter_count(message: str) -> dict[str, int]:
letter_count = {letter: 0 for letter in string.ascii_uppercase}
for letter in message.upper():
if letter in LETTERS:
letter_count[letter] += 1
return letter_count
def get_item_at_index_zero(x: tuple) -> str:
return x[0]
def get_frequency_order(message: str) -> str:
letter_to_freq = get_letter_count(message)
freq_to_letter: dict[int, list[str]] = {
freq: [] for letter, freq in letter_to_freq.items()
}
for letter in LETTERS:
freq_to_letter[letter_to_freq[letter]].append(letter)
freq_to_letter_str: dict[int, str] = {}
for freq in freq_to_letter:
freq_to_letter[freq].sort(key=ETAOIN.find, reverse=True)
freq_to_letter_str[freq] = "".join(freq_to_letter[freq])
freq_pairs = list(freq_to_letter_str.items())
freq_pairs.sort(key=get_item_at_index_zero, reverse=True)
freq_order: list[str] = [freq_pair[1] for freq_pair in freq_pairs]
return "".join(freq_order)
def english_freq_match_score(message: str) -> int:
"""
>>> english_freq_match_score('Hello World')
1
"""
freq_order = get_frequency_order(message)
match_score = 0
for common_letter in ETAOIN[:6]:
if common_letter in freq_order[:6]:
match_score += 1
for uncommon_letter in ETAOIN[-6:]:
if uncommon_letter in freq_order[-6:]:
match_score += 1
return match_score
if __name__ == "__main__":
import doctest
doctest.testmod()
| # Frequency Finder
import string
# frequency taken from http://en.wikipedia.org/wiki/Letter_frequency
english_letter_freq = {
"E": 12.70,
"T": 9.06,
"A": 8.17,
"O": 7.51,
"I": 6.97,
"N": 6.75,
"S": 6.33,
"H": 6.09,
"R": 5.99,
"D": 4.25,
"L": 4.03,
"C": 2.78,
"U": 2.76,
"M": 2.41,
"W": 2.36,
"F": 2.23,
"G": 2.02,
"Y": 1.97,
"P": 1.93,
"B": 1.29,
"V": 0.98,
"K": 0.77,
"J": 0.15,
"X": 0.15,
"Q": 0.10,
"Z": 0.07,
}
ETAOIN = "ETAOINSHRDLCUMWFGYPBVKJXQZ"
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def get_letter_count(message: str) -> dict[str, int]:
letter_count = {letter: 0 for letter in string.ascii_uppercase}
for letter in message.upper():
if letter in LETTERS:
letter_count[letter] += 1
return letter_count
def get_item_at_index_zero(x: tuple) -> str:
return x[0]
def get_frequency_order(message: str) -> str:
letter_to_freq = get_letter_count(message)
freq_to_letter: dict[int, list[str]] = {
freq: [] for letter, freq in letter_to_freq.items()
}
for letter in LETTERS:
freq_to_letter[letter_to_freq[letter]].append(letter)
freq_to_letter_str: dict[int, str] = {}
for freq in freq_to_letter:
freq_to_letter[freq].sort(key=ETAOIN.find, reverse=True)
freq_to_letter_str[freq] = "".join(freq_to_letter[freq])
freq_pairs = list(freq_to_letter_str.items())
freq_pairs.sort(key=get_item_at_index_zero, reverse=True)
freq_order: list[str] = [freq_pair[1] for freq_pair in freq_pairs]
return "".join(freq_order)
def english_freq_match_score(message: str) -> int:
"""
>>> english_freq_match_score('Hello World')
1
"""
freq_order = get_frequency_order(message)
match_score = 0
for common_letter in ETAOIN[:6]:
if common_letter in freq_order[:6]:
match_score += 1
for uncommon_letter in ETAOIN[-6:]:
if uncommon_letter in freq_order[-6:]:
match_score += 1
return match_score
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Find the kth smallest element in linear time using divide and conquer.
Recall we can do this trivially in O(nlogn) time. Sort the list and
access kth element in constant time.
This is a divide and conquer algorithm that can find a solution in O(n) time.
For more information of this algorithm:
https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/08/Small08.pdf
"""
from __future__ import annotations
from random import choice
def random_pivot(lst):
"""
Choose a random pivot for the list.
We can use a more sophisticated algorithm here, such as the median-of-medians
algorithm.
"""
return choice(lst)
def kth_number(lst: list[int], k: int) -> int:
"""
Return the kth smallest number in lst.
>>> kth_number([2, 1, 3, 4, 5], 3)
3
>>> kth_number([2, 1, 3, 4, 5], 1)
1
>>> kth_number([2, 1, 3, 4, 5], 5)
5
>>> kth_number([3, 2, 5, 6, 7, 8], 2)
3
>>> kth_number([25, 21, 98, 100, 76, 22, 43, 60, 89, 87], 4)
43
"""
# pick a pivot and separate into list based on pivot.
pivot = random_pivot(lst)
# partition based on pivot
# linear time
small = [e for e in lst if e < pivot]
big = [e for e in lst if e > pivot]
# if we get lucky, pivot might be the element we want.
# we can easily see this:
# small (elements smaller than k)
# + pivot (kth element)
# + big (elements larger than k)
if len(small) == k - 1:
return pivot
# pivot is in elements bigger than k
elif len(small) < k - 1:
return kth_number(big, k - len(small) - 1)
# pivot is in elements smaller than k
else:
return kth_number(small, k)
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Find the kth smallest element in linear time using divide and conquer.
Recall we can do this trivially in O(nlogn) time. Sort the list and
access kth element in constant time.
This is a divide and conquer algorithm that can find a solution in O(n) time.
For more information of this algorithm:
https://web.stanford.edu/class/archive/cs/cs161/cs161.1138/lectures/08/Small08.pdf
"""
from __future__ import annotations
from random import choice
def random_pivot(lst):
"""
Choose a random pivot for the list.
We can use a more sophisticated algorithm here, such as the median-of-medians
algorithm.
"""
return choice(lst)
def kth_number(lst: list[int], k: int) -> int:
"""
Return the kth smallest number in lst.
>>> kth_number([2, 1, 3, 4, 5], 3)
3
>>> kth_number([2, 1, 3, 4, 5], 1)
1
>>> kth_number([2, 1, 3, 4, 5], 5)
5
>>> kth_number([3, 2, 5, 6, 7, 8], 2)
3
>>> kth_number([25, 21, 98, 100, 76, 22, 43, 60, 89, 87], 4)
43
"""
# pick a pivot and separate into list based on pivot.
pivot = random_pivot(lst)
# partition based on pivot
# linear time
small = [e for e in lst if e < pivot]
big = [e for e in lst if e > pivot]
# if we get lucky, pivot might be the element we want.
# we can easily see this:
# small (elements smaller than k)
# + pivot (kth element)
# + big (elements larger than k)
if len(small) == k - 1:
return pivot
# pivot is in elements bigger than k
elif len(small) < k - 1:
return kth_number(big, k - len(small) - 1)
# pivot is in elements smaller than k
else:
return kth_number(small, k)
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers. By convention,
1 is included.
Given an integer n, we have to find the nth ugly number.
For more details, refer this article
https://www.geeksforgeeks.org/ugly-numbers/
"""
def ugly_numbers(n: int) -> int:
"""
Returns the nth ugly number.
>>> ugly_numbers(100)
1536
>>> ugly_numbers(0)
1
>>> ugly_numbers(20)
36
>>> ugly_numbers(-5)
1
>>> ugly_numbers(-5.5)
Traceback (most recent call last):
...
TypeError: 'float' object cannot be interpreted as an integer
"""
ugly_nums = [1]
i2, i3, i5 = 0, 0, 0
next_2 = ugly_nums[i2] * 2
next_3 = ugly_nums[i3] * 3
next_5 = ugly_nums[i5] * 5
for i in range(1, n):
next_num = min(next_2, next_3, next_5)
ugly_nums.append(next_num)
if next_num == next_2:
i2 += 1
next_2 = ugly_nums[i2] * 2
if next_num == next_3:
i3 += 1
next_3 = ugly_nums[i3] * 3
if next_num == next_5:
i5 += 1
next_5 = ugly_nums[i5] * 5
return ugly_nums[-1]
if __name__ == "__main__":
from doctest import testmod
testmod(verbose=True)
print(f"{ugly_numbers(200) = }")
| """
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the first 11 ugly numbers. By convention,
1 is included.
Given an integer n, we have to find the nth ugly number.
For more details, refer this article
https://www.geeksforgeeks.org/ugly-numbers/
"""
def ugly_numbers(n: int) -> int:
"""
Returns the nth ugly number.
>>> ugly_numbers(100)
1536
>>> ugly_numbers(0)
1
>>> ugly_numbers(20)
36
>>> ugly_numbers(-5)
1
>>> ugly_numbers(-5.5)
Traceback (most recent call last):
...
TypeError: 'float' object cannot be interpreted as an integer
"""
ugly_nums = [1]
i2, i3, i5 = 0, 0, 0
next_2 = ugly_nums[i2] * 2
next_3 = ugly_nums[i3] * 3
next_5 = ugly_nums[i5] * 5
for i in range(1, n):
next_num = min(next_2, next_3, next_5)
ugly_nums.append(next_num)
if next_num == next_2:
i2 += 1
next_2 = ugly_nums[i2] * 2
if next_num == next_3:
i3 += 1
next_3 = ugly_nums[i3] * 3
if next_num == next_5:
i5 += 1
next_5 = ugly_nums[i5] * 5
return ugly_nums[-1]
if __name__ == "__main__":
from doctest import testmod
testmod(verbose=True)
print(f"{ugly_numbers(200) = }")
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import os
UPPERLETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + " \t\n"
def load_dictionary() -> dict[str, None]:
path = os.path.split(os.path.realpath(__file__))
english_words: dict[str, None] = {}
with open(path[0] + "/dictionary.txt") as dictionary_file:
for word in dictionary_file.read().split("\n"):
english_words[word] = None
return english_words
ENGLISH_WORDS = load_dictionary()
def get_english_count(message: str) -> float:
message = message.upper()
message = remove_non_letters(message)
possible_words = message.split()
if possible_words == []:
return 0.0
matches = 0
for word in possible_words:
if word in ENGLISH_WORDS:
matches += 1
return float(matches) / len(possible_words)
def remove_non_letters(message: str) -> str:
letters_only = []
for symbol in message:
if symbol in LETTERS_AND_SPACE:
letters_only.append(symbol)
return "".join(letters_only)
def is_english(
message: str, word_percentage: int = 20, letter_percentage: int = 85
) -> bool:
"""
>>> is_english('Hello World')
True
>>> is_english('llold HorWd')
False
"""
words_match = get_english_count(message) * 100 >= word_percentage
num_letters = len(remove_non_letters(message))
message_letters_percentage = (float(num_letters) / len(message)) * 100
letters_match = message_letters_percentage >= letter_percentage
return words_match and letters_match
if __name__ == "__main__":
import doctest
doctest.testmod()
| import os
UPPERLETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + " \t\n"
def load_dictionary() -> dict[str, None]:
path = os.path.split(os.path.realpath(__file__))
english_words: dict[str, None] = {}
with open(path[0] + "/dictionary.txt") as dictionary_file:
for word in dictionary_file.read().split("\n"):
english_words[word] = None
return english_words
ENGLISH_WORDS = load_dictionary()
def get_english_count(message: str) -> float:
message = message.upper()
message = remove_non_letters(message)
possible_words = message.split()
if possible_words == []:
return 0.0
matches = 0
for word in possible_words:
if word in ENGLISH_WORDS:
matches += 1
return float(matches) / len(possible_words)
def remove_non_letters(message: str) -> str:
letters_only = []
for symbol in message:
if symbol in LETTERS_AND_SPACE:
letters_only.append(symbol)
return "".join(letters_only)
def is_english(
message: str, word_percentage: int = 20, letter_percentage: int = 85
) -> bool:
"""
>>> is_english('Hello World')
True
>>> is_english('llold HorWd')
False
"""
words_match = get_english_count(message) * 100 >= word_percentage
num_letters = len(remove_non_letters(message))
message_letters_percentage = (float(num_letters) / len(message)) * 100
letters_match = message_letters_percentage >= letter_percentage
return words_match and letters_match
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Wikipedia: https://en.wikipedia.org/wiki/Enigma_machine
Video explanation: https://youtu.be/QwQVMqfoB2E
Also check out Numberphile's and Computerphile's videos on this topic
This module contains function 'enigma' which emulates
the famous Enigma machine from WWII.
Module includes:
- enigma function
- showcase of function usage
- 9 randomly generated rotors
- reflector (aka static rotor)
- original alphabet
Created by TrapinchO
"""
from __future__ import annotations
RotorPositionT = tuple[int, int, int]
RotorSelectionT = tuple[str, str, str]
# used alphabet --------------------------
# from string.ascii_uppercase
abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# -------------------------- default selection --------------------------
# rotors --------------------------
rotor1 = "EGZWVONAHDCLFQMSIPJBYUKXTR"
rotor2 = "FOBHMDKEXQNRAULPGSJVTYICZW"
rotor3 = "ZJXESIUQLHAVRMDOYGTNFWPBKC"
# reflector --------------------------
reflector = {
"A": "N",
"N": "A",
"B": "O",
"O": "B",
"C": "P",
"P": "C",
"D": "Q",
"Q": "D",
"E": "R",
"R": "E",
"F": "S",
"S": "F",
"G": "T",
"T": "G",
"H": "U",
"U": "H",
"I": "V",
"V": "I",
"J": "W",
"W": "J",
"K": "X",
"X": "K",
"L": "Y",
"Y": "L",
"M": "Z",
"Z": "M",
}
# -------------------------- extra rotors --------------------------
rotor4 = "RMDJXFUWGISLHVTCQNKYPBEZOA"
rotor5 = "SGLCPQWZHKXAREONTFBVIYJUDM"
rotor6 = "HVSICLTYKQUBXDWAJZOMFGPREN"
rotor7 = "RZWQHFMVDBKICJLNTUXAGYPSOE"
rotor8 = "LFKIJODBEGAMQPXVUHYSTCZRWN"
rotor9 = "KOAEGVDHXPQZMLFTYWJNBRCIUS"
def _validator(
rotpos: RotorPositionT, rotsel: RotorSelectionT, pb: str
) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]:
"""
Checks if the values can be used for the 'enigma' function
>>> _validator((1,1,1), (rotor1, rotor2, rotor3), 'POLAND')
((1, 1, 1), ('EGZWVONAHDCLFQMSIPJBYUKXTR', 'FOBHMDKEXQNRAULPGSJVTYICZW', \
'ZJXESIUQLHAVRMDOYGTNFWPBKC'), \
{'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'})
:param rotpos: rotor_positon
:param rotsel: rotor_selection
:param pb: plugb -> validated and transformed
:return: (rotpos, rotsel, pb)
"""
# Checks if there are 3 unique rotors
unique_rotsel = len(set(rotsel))
if unique_rotsel < 3:
raise Exception(f"Please use 3 unique rotors (not {unique_rotsel})")
# Checks if rotor positions are valid
rotorpos1, rotorpos2, rotorpos3 = rotpos
if not 0 < rotorpos1 <= len(abc):
raise ValueError(
"First rotor position is not within range of 1..26 (" f"{rotorpos1}"
)
if not 0 < rotorpos2 <= len(abc):
raise ValueError(
"Second rotor position is not within range of 1..26 (" f"{rotorpos2})"
)
if not 0 < rotorpos3 <= len(abc):
raise ValueError(
"Third rotor position is not within range of 1..26 (" f"{rotorpos3})"
)
# Validates string and returns dict
pbdict = _plugboard(pb)
return rotpos, rotsel, pbdict
def _plugboard(pbstring: str) -> dict[str, str]:
"""
https://en.wikipedia.org/wiki/Enigma_machine#Plugboard
>>> _plugboard('PICTURES')
{'P': 'I', 'I': 'P', 'C': 'T', 'T': 'C', 'U': 'R', 'R': 'U', 'E': 'S', 'S': 'E'}
>>> _plugboard('POLAND')
{'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'}
In the code, 'pb' stands for 'plugboard'
Pairs can be separated by spaces
:param pbstring: string containing plugboard setting for the Enigma machine
:return: dictionary containing converted pairs
"""
# tests the input string if it
# a) is type string
# b) has even length (so pairs can be made)
if not isinstance(pbstring, str):
raise TypeError(f"Plugboard setting isn't type string ({type(pbstring)})")
elif len(pbstring) % 2 != 0:
raise Exception(f"Odd number of symbols ({len(pbstring)})")
elif pbstring == "":
return {}
pbstring.replace(" ", "")
# Checks if all characters are unique
tmppbl = set()
for i in pbstring:
if i not in abc:
raise Exception(f"'{i}' not in list of symbols")
elif i in tmppbl:
raise Exception(f"Duplicate symbol ({i})")
else:
tmppbl.add(i)
del tmppbl
# Created the dictionary
pb = {}
for j in range(0, len(pbstring) - 1, 2):
pb[pbstring[j]] = pbstring[j + 1]
pb[pbstring[j + 1]] = pbstring[j]
return pb
def enigma(
text: str,
rotor_position: RotorPositionT,
rotor_selection: RotorSelectionT = (rotor1, rotor2, rotor3),
plugb: str = "",
) -> str:
"""
The only difference with real-world enigma is that I allowed string input.
All characters are converted to uppercase. (non-letter symbol are ignored)
How it works:
(for every letter in the message)
- Input letter goes into the plugboard.
If it is connected to another one, switch it.
- Letter goes through 3 rotors.
Each rotor can be represented as 2 sets of symbol, where one is shuffled.
Each symbol from the first set has corresponding symbol in
the second set and vice versa.
example:
| ABCDEFGHIJKLMNOPQRSTUVWXYZ | e.g. F=D and D=F
| VKLEPDBGRNWTFCJOHQAMUZYIXS |
- Symbol then goes through reflector (static rotor).
There it is switched with paired symbol
The reflector can be represented as2 sets, each with half of the alphanet.
There are usually 10 pairs of letters.
Example:
| ABCDEFGHIJKLM | e.g. E is paired to X
| ZYXWVUTSRQPON | so when E goes in X goes out and vice versa
- Letter then goes through the rotors again
- If the letter is connected to plugboard, it is switched.
- Return the letter
>>> enigma('Hello World!', (1, 2, 1), plugb='pictures')
'KORYH JUHHI!'
>>> enigma('KORYH, juhhi!', (1, 2, 1), plugb='pictures')
'HELLO, WORLD!'
>>> enigma('hello world!', (1, 1, 1), plugb='pictures')
'FPNCZ QWOBU!'
>>> enigma('FPNCZ QWOBU', (1, 1, 1), plugb='pictures')
'HELLO WORLD'
:param text: input message
:param rotor_position: tuple with 3 values in range 1..26
:param rotor_selection: tuple with 3 rotors ()
:param plugb: string containing plugboard configuration (default '')
:return: en/decrypted string
"""
text = text.upper()
rotor_position, rotor_selection, plugboard = _validator(
rotor_position, rotor_selection, plugb.upper()
)
rotorpos1, rotorpos2, rotorpos3 = rotor_position
rotor1, rotor2, rotor3 = rotor_selection
rotorpos1 -= 1
rotorpos2 -= 1
rotorpos3 -= 1
result = []
# encryption/decryption process --------------------------
for symbol in text:
if symbol in abc:
# 1st plugboard --------------------------
if symbol in plugboard:
symbol = plugboard[symbol]
# rotor ra --------------------------
index = abc.index(symbol) + rotorpos1
symbol = rotor1[index % len(abc)]
# rotor rb --------------------------
index = abc.index(symbol) + rotorpos2
symbol = rotor2[index % len(abc)]
# rotor rc --------------------------
index = abc.index(symbol) + rotorpos3
symbol = rotor3[index % len(abc)]
# reflector --------------------------
# this is the reason you don't need another machine to decipher
symbol = reflector[symbol]
# 2nd rotors
symbol = abc[rotor3.index(symbol) - rotorpos3]
symbol = abc[rotor2.index(symbol) - rotorpos2]
symbol = abc[rotor1.index(symbol) - rotorpos1]
# 2nd plugboard
if symbol in plugboard:
symbol = plugboard[symbol]
# moves/resets rotor positions
rotorpos1 += 1
if rotorpos1 >= len(abc):
rotorpos1 = 0
rotorpos2 += 1
if rotorpos2 >= len(abc):
rotorpos2 = 0
rotorpos3 += 1
if rotorpos3 >= len(abc):
rotorpos3 = 0
# else:
# pass
# Error could be also raised
# raise ValueError(
# 'Invalid symbol('+repr(symbol)+')')
result.append(symbol)
return "".join(result)
if __name__ == "__main__":
message = "This is my Python script that emulates the Enigma machine from WWII."
rotor_pos = (1, 1, 1)
pb = "pictures"
rotor_sel = (rotor2, rotor4, rotor8)
en = enigma(message, rotor_pos, rotor_sel, pb)
print("Encrypted message:", en)
print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))
| """
Wikipedia: https://en.wikipedia.org/wiki/Enigma_machine
Video explanation: https://youtu.be/QwQVMqfoB2E
Also check out Numberphile's and Computerphile's videos on this topic
This module contains function 'enigma' which emulates
the famous Enigma machine from WWII.
Module includes:
- enigma function
- showcase of function usage
- 9 randomly generated rotors
- reflector (aka static rotor)
- original alphabet
Created by TrapinchO
"""
from __future__ import annotations
RotorPositionT = tuple[int, int, int]
RotorSelectionT = tuple[str, str, str]
# used alphabet --------------------------
# from string.ascii_uppercase
abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# -------------------------- default selection --------------------------
# rotors --------------------------
rotor1 = "EGZWVONAHDCLFQMSIPJBYUKXTR"
rotor2 = "FOBHMDKEXQNRAULPGSJVTYICZW"
rotor3 = "ZJXESIUQLHAVRMDOYGTNFWPBKC"
# reflector --------------------------
reflector = {
"A": "N",
"N": "A",
"B": "O",
"O": "B",
"C": "P",
"P": "C",
"D": "Q",
"Q": "D",
"E": "R",
"R": "E",
"F": "S",
"S": "F",
"G": "T",
"T": "G",
"H": "U",
"U": "H",
"I": "V",
"V": "I",
"J": "W",
"W": "J",
"K": "X",
"X": "K",
"L": "Y",
"Y": "L",
"M": "Z",
"Z": "M",
}
# -------------------------- extra rotors --------------------------
rotor4 = "RMDJXFUWGISLHVTCQNKYPBEZOA"
rotor5 = "SGLCPQWZHKXAREONTFBVIYJUDM"
rotor6 = "HVSICLTYKQUBXDWAJZOMFGPREN"
rotor7 = "RZWQHFMVDBKICJLNTUXAGYPSOE"
rotor8 = "LFKIJODBEGAMQPXVUHYSTCZRWN"
rotor9 = "KOAEGVDHXPQZMLFTYWJNBRCIUS"
def _validator(
rotpos: RotorPositionT, rotsel: RotorSelectionT, pb: str
) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]:
"""
Checks if the values can be used for the 'enigma' function
>>> _validator((1,1,1), (rotor1, rotor2, rotor3), 'POLAND')
((1, 1, 1), ('EGZWVONAHDCLFQMSIPJBYUKXTR', 'FOBHMDKEXQNRAULPGSJVTYICZW', \
'ZJXESIUQLHAVRMDOYGTNFWPBKC'), \
{'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'})
:param rotpos: rotor_positon
:param rotsel: rotor_selection
:param pb: plugb -> validated and transformed
:return: (rotpos, rotsel, pb)
"""
# Checks if there are 3 unique rotors
unique_rotsel = len(set(rotsel))
if unique_rotsel < 3:
raise Exception(f"Please use 3 unique rotors (not {unique_rotsel})")
# Checks if rotor positions are valid
rotorpos1, rotorpos2, rotorpos3 = rotpos
if not 0 < rotorpos1 <= len(abc):
raise ValueError(
"First rotor position is not within range of 1..26 (" f"{rotorpos1}"
)
if not 0 < rotorpos2 <= len(abc):
raise ValueError(
"Second rotor position is not within range of 1..26 (" f"{rotorpos2})"
)
if not 0 < rotorpos3 <= len(abc):
raise ValueError(
"Third rotor position is not within range of 1..26 (" f"{rotorpos3})"
)
# Validates string and returns dict
pbdict = _plugboard(pb)
return rotpos, rotsel, pbdict
def _plugboard(pbstring: str) -> dict[str, str]:
"""
https://en.wikipedia.org/wiki/Enigma_machine#Plugboard
>>> _plugboard('PICTURES')
{'P': 'I', 'I': 'P', 'C': 'T', 'T': 'C', 'U': 'R', 'R': 'U', 'E': 'S', 'S': 'E'}
>>> _plugboard('POLAND')
{'P': 'O', 'O': 'P', 'L': 'A', 'A': 'L', 'N': 'D', 'D': 'N'}
In the code, 'pb' stands for 'plugboard'
Pairs can be separated by spaces
:param pbstring: string containing plugboard setting for the Enigma machine
:return: dictionary containing converted pairs
"""
# tests the input string if it
# a) is type string
# b) has even length (so pairs can be made)
if not isinstance(pbstring, str):
raise TypeError(f"Plugboard setting isn't type string ({type(pbstring)})")
elif len(pbstring) % 2 != 0:
raise Exception(f"Odd number of symbols ({len(pbstring)})")
elif pbstring == "":
return {}
pbstring.replace(" ", "")
# Checks if all characters are unique
tmppbl = set()
for i in pbstring:
if i not in abc:
raise Exception(f"'{i}' not in list of symbols")
elif i in tmppbl:
raise Exception(f"Duplicate symbol ({i})")
else:
tmppbl.add(i)
del tmppbl
# Created the dictionary
pb = {}
for j in range(0, len(pbstring) - 1, 2):
pb[pbstring[j]] = pbstring[j + 1]
pb[pbstring[j + 1]] = pbstring[j]
return pb
def enigma(
text: str,
rotor_position: RotorPositionT,
rotor_selection: RotorSelectionT = (rotor1, rotor2, rotor3),
plugb: str = "",
) -> str:
"""
The only difference with real-world enigma is that I allowed string input.
All characters are converted to uppercase. (non-letter symbol are ignored)
How it works:
(for every letter in the message)
- Input letter goes into the plugboard.
If it is connected to another one, switch it.
- Letter goes through 3 rotors.
Each rotor can be represented as 2 sets of symbol, where one is shuffled.
Each symbol from the first set has corresponding symbol in
the second set and vice versa.
example:
| ABCDEFGHIJKLMNOPQRSTUVWXYZ | e.g. F=D and D=F
| VKLEPDBGRNWTFCJOHQAMUZYIXS |
- Symbol then goes through reflector (static rotor).
There it is switched with paired symbol
The reflector can be represented as2 sets, each with half of the alphanet.
There are usually 10 pairs of letters.
Example:
| ABCDEFGHIJKLM | e.g. E is paired to X
| ZYXWVUTSRQPON | so when E goes in X goes out and vice versa
- Letter then goes through the rotors again
- If the letter is connected to plugboard, it is switched.
- Return the letter
>>> enigma('Hello World!', (1, 2, 1), plugb='pictures')
'KORYH JUHHI!'
>>> enigma('KORYH, juhhi!', (1, 2, 1), plugb='pictures')
'HELLO, WORLD!'
>>> enigma('hello world!', (1, 1, 1), plugb='pictures')
'FPNCZ QWOBU!'
>>> enigma('FPNCZ QWOBU', (1, 1, 1), plugb='pictures')
'HELLO WORLD'
:param text: input message
:param rotor_position: tuple with 3 values in range 1..26
:param rotor_selection: tuple with 3 rotors ()
:param plugb: string containing plugboard configuration (default '')
:return: en/decrypted string
"""
text = text.upper()
rotor_position, rotor_selection, plugboard = _validator(
rotor_position, rotor_selection, plugb.upper()
)
rotorpos1, rotorpos2, rotorpos3 = rotor_position
rotor1, rotor2, rotor3 = rotor_selection
rotorpos1 -= 1
rotorpos2 -= 1
rotorpos3 -= 1
result = []
# encryption/decryption process --------------------------
for symbol in text:
if symbol in abc:
# 1st plugboard --------------------------
if symbol in plugboard:
symbol = plugboard[symbol]
# rotor ra --------------------------
index = abc.index(symbol) + rotorpos1
symbol = rotor1[index % len(abc)]
# rotor rb --------------------------
index = abc.index(symbol) + rotorpos2
symbol = rotor2[index % len(abc)]
# rotor rc --------------------------
index = abc.index(symbol) + rotorpos3
symbol = rotor3[index % len(abc)]
# reflector --------------------------
# this is the reason you don't need another machine to decipher
symbol = reflector[symbol]
# 2nd rotors
symbol = abc[rotor3.index(symbol) - rotorpos3]
symbol = abc[rotor2.index(symbol) - rotorpos2]
symbol = abc[rotor1.index(symbol) - rotorpos1]
# 2nd plugboard
if symbol in plugboard:
symbol = plugboard[symbol]
# moves/resets rotor positions
rotorpos1 += 1
if rotorpos1 >= len(abc):
rotorpos1 = 0
rotorpos2 += 1
if rotorpos2 >= len(abc):
rotorpos2 = 0
rotorpos3 += 1
if rotorpos3 >= len(abc):
rotorpos3 = 0
# else:
# pass
# Error could be also raised
# raise ValueError(
# 'Invalid symbol('+repr(symbol)+')')
result.append(symbol)
return "".join(result)
if __name__ == "__main__":
message = "This is my Python script that emulates the Enigma machine from WWII."
rotor_pos = (1, 1, 1)
pb = "pictures"
rotor_sel = (rotor2, rotor4, rotor8)
en = enigma(message, rotor_pos, rotor_sel, pb)
print("Encrypted message:", en)
print("Decrypted message:", enigma(en, rotor_pos, rotor_sel, pb))
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import random
import sys
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def main() -> None:
message = input("Enter message: ")
key = "LFWOAYUISVKMNXPBDCRJTQEGHZ"
resp = input("Encrypt/Decrypt [e/d]: ")
checkValidKey(key)
if resp.lower().startswith("e"):
mode = "encrypt"
translated = encryptMessage(key, message)
elif resp.lower().startswith("d"):
mode = "decrypt"
translated = decryptMessage(key, message)
print(f"\n{mode.title()}ion: \n{translated}")
def checkValidKey(key: str) -> None:
keyList = list(key)
lettersList = list(LETTERS)
keyList.sort()
lettersList.sort()
if keyList != lettersList:
sys.exit("Error in the key or symbol set.")
def encryptMessage(key: str, message: str) -> str:
"""
>>> encryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji')
'Ilcrism Olcvs'
"""
return translateMessage(key, message, "encrypt")
def decryptMessage(key: str, message: str) -> str:
"""
>>> decryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs')
'Harshil Darji'
"""
return translateMessage(key, message, "decrypt")
def translateMessage(key: str, message: str, mode: str) -> str:
translated = ""
charsA = LETTERS
charsB = key
if mode == "decrypt":
charsA, charsB = charsB, charsA
for symbol in message:
if symbol.upper() in charsA:
symIndex = charsA.find(symbol.upper())
if symbol.isupper():
translated += charsB[symIndex].upper()
else:
translated += charsB[symIndex].lower()
else:
translated += symbol
return translated
def getRandomKey() -> str:
key = list(LETTERS)
random.shuffle(key)
return "".join(key)
if __name__ == "__main__":
main()
| import random
import sys
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def main() -> None:
message = input("Enter message: ")
key = "LFWOAYUISVKMNXPBDCRJTQEGHZ"
resp = input("Encrypt/Decrypt [e/d]: ")
checkValidKey(key)
if resp.lower().startswith("e"):
mode = "encrypt"
translated = encryptMessage(key, message)
elif resp.lower().startswith("d"):
mode = "decrypt"
translated = decryptMessage(key, message)
print(f"\n{mode.title()}ion: \n{translated}")
def checkValidKey(key: str) -> None:
keyList = list(key)
lettersList = list(LETTERS)
keyList.sort()
lettersList.sort()
if keyList != lettersList:
sys.exit("Error in the key or symbol set.")
def encryptMessage(key: str, message: str) -> str:
"""
>>> encryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji')
'Ilcrism Olcvs'
"""
return translateMessage(key, message, "encrypt")
def decryptMessage(key: str, message: str) -> str:
"""
>>> decryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs')
'Harshil Darji'
"""
return translateMessage(key, message, "decrypt")
def translateMessage(key: str, message: str, mode: str) -> str:
translated = ""
charsA = LETTERS
charsB = key
if mode == "decrypt":
charsA, charsB = charsB, charsA
for symbol in message:
if symbol.upper() in charsA:
symIndex = charsA.find(symbol.upper())
if symbol.isupper():
translated += charsB[symIndex].upper()
else:
translated += charsB[symIndex].lower()
else:
translated += symbol
return translated
def getRandomKey() -> str:
key = list(LETTERS)
random.shuffle(key)
return "".join(key)
if __name__ == "__main__":
main()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| 37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690
| 37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Primality Testing with the Rabin-Miller Algorithm
import random
def rabinMiller(num: int) -> bool:
s = num - 1
t = 0
while s % 2 == 0:
s = s // 2
t += 1
for trials in range(5):
a = random.randrange(2, num - 1)
v = pow(a, s, num)
if v != 1:
i = 0
while v != (num - 1):
if i == t - 1:
return False
else:
i = i + 1
v = (v**2) % num
return True
def is_prime_low_num(num: int) -> bool:
if num < 2:
return False
lowPrimes = [
2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
101,
103,
107,
109,
113,
127,
131,
137,
139,
149,
151,
157,
163,
167,
173,
179,
181,
191,
193,
197,
199,
211,
223,
227,
229,
233,
239,
241,
251,
257,
263,
269,
271,
277,
281,
283,
293,
307,
311,
313,
317,
331,
337,
347,
349,
353,
359,
367,
373,
379,
383,
389,
397,
401,
409,
419,
421,
431,
433,
439,
443,
449,
457,
461,
463,
467,
479,
487,
491,
499,
503,
509,
521,
523,
541,
547,
557,
563,
569,
571,
577,
587,
593,
599,
601,
607,
613,
617,
619,
631,
641,
643,
647,
653,
659,
661,
673,
677,
683,
691,
701,
709,
719,
727,
733,
739,
743,
751,
757,
761,
769,
773,
787,
797,
809,
811,
821,
823,
827,
829,
839,
853,
857,
859,
863,
877,
881,
883,
887,
907,
911,
919,
929,
937,
941,
947,
953,
967,
971,
977,
983,
991,
997,
]
if num in lowPrimes:
return True
for prime in lowPrimes:
if (num % prime) == 0:
return False
return rabinMiller(num)
def generateLargePrime(keysize: int = 1024) -> int:
while True:
num = random.randrange(2 ** (keysize - 1), 2 ** (keysize))
if is_prime_low_num(num):
return num
if __name__ == "__main__":
num = generateLargePrime()
print(("Prime number:", num))
print(("is_prime_low_num:", is_prime_low_num(num)))
| # Primality Testing with the Rabin-Miller Algorithm
import random
def rabinMiller(num: int) -> bool:
s = num - 1
t = 0
while s % 2 == 0:
s = s // 2
t += 1
for trials in range(5):
a = random.randrange(2, num - 1)
v = pow(a, s, num)
if v != 1:
i = 0
while v != (num - 1):
if i == t - 1:
return False
else:
i = i + 1
v = (v**2) % num
return True
def is_prime_low_num(num: int) -> bool:
if num < 2:
return False
lowPrimes = [
2,
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
101,
103,
107,
109,
113,
127,
131,
137,
139,
149,
151,
157,
163,
167,
173,
179,
181,
191,
193,
197,
199,
211,
223,
227,
229,
233,
239,
241,
251,
257,
263,
269,
271,
277,
281,
283,
293,
307,
311,
313,
317,
331,
337,
347,
349,
353,
359,
367,
373,
379,
383,
389,
397,
401,
409,
419,
421,
431,
433,
439,
443,
449,
457,
461,
463,
467,
479,
487,
491,
499,
503,
509,
521,
523,
541,
547,
557,
563,
569,
571,
577,
587,
593,
599,
601,
607,
613,
617,
619,
631,
641,
643,
647,
653,
659,
661,
673,
677,
683,
691,
701,
709,
719,
727,
733,
739,
743,
751,
757,
761,
769,
773,
787,
797,
809,
811,
821,
823,
827,
829,
839,
853,
857,
859,
863,
877,
881,
883,
887,
907,
911,
919,
929,
937,
941,
947,
953,
967,
971,
977,
983,
991,
997,
]
if num in lowPrimes:
return True
for prime in lowPrimes:
if (num % prime) == 0:
return False
return rabinMiller(num)
def generateLargePrime(keysize: int = 1024) -> int:
while True:
num = random.randrange(2 ** (keysize - 1), 2 ** (keysize))
if is_prime_low_num(num):
return num
if __name__ == "__main__":
num = generateLargePrime()
print(("Prime number:", num))
print(("is_prime_low_num:", is_prime_low_num(num)))
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Geometric Mean
Reference : https://en.wikipedia.org/wiki/Geometric_mean
Geometric series
Reference: https://en.wikipedia.org/wiki/Geometric_series
"""
def is_geometric_series(series: list) -> bool:
"""
checking whether the input series is geometric series or not
>>> is_geometric_series([2, 4, 8])
True
>>> is_geometric_series([3, 6, 12, 24])
True
>>> is_geometric_series([1, 2, 3])
False
>>> is_geometric_series([0, 0, 3])
False
>>> is_geometric_series([])
Traceback (most recent call last):
...
ValueError: Input list must be a non empty list
>>> is_geometric_series(4)
Traceback (most recent call last):
...
ValueError: Input series is not valid, valid series - [2, 4, 8]
"""
if not isinstance(series, list):
raise ValueError("Input series is not valid, valid series - [2, 4, 8]")
if len(series) == 0:
raise ValueError("Input list must be a non empty list")
if len(series) == 1:
return True
try:
common_ratio = series[1] / series[0]
for index in range(len(series) - 1):
if series[index + 1] / series[index] != common_ratio:
return False
except ZeroDivisionError:
return False
return True
def geometric_mean(series: list) -> float:
"""
return the geometric mean of series
>>> geometric_mean([2, 4, 8])
3.9999999999999996
>>> geometric_mean([3, 6, 12, 24])
8.48528137423857
>>> geometric_mean([4, 8, 16])
7.999999999999999
>>> geometric_mean(4)
Traceback (most recent call last):
...
ValueError: Input series is not valid, valid series - [2, 4, 8]
>>> geometric_mean([1, 2, 3])
1.8171205928321397
>>> geometric_mean([0, 2, 3])
0.0
>>> geometric_mean([])
Traceback (most recent call last):
...
ValueError: Input list must be a non empty list
"""
if not isinstance(series, list):
raise ValueError("Input series is not valid, valid series - [2, 4, 8]")
if len(series) == 0:
raise ValueError("Input list must be a non empty list")
answer = 1
for value in series:
answer *= value
return pow(answer, 1 / len(series))
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Geometric Mean
Reference : https://en.wikipedia.org/wiki/Geometric_mean
Geometric series
Reference: https://en.wikipedia.org/wiki/Geometric_series
"""
def is_geometric_series(series: list) -> bool:
"""
checking whether the input series is geometric series or not
>>> is_geometric_series([2, 4, 8])
True
>>> is_geometric_series([3, 6, 12, 24])
True
>>> is_geometric_series([1, 2, 3])
False
>>> is_geometric_series([0, 0, 3])
False
>>> is_geometric_series([])
Traceback (most recent call last):
...
ValueError: Input list must be a non empty list
>>> is_geometric_series(4)
Traceback (most recent call last):
...
ValueError: Input series is not valid, valid series - [2, 4, 8]
"""
if not isinstance(series, list):
raise ValueError("Input series is not valid, valid series - [2, 4, 8]")
if len(series) == 0:
raise ValueError("Input list must be a non empty list")
if len(series) == 1:
return True
try:
common_ratio = series[1] / series[0]
for index in range(len(series) - 1):
if series[index + 1] / series[index] != common_ratio:
return False
except ZeroDivisionError:
return False
return True
def geometric_mean(series: list) -> float:
"""
return the geometric mean of series
>>> geometric_mean([2, 4, 8])
3.9999999999999996
>>> geometric_mean([3, 6, 12, 24])
8.48528137423857
>>> geometric_mean([4, 8, 16])
7.999999999999999
>>> geometric_mean(4)
Traceback (most recent call last):
...
ValueError: Input series is not valid, valid series - [2, 4, 8]
>>> geometric_mean([1, 2, 3])
1.8171205928321397
>>> geometric_mean([0, 2, 3])
0.0
>>> geometric_mean([])
Traceback (most recent call last):
...
ValueError: Input list must be a non empty list
"""
if not isinstance(series, list):
raise ValueError("Input series is not valid, valid series - [2, 4, 8]")
if len(series) == 0:
raise ValueError("Input list must be a non empty list")
answer = 1
for value in series:
answer *= value
return pow(answer, 1 / len(series))
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Computer Vision
Computer vision is a field of computer science that works on enabling computers to see, identify and process images in the same way that human does, and provide appropriate output.
It is like imparting human intelligence and instincts to a computer.
Image processing and computer vision are a little different from each other. Image processing means applying some algorithms for transforming image from one form to the other like smoothing, contrasting, stretching, etc.
While computer vision comes from modelling image processing using the techniques of machine learning, computer vision applies machine learning to recognize patterns for interpretation of images (much like the process of visual reasoning of human vision).
* <https://en.wikipedia.org/wiki/Computer_vision>
* <https://www.algorithmia.com/blog/introduction-to-computer-vision>
| # Computer Vision
Computer vision is a field of computer science that works on enabling computers to see, identify and process images in the same way that human does, and provide appropriate output.
It is like imparting human intelligence and instincts to a computer.
Image processing and computer vision are a little different from each other. Image processing means applying some algorithms for transforming image from one form to the other like smoothing, contrasting, stretching, etc.
While computer vision comes from modelling image processing using the techniques of machine learning, computer vision applies machine learning to recognize patterns for interpretation of images (much like the process of visual reasoning of human vision).
* <https://en.wikipedia.org/wiki/Computer_vision>
* <https://www.algorithmia.com/blog/introduction-to-computer-vision>
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
This is a Python implementation of the levenshtein distance.
Levenshtein distance is a string metric for measuring the
difference between two sequences.
For doctests run following command:
python -m doctest -v levenshtein-distance.py
or
python3 -m doctest -v levenshtein-distance.py
For manual testing run:
python levenshtein-distance.py
"""
def levenshtein_distance(first_word: str, second_word: str) -> int:
"""Implementation of the levenshtein distance in Python.
:param first_word: the first word to measure the difference.
:param second_word: the second word to measure the difference.
:return: the levenshtein distance between the two words.
Examples:
>>> levenshtein_distance("planet", "planetary")
3
>>> levenshtein_distance("", "test")
4
>>> levenshtein_distance("book", "back")
2
>>> levenshtein_distance("book", "book")
0
>>> levenshtein_distance("test", "")
4
>>> levenshtein_distance("", "")
0
>>> levenshtein_distance("orchestration", "container")
10
"""
# The longer word should come first
if len(first_word) < len(second_word):
return levenshtein_distance(second_word, first_word)
if len(second_word) == 0:
return len(first_word)
previous_row = list(range(len(second_word) + 1))
for i, c1 in enumerate(first_word):
current_row = [i + 1]
for j, c2 in enumerate(second_word):
# Calculate insertions, deletions and substitutions
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] + (c1 != c2)
# Get the minimum to append to the current row
current_row.append(min(insertions, deletions, substitutions))
# Store the previous row
previous_row = current_row
# Returns the last element (distance)
return previous_row[-1]
if __name__ == "__main__":
first_word = input("Enter the first word:\n").strip()
second_word = input("Enter the second word:\n").strip()
result = levenshtein_distance(first_word, second_word)
print(f"Levenshtein distance between {first_word} and {second_word} is {result}")
| """
This is a Python implementation of the levenshtein distance.
Levenshtein distance is a string metric for measuring the
difference between two sequences.
For doctests run following command:
python -m doctest -v levenshtein-distance.py
or
python3 -m doctest -v levenshtein-distance.py
For manual testing run:
python levenshtein-distance.py
"""
def levenshtein_distance(first_word: str, second_word: str) -> int:
"""Implementation of the levenshtein distance in Python.
:param first_word: the first word to measure the difference.
:param second_word: the second word to measure the difference.
:return: the levenshtein distance between the two words.
Examples:
>>> levenshtein_distance("planet", "planetary")
3
>>> levenshtein_distance("", "test")
4
>>> levenshtein_distance("book", "back")
2
>>> levenshtein_distance("book", "book")
0
>>> levenshtein_distance("test", "")
4
>>> levenshtein_distance("", "")
0
>>> levenshtein_distance("orchestration", "container")
10
"""
# The longer word should come first
if len(first_word) < len(second_word):
return levenshtein_distance(second_word, first_word)
if len(second_word) == 0:
return len(first_word)
previous_row = list(range(len(second_word) + 1))
for i, c1 in enumerate(first_word):
current_row = [i + 1]
for j, c2 in enumerate(second_word):
# Calculate insertions, deletions and substitutions
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] + (c1 != c2)
# Get the minimum to append to the current row
current_row.append(min(insertions, deletions, substitutions))
# Store the previous row
previous_row = current_row
# Returns the last element (distance)
return previous_row[-1]
if __name__ == "__main__":
first_word = input("Enter the first word:\n").strip()
second_word = input("Enter the second word:\n").strip()
result = levenshtein_distance(first_word, second_word)
print(f"Levenshtein distance between {first_word} and {second_word} is {result}")
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Video Explanation: https://www.youtube.com/watch?v=6w60Zi1NtL8&feature=emb_logo
from __future__ import annotations
def maximum_non_adjacent_sum(nums: list[int]) -> int:
"""
Find the maximum non-adjacent sum of the integers in the nums input list
>>> print(maximum_non_adjacent_sum([1, 2, 3]))
4
>>> maximum_non_adjacent_sum([1, 5, 3, 7, 2, 2, 6])
18
>>> maximum_non_adjacent_sum([-1, -5, -3, -7, -2, -2, -6])
0
>>> maximum_non_adjacent_sum([499, 500, -3, -7, -2, -2, -6])
500
"""
if not nums:
return 0
max_including = nums[0]
max_excluding = 0
for num in nums[1:]:
max_including, max_excluding = (
max_excluding + num,
max(max_including, max_excluding),
)
return max(max_excluding, max_including)
if __name__ == "__main__":
import doctest
doctest.testmod()
| # Video Explanation: https://www.youtube.com/watch?v=6w60Zi1NtL8&feature=emb_logo
from __future__ import annotations
def maximum_non_adjacent_sum(nums: list[int]) -> int:
"""
Find the maximum non-adjacent sum of the integers in the nums input list
>>> print(maximum_non_adjacent_sum([1, 2, 3]))
4
>>> maximum_non_adjacent_sum([1, 5, 3, 7, 2, 2, 6])
18
>>> maximum_non_adjacent_sum([-1, -5, -3, -7, -2, -2, -6])
0
>>> maximum_non_adjacent_sum([499, 500, -3, -7, -2, -2, -6])
500
"""
if not nums:
return 0
max_including = nums[0]
max_excluding = 0
for num in nums[1:]:
max_including, max_excluding = (
max_excluding + num,
max(max_including, max_excluding),
)
return max(max_excluding, max_including)
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import cv2
import numpy as np
from digital_image_processing.filters.convolve import img_convolve
from digital_image_processing.filters.sobel_filter import sobel_filter
PI = 180
def gen_gaussian_kernel(k_size, sigma):
center = k_size // 2
x, y = np.mgrid[0 - center : k_size - center, 0 - center : k_size - center]
g = (
1
/ (2 * np.pi * sigma)
* np.exp(-(np.square(x) + np.square(y)) / (2 * np.square(sigma)))
)
return g
def canny(image, threshold_low=15, threshold_high=30, weak=128, strong=255):
image_row, image_col = image.shape[0], image.shape[1]
# gaussian_filter
gaussian_out = img_convolve(image, gen_gaussian_kernel(9, sigma=1.4))
# get the gradient and degree by sobel_filter
sobel_grad, sobel_theta = sobel_filter(gaussian_out)
gradient_direction = np.rad2deg(sobel_theta)
gradient_direction += PI
dst = np.zeros((image_row, image_col))
"""
Non-maximum suppression. If the edge strength of the current pixel is the largest
compared to the other pixels in the mask with the same direction, the value will be
preserved. Otherwise, the value will be suppressed.
"""
for row in range(1, image_row - 1):
for col in range(1, image_col - 1):
direction = gradient_direction[row, col]
if (
0 <= direction < 22.5
or 15 * PI / 8 <= direction <= 2 * PI
or 7 * PI / 8 <= direction <= 9 * PI / 8
):
W = sobel_grad[row, col - 1]
E = sobel_grad[row, col + 1]
if sobel_grad[row, col] >= W and sobel_grad[row, col] >= E:
dst[row, col] = sobel_grad[row, col]
elif (PI / 8 <= direction < 3 * PI / 8) or (
9 * PI / 8 <= direction < 11 * PI / 8
):
SW = sobel_grad[row + 1, col - 1]
NE = sobel_grad[row - 1, col + 1]
if sobel_grad[row, col] >= SW and sobel_grad[row, col] >= NE:
dst[row, col] = sobel_grad[row, col]
elif (3 * PI / 8 <= direction < 5 * PI / 8) or (
11 * PI / 8 <= direction < 13 * PI / 8
):
N = sobel_grad[row - 1, col]
S = sobel_grad[row + 1, col]
if sobel_grad[row, col] >= N and sobel_grad[row, col] >= S:
dst[row, col] = sobel_grad[row, col]
elif (5 * PI / 8 <= direction < 7 * PI / 8) or (
13 * PI / 8 <= direction < 15 * PI / 8
):
NW = sobel_grad[row - 1, col - 1]
SE = sobel_grad[row + 1, col + 1]
if sobel_grad[row, col] >= NW and sobel_grad[row, col] >= SE:
dst[row, col] = sobel_grad[row, col]
"""
High-Low threshold detection. If an edge pixel’s gradient value is higher
than the high threshold value, it is marked as a strong edge pixel. If an
edge pixel’s gradient value is smaller than the high threshold value and
larger than the low threshold value, it is marked as a weak edge pixel. If
an edge pixel's value is smaller than the low threshold value, it will be
suppressed.
"""
if dst[row, col] >= threshold_high:
dst[row, col] = strong
elif dst[row, col] <= threshold_low:
dst[row, col] = 0
else:
dst[row, col] = weak
"""
Edge tracking. Usually a weak edge pixel caused from true edges will be connected
to a strong edge pixel while noise responses are unconnected. As long as there is
one strong edge pixel that is involved in its 8-connected neighborhood, that weak
edge point can be identified as one that should be preserved.
"""
for row in range(1, image_row):
for col in range(1, image_col):
if dst[row, col] == weak:
if 255 in (
dst[row, col + 1],
dst[row, col - 1],
dst[row - 1, col],
dst[row + 1, col],
dst[row - 1, col - 1],
dst[row + 1, col - 1],
dst[row - 1, col + 1],
dst[row + 1, col + 1],
):
dst[row, col] = strong
else:
dst[row, col] = 0
return dst
if __name__ == "__main__":
# read original image in gray mode
lena = cv2.imread(r"../image_data/lena.jpg", 0)
# canny edge detection
canny_dst = canny(lena)
cv2.imshow("canny", canny_dst)
cv2.waitKey(0)
| import cv2
import numpy as np
from digital_image_processing.filters.convolve import img_convolve
from digital_image_processing.filters.sobel_filter import sobel_filter
PI = 180
def gen_gaussian_kernel(k_size, sigma):
center = k_size // 2
x, y = np.mgrid[0 - center : k_size - center, 0 - center : k_size - center]
g = (
1
/ (2 * np.pi * sigma)
* np.exp(-(np.square(x) + np.square(y)) / (2 * np.square(sigma)))
)
return g
def canny(image, threshold_low=15, threshold_high=30, weak=128, strong=255):
image_row, image_col = image.shape[0], image.shape[1]
# gaussian_filter
gaussian_out = img_convolve(image, gen_gaussian_kernel(9, sigma=1.4))
# get the gradient and degree by sobel_filter
sobel_grad, sobel_theta = sobel_filter(gaussian_out)
gradient_direction = np.rad2deg(sobel_theta)
gradient_direction += PI
dst = np.zeros((image_row, image_col))
"""
Non-maximum suppression. If the edge strength of the current pixel is the largest
compared to the other pixels in the mask with the same direction, the value will be
preserved. Otherwise, the value will be suppressed.
"""
for row in range(1, image_row - 1):
for col in range(1, image_col - 1):
direction = gradient_direction[row, col]
if (
0 <= direction < 22.5
or 15 * PI / 8 <= direction <= 2 * PI
or 7 * PI / 8 <= direction <= 9 * PI / 8
):
W = sobel_grad[row, col - 1]
E = sobel_grad[row, col + 1]
if sobel_grad[row, col] >= W and sobel_grad[row, col] >= E:
dst[row, col] = sobel_grad[row, col]
elif (PI / 8 <= direction < 3 * PI / 8) or (
9 * PI / 8 <= direction < 11 * PI / 8
):
SW = sobel_grad[row + 1, col - 1]
NE = sobel_grad[row - 1, col + 1]
if sobel_grad[row, col] >= SW and sobel_grad[row, col] >= NE:
dst[row, col] = sobel_grad[row, col]
elif (3 * PI / 8 <= direction < 5 * PI / 8) or (
11 * PI / 8 <= direction < 13 * PI / 8
):
N = sobel_grad[row - 1, col]
S = sobel_grad[row + 1, col]
if sobel_grad[row, col] >= N and sobel_grad[row, col] >= S:
dst[row, col] = sobel_grad[row, col]
elif (5 * PI / 8 <= direction < 7 * PI / 8) or (
13 * PI / 8 <= direction < 15 * PI / 8
):
NW = sobel_grad[row - 1, col - 1]
SE = sobel_grad[row + 1, col + 1]
if sobel_grad[row, col] >= NW and sobel_grad[row, col] >= SE:
dst[row, col] = sobel_grad[row, col]
"""
High-Low threshold detection. If an edge pixel’s gradient value is higher
than the high threshold value, it is marked as a strong edge pixel. If an
edge pixel’s gradient value is smaller than the high threshold value and
larger than the low threshold value, it is marked as a weak edge pixel. If
an edge pixel's value is smaller than the low threshold value, it will be
suppressed.
"""
if dst[row, col] >= threshold_high:
dst[row, col] = strong
elif dst[row, col] <= threshold_low:
dst[row, col] = 0
else:
dst[row, col] = weak
"""
Edge tracking. Usually a weak edge pixel caused from true edges will be connected
to a strong edge pixel while noise responses are unconnected. As long as there is
one strong edge pixel that is involved in its 8-connected neighborhood, that weak
edge point can be identified as one that should be preserved.
"""
for row in range(1, image_row):
for col in range(1, image_col):
if dst[row, col] == weak:
if 255 in (
dst[row, col + 1],
dst[row, col - 1],
dst[row - 1, col],
dst[row + 1, col],
dst[row - 1, col - 1],
dst[row + 1, col - 1],
dst[row - 1, col + 1],
dst[row + 1, col + 1],
):
dst[row, col] = strong
else:
dst[row, col] = 0
return dst
if __name__ == "__main__":
# read original image in gray mode
lena = cv2.imread(r"../image_data/lena.jpg", 0)
# canny edge detection
canny_dst = canny(lena)
cv2.imshow("canny", canny_dst)
cv2.waitKey(0)
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import numpy as np
def power_iteration(
input_matrix: np.ndarray,
vector: np.ndarray,
error_tol: float = 1e-12,
max_iterations: int = 100,
) -> tuple[float, np.ndarray]:
"""
Power Iteration.
Find the largest eigenvalue and corresponding eigenvector
of matrix input_matrix given a random vector in the same space.
Will work so long as vector has component of largest eigenvector.
input_matrix must be either real or Hermitian.
Input
input_matrix: input matrix whose largest eigenvalue we will find.
Numpy array. np.shape(input_matrix) == (N,N).
vector: random initial vector in same space as matrix.
Numpy array. np.shape(vector) == (N,) or (N,1)
Output
largest_eigenvalue: largest eigenvalue of the matrix input_matrix.
Float. Scalar.
largest_eigenvector: eigenvector corresponding to largest_eigenvalue.
Numpy array. np.shape(largest_eigenvector) == (N,) or (N,1).
>>> import numpy as np
>>> input_matrix = np.array([
... [41, 4, 20],
... [ 4, 26, 30],
... [20, 30, 50]
... ])
>>> vector = np.array([41,4,20])
>>> power_iteration(input_matrix,vector)
(79.66086378788381, array([0.44472726, 0.46209842, 0.76725662]))
"""
# Ensure matrix is square.
assert np.shape(input_matrix)[0] == np.shape(input_matrix)[1]
# Ensure proper dimensionality.
assert np.shape(input_matrix)[0] == np.shape(vector)[0]
# Ensure inputs are either both complex or both real
assert np.iscomplexobj(input_matrix) == np.iscomplexobj(vector)
is_complex = np.iscomplexobj(input_matrix)
if is_complex:
# Ensure complex input_matrix is Hermitian
assert np.array_equal(input_matrix, input_matrix.conj().T)
# Set convergence to False. Will define convergence when we exceed max_iterations
# or when we have small changes from one iteration to next.
convergence = False
lamda_previous = 0
iterations = 0
error = 1e12
while not convergence:
# Multiple matrix by the vector.
w = np.dot(input_matrix, vector)
# Normalize the resulting output vector.
vector = w / np.linalg.norm(w)
# Find rayleigh quotient
# (faster than usual b/c we know vector is normalized already)
vectorH = vector.conj().T if is_complex else vector.T
lamda = np.dot(vectorH, np.dot(input_matrix, vector))
# Check convergence.
error = np.abs(lamda - lamda_previous) / lamda
iterations += 1
if error <= error_tol or iterations >= max_iterations:
convergence = True
lamda_previous = lamda
if is_complex:
lamda = np.real(lamda)
return lamda, vector
def test_power_iteration() -> None:
"""
>>> test_power_iteration() # self running tests
"""
real_input_matrix = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]])
real_vector = np.array([41, 4, 20])
complex_input_matrix = real_input_matrix.astype(np.complex128)
imag_matrix = np.triu(1j * complex_input_matrix, 1)
complex_input_matrix += imag_matrix
complex_input_matrix += -1 * imag_matrix.T
complex_vector = np.array([41, 4, 20]).astype(np.complex128)
for problem_type in ["real", "complex"]:
if problem_type == "real":
input_matrix = real_input_matrix
vector = real_vector
elif problem_type == "complex":
input_matrix = complex_input_matrix
vector = complex_vector
# Our implementation.
eigen_value, eigen_vector = power_iteration(input_matrix, vector)
# Numpy implementation.
# Get eigenvalues and eigenvectors using built-in numpy
# eigh (eigh used for symmetric or hermetian matrices).
eigen_values, eigen_vectors = np.linalg.eigh(input_matrix)
# Last eigenvalue is the maximum one.
eigen_value_max = eigen_values[-1]
# Last column in this matrix is eigenvector corresponding to largest eigenvalue.
eigen_vector_max = eigen_vectors[:, -1]
# Check our implementation and numpy gives close answers.
assert np.abs(eigen_value - eigen_value_max) <= 1e-6
# Take absolute values element wise of each eigenvector.
# as they are only unique to a minus sign.
assert np.linalg.norm(np.abs(eigen_vector) - np.abs(eigen_vector_max)) <= 1e-6
if __name__ == "__main__":
import doctest
doctest.testmod()
test_power_iteration()
| import numpy as np
def power_iteration(
input_matrix: np.ndarray,
vector: np.ndarray,
error_tol: float = 1e-12,
max_iterations: int = 100,
) -> tuple[float, np.ndarray]:
"""
Power Iteration.
Find the largest eigenvalue and corresponding eigenvector
of matrix input_matrix given a random vector in the same space.
Will work so long as vector has component of largest eigenvector.
input_matrix must be either real or Hermitian.
Input
input_matrix: input matrix whose largest eigenvalue we will find.
Numpy array. np.shape(input_matrix) == (N,N).
vector: random initial vector in same space as matrix.
Numpy array. np.shape(vector) == (N,) or (N,1)
Output
largest_eigenvalue: largest eigenvalue of the matrix input_matrix.
Float. Scalar.
largest_eigenvector: eigenvector corresponding to largest_eigenvalue.
Numpy array. np.shape(largest_eigenvector) == (N,) or (N,1).
>>> import numpy as np
>>> input_matrix = np.array([
... [41, 4, 20],
... [ 4, 26, 30],
... [20, 30, 50]
... ])
>>> vector = np.array([41,4,20])
>>> power_iteration(input_matrix,vector)
(79.66086378788381, array([0.44472726, 0.46209842, 0.76725662]))
"""
# Ensure matrix is square.
assert np.shape(input_matrix)[0] == np.shape(input_matrix)[1]
# Ensure proper dimensionality.
assert np.shape(input_matrix)[0] == np.shape(vector)[0]
# Ensure inputs are either both complex or both real
assert np.iscomplexobj(input_matrix) == np.iscomplexobj(vector)
is_complex = np.iscomplexobj(input_matrix)
if is_complex:
# Ensure complex input_matrix is Hermitian
assert np.array_equal(input_matrix, input_matrix.conj().T)
# Set convergence to False. Will define convergence when we exceed max_iterations
# or when we have small changes from one iteration to next.
convergence = False
lamda_previous = 0
iterations = 0
error = 1e12
while not convergence:
# Multiple matrix by the vector.
w = np.dot(input_matrix, vector)
# Normalize the resulting output vector.
vector = w / np.linalg.norm(w)
# Find rayleigh quotient
# (faster than usual b/c we know vector is normalized already)
vectorH = vector.conj().T if is_complex else vector.T
lamda = np.dot(vectorH, np.dot(input_matrix, vector))
# Check convergence.
error = np.abs(lamda - lamda_previous) / lamda
iterations += 1
if error <= error_tol or iterations >= max_iterations:
convergence = True
lamda_previous = lamda
if is_complex:
lamda = np.real(lamda)
return lamda, vector
def test_power_iteration() -> None:
"""
>>> test_power_iteration() # self running tests
"""
real_input_matrix = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]])
real_vector = np.array([41, 4, 20])
complex_input_matrix = real_input_matrix.astype(np.complex128)
imag_matrix = np.triu(1j * complex_input_matrix, 1)
complex_input_matrix += imag_matrix
complex_input_matrix += -1 * imag_matrix.T
complex_vector = np.array([41, 4, 20]).astype(np.complex128)
for problem_type in ["real", "complex"]:
if problem_type == "real":
input_matrix = real_input_matrix
vector = real_vector
elif problem_type == "complex":
input_matrix = complex_input_matrix
vector = complex_vector
# Our implementation.
eigen_value, eigen_vector = power_iteration(input_matrix, vector)
# Numpy implementation.
# Get eigenvalues and eigenvectors using built-in numpy
# eigh (eigh used for symmetric or hermetian matrices).
eigen_values, eigen_vectors = np.linalg.eigh(input_matrix)
# Last eigenvalue is the maximum one.
eigen_value_max = eigen_values[-1]
# Last column in this matrix is eigenvector corresponding to largest eigenvalue.
eigen_vector_max = eigen_vectors[:, -1]
# Check our implementation and numpy gives close answers.
assert np.abs(eigen_value - eigen_value_max) <= 1e-6
# Take absolute values element wise of each eigenvector.
# as they are only unique to a minus sign.
assert np.linalg.norm(np.abs(eigen_vector) - np.abs(eigen_vector_max)) <= 1e-6
if __name__ == "__main__":
import doctest
doctest.testmod()
test_power_iteration()
| -1 |
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,230 | MAINT: Updated f-string method |
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| cyai | "2022-07-05T17:02:31Z" | "2022-07-07T14:34:08Z" | 0a0f4986e4fde05ebc2a24c9cc2cd6b8200b8df1 | 2d5dd6f132a25165473471bf83765ec50c9f14d6 | MAINT: Updated f-string method.
### Describe your change:
Updated the code with f-string methods wherever required for a better and cleaner understanding of the code.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [x] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [x] All new Python files are placed inside an existing directory.
* [x] All filenames are in all lowercase characters with no spaces or dashes.
* [x] All functions and variable names follow Python naming conventions.
* [x] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [x] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [x] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [x] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
|
## Arithmetic Analysis
* [Bisection](arithmetic_analysis/bisection.py)
* [Gaussian Elimination](arithmetic_analysis/gaussian_elimination.py)
* [In Static Equilibrium](arithmetic_analysis/in_static_equilibrium.py)
* [Intersection](arithmetic_analysis/intersection.py)
* [Jacobi Iteration Method](arithmetic_analysis/jacobi_iteration_method.py)
* [Lu Decomposition](arithmetic_analysis/lu_decomposition.py)
* [Newton Forward Interpolation](arithmetic_analysis/newton_forward_interpolation.py)
* [Newton Method](arithmetic_analysis/newton_method.py)
* [Newton Raphson](arithmetic_analysis/newton_raphson.py)
* [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)
* [Hamiltonian Cycle](backtracking/hamiltonian_cycle.py)
* [Knight Tour](backtracking/knight_tour.py)
* [Minimax](backtracking/minimax.py)
* [N Queens](backtracking/n_queens.py)
* [N Queens Math](backtracking/n_queens_math.py)
* [Rat In Maze](backtracking/rat_in_maze.py)
* [Sudoku](backtracking/sudoku.py)
* [Sum Of Subsets](backtracking/sum_of_subsets.py)
## Bit Manipulation
* [Binary And Operator](bit_manipulation/binary_and_operator.py)
* [Binary Count Setbits](bit_manipulation/binary_count_setbits.py)
* [Binary Count Trailing Zeros](bit_manipulation/binary_count_trailing_zeros.py)
* [Binary Or Operator](bit_manipulation/binary_or_operator.py)
* [Binary Shifts](bit_manipulation/binary_shifts.py)
* [Binary Twos Complement](bit_manipulation/binary_twos_complement.py)
* [Binary Xor Operator](bit_manipulation/binary_xor_operator.py)
* [Count 1S Brian Kernighan Method](bit_manipulation/count_1s_brian_kernighan_method.py)
* [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py)
* [Gray Code Sequence](bit_manipulation/gray_code_sequence.py)
* [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
* [Quine Mc Cluskey](boolean_algebra/quine_mc_cluskey.py)
## Cellular Automata
* [Conways Game Of Life](cellular_automata/conways_game_of_life.py)
* [Game Of Life](cellular_automata/game_of_life.py)
* [Nagel Schrekenberg](cellular_automata/nagel_schrekenberg.py)
* [One Dimensional](cellular_automata/one_dimensional.py)
## Ciphers
* [A1Z26](ciphers/a1z26.py)
* [Affine Cipher](ciphers/affine_cipher.py)
* [Atbash](ciphers/atbash.py)
* [Baconian Cipher](ciphers/baconian_cipher.py)
* [Base16](ciphers/base16.py)
* [Base32](ciphers/base32.py)
* [Base64](ciphers/base64.py)
* [Base85](ciphers/base85.py)
* [Beaufort Cipher](ciphers/beaufort_cipher.py)
* [Bifid](ciphers/bifid.py)
* [Brute Force Caesar Cipher](ciphers/brute_force_caesar_cipher.py)
* [Caesar Cipher](ciphers/caesar_cipher.py)
* [Cryptomath Module](ciphers/cryptomath_module.py)
* [Decrypt Caesar With Chi Squared](ciphers/decrypt_caesar_with_chi_squared.py)
* [Deterministic Miller Rabin](ciphers/deterministic_miller_rabin.py)
* [Diffie](ciphers/diffie.py)
* [Diffie Hellman](ciphers/diffie_hellman.py)
* [Elgamal Key Generator](ciphers/elgamal_key_generator.py)
* [Enigma Machine2](ciphers/enigma_machine2.py)
* [Hill Cipher](ciphers/hill_cipher.py)
* [Mixed Keyword Cypher](ciphers/mixed_keyword_cypher.py)
* [Mono Alphabetic Ciphers](ciphers/mono_alphabetic_ciphers.py)
* [Morse Code](ciphers/morse_code.py)
* [Onepad Cipher](ciphers/onepad_cipher.py)
* [Playfair Cipher](ciphers/playfair_cipher.py)
* [Polybius](ciphers/polybius.py)
* [Porta Cipher](ciphers/porta_cipher.py)
* [Rabin Miller](ciphers/rabin_miller.py)
* [Rail Fence Cipher](ciphers/rail_fence_cipher.py)
* [Rot13](ciphers/rot13.py)
* [Rsa Cipher](ciphers/rsa_cipher.py)
* [Rsa Factorization](ciphers/rsa_factorization.py)
* [Rsa Key Generator](ciphers/rsa_key_generator.py)
* [Shuffled Shift Cipher](ciphers/shuffled_shift_cipher.py)
* [Simple Keyword Cypher](ciphers/simple_keyword_cypher.py)
* [Simple Substitution Cipher](ciphers/simple_substitution_cipher.py)
* [Trafid Cipher](ciphers/trafid_cipher.py)
* [Transposition Cipher](ciphers/transposition_cipher.py)
* [Transposition Cipher Encrypt Decrypt File](ciphers/transposition_cipher_encrypt_decrypt_file.py)
* [Vigenere Cipher](ciphers/vigenere_cipher.py)
* [Xor Cipher](ciphers/xor_cipher.py)
## Compression
* [Burrows Wheeler](compression/burrows_wheeler.py)
* [Huffman](compression/huffman.py)
* [Lempel Ziv](compression/lempel_ziv.py)
* [Lempel Ziv Decompress](compression/lempel_ziv_decompress.py)
* [Peak Signal To Noise Ratio](compression/peak_signal_to_noise_ratio.py)
## 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
* [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)
* [Temperature Conversions](conversions/temperature_conversions.py)
* [Volume Conversions](conversions/volume_conversions.py)
* [Weight Conversion](conversions/weight_conversion.py)
## Data Structures
* Binary Tree
* [Avl Tree](data_structures/binary_tree/avl_tree.py)
* [Basic Binary Tree](data_structures/binary_tree/basic_binary_tree.py)
* [Binary Search Tree](data_structures/binary_tree/binary_search_tree.py)
* [Binary Search Tree Recursive](data_structures/binary_tree/binary_search_tree_recursive.py)
* [Binary Tree Mirror](data_structures/binary_tree/binary_tree_mirror.py)
* [Binary Tree Traversals](data_structures/binary_tree/binary_tree_traversals.py)
* [Fenwick Tree](data_structures/binary_tree/fenwick_tree.py)
* [Lazy Segment Tree](data_structures/binary_tree/lazy_segment_tree.py)
* [Lowest Common Ancestor](data_structures/binary_tree/lowest_common_ancestor.py)
* [Merge Two Binary Trees](data_structures/binary_tree/merge_two_binary_trees.py)
* [Non Recursive Segment Tree](data_structures/binary_tree/non_recursive_segment_tree.py)
* [Number Of Possible Binary Trees](data_structures/binary_tree/number_of_possible_binary_trees.py)
* [Red Black Tree](data_structures/binary_tree/red_black_tree.py)
* [Segment Tree](data_structures/binary_tree/segment_tree.py)
* [Segment Tree Other](data_structures/binary_tree/segment_tree_other.py)
* [Treap](data_structures/binary_tree/treap.py)
* [Wavelet Tree](data_structures/binary_tree/wavelet_tree.py)
* Disjoint Set
* [Alternate Disjoint Set](data_structures/disjoint_set/alternate_disjoint_set.py)
* [Disjoint Set](data_structures/disjoint_set/disjoint_set.py)
* Hashing
* [Double Hash](data_structures/hashing/double_hash.py)
* [Hash Table](data_structures/hashing/hash_table.py)
* [Hash Table With Linked List](data_structures/hashing/hash_table_with_linked_list.py)
* Number Theory
* [Prime Numbers](data_structures/hashing/number_theory/prime_numbers.py)
* [Quadratic Probing](data_structures/hashing/quadratic_probing.py)
* Heap
* [Binomial Heap](data_structures/heap/binomial_heap.py)
* [Heap](data_structures/heap/heap.py)
* [Heap Generic](data_structures/heap/heap_generic.py)
* [Max Heap](data_structures/heap/max_heap.py)
* [Min Heap](data_structures/heap/min_heap.py)
* [Randomized Heap](data_structures/heap/randomized_heap.py)
* [Skew Heap](data_structures/heap/skew_heap.py)
* Linked List
* [Circular Linked List](data_structures/linked_list/circular_linked_list.py)
* [Deque Doubly](data_structures/linked_list/deque_doubly.py)
* [Doubly Linked List](data_structures/linked_list/doubly_linked_list.py)
* [Doubly Linked List Two](data_structures/linked_list/doubly_linked_list_two.py)
* [From Sequence](data_structures/linked_list/from_sequence.py)
* [Has Loop](data_structures/linked_list/has_loop.py)
* [Is Palindrome](data_structures/linked_list/is_palindrome.py)
* [Merge Two Lists](data_structures/linked_list/merge_two_lists.py)
* [Middle Element Of Linked List](data_structures/linked_list/middle_element_of_linked_list.py)
* [Print Reverse](data_structures/linked_list/print_reverse.py)
* [Singly Linked List](data_structures/linked_list/singly_linked_list.py)
* [Skip List](data_structures/linked_list/skip_list.py)
* [Swap Nodes](data_structures/linked_list/swap_nodes.py)
* Queue
* [Circular Queue](data_structures/queue/circular_queue.py)
* [Circular Queue Linked List](data_structures/queue/circular_queue_linked_list.py)
* [Double Ended Queue](data_structures/queue/double_ended_queue.py)
* [Linked Queue](data_structures/queue/linked_queue.py)
* [Priority Queue Using List](data_structures/queue/priority_queue_using_list.py)
* [Queue On List](data_structures/queue/queue_on_list.py)
* [Queue On Pseudo Stack](data_structures/queue/queue_on_pseudo_stack.py)
* Stacks
* [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py)
* [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py)
* [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py)
* [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py)
* [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py)
* [Next Greater Element](data_structures/stacks/next_greater_element.py)
* [Postfix Evaluation](data_structures/stacks/postfix_evaluation.py)
* [Prefix Evaluation](data_structures/stacks/prefix_evaluation.py)
* [Stack](data_structures/stacks/stack.py)
* [Stack With Doubly Linked List](data_structures/stacks/stack_with_doubly_linked_list.py)
* [Stack With Singly Linked List](data_structures/stacks/stack_with_singly_linked_list.py)
* [Stock Span Problem](data_structures/stacks/stock_span_problem.py)
* Trie
* [Trie](data_structures/trie/trie.py)
## Digital Image Processing
* [Change Brightness](digital_image_processing/change_brightness.py)
* [Change Contrast](digital_image_processing/change_contrast.py)
* [Convert To Negative](digital_image_processing/convert_to_negative.py)
* Dithering
* [Burkes](digital_image_processing/dithering/burkes.py)
* Edge Detection
* [Canny](digital_image_processing/edge_detection/canny.py)
* Filters
* [Bilateral Filter](digital_image_processing/filters/bilateral_filter.py)
* [Convolve](digital_image_processing/filters/convolve.py)
* [Gabor Filter](digital_image_processing/filters/gabor_filter.py)
* [Gaussian Filter](digital_image_processing/filters/gaussian_filter.py)
* [Median Filter](digital_image_processing/filters/median_filter.py)
* [Sobel Filter](digital_image_processing/filters/sobel_filter.py)
* Histogram Equalization
* [Histogram Stretch](digital_image_processing/histogram_equalization/histogram_stretch.py)
* [Index Calculation](digital_image_processing/index_calculation.py)
* Morphological Operations
* [Dilation Operation](digital_image_processing/morphological_operations/dilation_operation.py)
* [Erosion Operation](digital_image_processing/morphological_operations/erosion_operation.py)
* Resize
* [Resize](digital_image_processing/resize/resize.py)
* Rotation
* [Rotation](digital_image_processing/rotation/rotation.py)
* [Sepia](digital_image_processing/sepia.py)
* [Test Digital Image Processing](digital_image_processing/test_digital_image_processing.py)
## Divide And Conquer
* [Closest Pair Of Points](divide_and_conquer/closest_pair_of_points.py)
* [Convex Hull](divide_and_conquer/convex_hull.py)
* [Heaps Algorithm](divide_and_conquer/heaps_algorithm.py)
* [Heaps Algorithm Iterative](divide_and_conquer/heaps_algorithm_iterative.py)
* [Inversions](divide_and_conquer/inversions.py)
* [Kth Order Statistic](divide_and_conquer/kth_order_statistic.py)
* [Max Difference Pair](divide_and_conquer/max_difference_pair.py)
* [Max Subarray Sum](divide_and_conquer/max_subarray_sum.py)
* [Mergesort](divide_and_conquer/mergesort.py)
* [Peak](divide_and_conquer/peak.py)
* [Power](divide_and_conquer/power.py)
* [Strassen Matrix Multiplication](divide_and_conquer/strassen_matrix_multiplication.py)
## Dynamic Programming
* [Abbreviation](dynamic_programming/abbreviation.py)
* [All Construct](dynamic_programming/all_construct.py)
* [Bitmask](dynamic_programming/bitmask.py)
* [Catalan Numbers](dynamic_programming/catalan_numbers.py)
* [Climbing Stairs](dynamic_programming/climbing_stairs.py)
* [Edit Distance](dynamic_programming/edit_distance.py)
* [Factorial](dynamic_programming/factorial.py)
* [Fast Fibonacci](dynamic_programming/fast_fibonacci.py)
* [Fibonacci](dynamic_programming/fibonacci.py)
* [Floyd Warshall](dynamic_programming/floyd_warshall.py)
* [Fractional Knapsack](dynamic_programming/fractional_knapsack.py)
* [Fractional Knapsack 2](dynamic_programming/fractional_knapsack_2.py)
* [Integer Partition](dynamic_programming/integer_partition.py)
* [Iterating Through Submasks](dynamic_programming/iterating_through_submasks.py)
* [Knapsack](dynamic_programming/knapsack.py)
* [Longest Common Subsequence](dynamic_programming/longest_common_subsequence.py)
* [Longest Increasing Subsequence](dynamic_programming/longest_increasing_subsequence.py)
* [Longest Increasing Subsequence O(Nlogn)](dynamic_programming/longest_increasing_subsequence_o(nlogn).py)
* [Longest Sub Array](dynamic_programming/longest_sub_array.py)
* [Matrix Chain Order](dynamic_programming/matrix_chain_order.py)
* [Max Non Adjacent Sum](dynamic_programming/max_non_adjacent_sum.py)
* [Max Sub Array](dynamic_programming/max_sub_array.py)
* [Max Sum Contiguous Subsequence](dynamic_programming/max_sum_contiguous_subsequence.py)
* [Minimum Coin Change](dynamic_programming/minimum_coin_change.py)
* [Minimum Cost Path](dynamic_programming/minimum_cost_path.py)
* [Minimum Partition](dynamic_programming/minimum_partition.py)
* [Minimum Steps To One](dynamic_programming/minimum_steps_to_one.py)
* [Optimal Binary Search Tree](dynamic_programming/optimal_binary_search_tree.py)
* [Rod Cutting](dynamic_programming/rod_cutting.py)
* [Subset Generation](dynamic_programming/subset_generation.py)
* [Sum Of Subset](dynamic_programming/sum_of_subset.py)
## Electronics
* [Carrier Concentration](electronics/carrier_concentration.py)
* [Coulombs Law](electronics/coulombs_law.py)
* [Electric Power](electronics/electric_power.py)
* [Ohms Law](electronics/ohms_law.py)
## File Transfer
* [Receive File](file_transfer/receive_file.py)
* [Send File](file_transfer/send_file.py)
* Tests
* [Test Send File](file_transfer/tests/test_send_file.py)
## Financial
* [Equated Monthly Installments](financial/equated_monthly_installments.py)
* [Interest](financial/interest.py)
## Fractals
* [Julia Sets](fractals/julia_sets.py)
* [Koch Snowflake](fractals/koch_snowflake.py)
* [Mandelbrot](fractals/mandelbrot.py)
* [Sierpinski Triangle](fractals/sierpinski_triangle.py)
## Fuzzy Logic
* [Fuzzy Operations](fuzzy_logic/fuzzy_operations.py)
## Genetic Algorithm
* [Basic String](genetic_algorithm/basic_string.py)
## Geodesy
* [Haversine Distance](geodesy/haversine_distance.py)
* [Lamberts Ellipsoidal Distance](geodesy/lamberts_ellipsoidal_distance.py)
## Graphics
* [Bezier Curve](graphics/bezier_curve.py)
* [Vector3 For 2D Rendering](graphics/vector3_for_2d_rendering.py)
## Graphs
* [A Star](graphs/a_star.py)
* [Articulation Points](graphs/articulation_points.py)
* [Basic Graphs](graphs/basic_graphs.py)
* [Bellman Ford](graphs/bellman_ford.py)
* [Bfs Shortest Path](graphs/bfs_shortest_path.py)
* [Bfs Zero One Shortest Path](graphs/bfs_zero_one_shortest_path.py)
* [Bidirectional A Star](graphs/bidirectional_a_star.py)
* [Bidirectional Breadth First Search](graphs/bidirectional_breadth_first_search.py)
* [Boruvka](graphs/boruvka.py)
* [Breadth First Search](graphs/breadth_first_search.py)
* [Breadth First Search 2](graphs/breadth_first_search_2.py)
* [Breadth First Search Shortest Path](graphs/breadth_first_search_shortest_path.py)
* [Check Bipartite Graph Bfs](graphs/check_bipartite_graph_bfs.py)
* [Check Bipartite Graph Dfs](graphs/check_bipartite_graph_dfs.py)
* [Check Cycle](graphs/check_cycle.py)
* [Connected Components](graphs/connected_components.py)
* [Depth First Search](graphs/depth_first_search.py)
* [Depth First Search 2](graphs/depth_first_search_2.py)
* [Dijkstra](graphs/dijkstra.py)
* [Dijkstra 2](graphs/dijkstra_2.py)
* [Dijkstra Algorithm](graphs/dijkstra_algorithm.py)
* [Dinic](graphs/dinic.py)
* [Directed And Undirected (Weighted) Graph](graphs/directed_and_undirected_(weighted)_graph.py)
* [Edmonds Karp Multiple Source And Sink](graphs/edmonds_karp_multiple_source_and_sink.py)
* [Eulerian Path And Circuit For Undirected Graph](graphs/eulerian_path_and_circuit_for_undirected_graph.py)
* [Even Tree](graphs/even_tree.py)
* [Finding Bridges](graphs/finding_bridges.py)
* [Frequent Pattern Graph Miner](graphs/frequent_pattern_graph_miner.py)
* [G Topological Sort](graphs/g_topological_sort.py)
* [Gale Shapley Bigraph](graphs/gale_shapley_bigraph.py)
* [Graph List](graphs/graph_list.py)
* [Graph Matrix](graphs/graph_matrix.py)
* [Graphs Floyd Warshall](graphs/graphs_floyd_warshall.py)
* [Greedy Best First](graphs/greedy_best_first.py)
* [Greedy Min Vertex Cover](graphs/greedy_min_vertex_cover.py)
* [Kahns Algorithm Long](graphs/kahns_algorithm_long.py)
* [Kahns Algorithm Topo](graphs/kahns_algorithm_topo.py)
* [Karger](graphs/karger.py)
* [Markov Chain](graphs/markov_chain.py)
* [Matching Min Vertex Cover](graphs/matching_min_vertex_cover.py)
* [Minimum Path Sum](graphs/minimum_path_sum.py)
* [Minimum Spanning Tree Boruvka](graphs/minimum_spanning_tree_boruvka.py)
* [Minimum Spanning Tree Kruskal](graphs/minimum_spanning_tree_kruskal.py)
* [Minimum Spanning Tree Kruskal2](graphs/minimum_spanning_tree_kruskal2.py)
* [Minimum Spanning Tree Prims](graphs/minimum_spanning_tree_prims.py)
* [Minimum Spanning Tree Prims2](graphs/minimum_spanning_tree_prims2.py)
* [Multi Heuristic Astar](graphs/multi_heuristic_astar.py)
* [Page Rank](graphs/page_rank.py)
* [Prim](graphs/prim.py)
* [Random Graph Generator](graphs/random_graph_generator.py)
* [Scc Kosaraju](graphs/scc_kosaraju.py)
* [Strongly Connected Components](graphs/strongly_connected_components.py)
* [Tarjans Scc](graphs/tarjans_scc.py)
* Tests
* [Test Min Spanning Tree Kruskal](graphs/tests/test_min_spanning_tree_kruskal.py)
* [Test Min Spanning Tree Prim](graphs/tests/test_min_spanning_tree_prim.py)
## Greedy Methods
* [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py)
## Hashes
* [Adler32](hashes/adler32.py)
* [Chaos Machine](hashes/chaos_machine.py)
* [Djb2](hashes/djb2.py)
* [Enigma Machine](hashes/enigma_machine.py)
* [Hamming Code](hashes/hamming_code.py)
* [Luhn](hashes/luhn.py)
* [Md5](hashes/md5.py)
* [Sdbm](hashes/sdbm.py)
* [Sha1](hashes/sha1.py)
* [Sha256](hashes/sha256.py)
## Knapsack
* [Greedy Knapsack](knapsack/greedy_knapsack.py)
* [Knapsack](knapsack/knapsack.py)
* Tests
* [Test Greedy Knapsack](knapsack/tests/test_greedy_knapsack.py)
* [Test Knapsack](knapsack/tests/test_knapsack.py)
## Linear Algebra
* Src
* [Conjugate Gradient](linear_algebra/src/conjugate_gradient.py)
* [Lib](linear_algebra/src/lib.py)
* [Polynom For Points](linear_algebra/src/polynom_for_points.py)
* [Power Iteration](linear_algebra/src/power_iteration.py)
* [Rayleigh Quotient](linear_algebra/src/rayleigh_quotient.py)
* [Schur Complement](linear_algebra/src/schur_complement.py)
* [Test Linear Algebra](linear_algebra/src/test_linear_algebra.py)
* [Transformations 2D](linear_algebra/src/transformations_2d.py)
## Machine Learning
* [Astar](machine_learning/astar.py)
* [Data Transformations](machine_learning/data_transformations.py)
* [Decision Tree](machine_learning/decision_tree.py)
* Forecasting
* [Run](machine_learning/forecasting/run.py)
* [Gaussian Naive Bayes](machine_learning/gaussian_naive_bayes.py)
* [Gradient Boosting Regressor](machine_learning/gradient_boosting_regressor.py)
* [Gradient Descent](machine_learning/gradient_descent.py)
* [K Means Clust](machine_learning/k_means_clust.py)
* [K Nearest Neighbours](machine_learning/k_nearest_neighbours.py)
* [Knn Sklearn](machine_learning/knn_sklearn.py)
* [Linear Discriminant Analysis](machine_learning/linear_discriminant_analysis.py)
* [Linear Regression](machine_learning/linear_regression.py)
* Local Weighted Learning
* [Local Weighted Learning](machine_learning/local_weighted_learning/local_weighted_learning.py)
* [Logistic Regression](machine_learning/logistic_regression.py)
* Lstm
* [Lstm Prediction](machine_learning/lstm/lstm_prediction.py)
* [Multilayer Perceptron Classifier](machine_learning/multilayer_perceptron_classifier.py)
* [Polymonial Regression](machine_learning/polymonial_regression.py)
* [Random Forest Classifier](machine_learning/random_forest_classifier.py)
* [Random Forest Regressor](machine_learning/random_forest_regressor.py)
* [Scoring Functions](machine_learning/scoring_functions.py)
* [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)
## Maths
* [3N Plus 1](maths/3n_plus_1.py)
* [Abs](maths/abs.py)
* [Abs Max](maths/abs_max.py)
* [Abs Min](maths/abs_min.py)
* [Add](maths/add.py)
* [Aliquot Sum](maths/aliquot_sum.py)
* [Allocation Number](maths/allocation_number.py)
* [Area](maths/area.py)
* [Area Under Curve](maths/area_under_curve.py)
* [Armstrong Numbers](maths/armstrong_numbers.py)
* [Average Absolute Deviation](maths/average_absolute_deviation.py)
* [Average Mean](maths/average_mean.py)
* [Average Median](maths/average_median.py)
* [Average Mode](maths/average_mode.py)
* [Bailey Borwein Plouffe](maths/bailey_borwein_plouffe.py)
* [Basic Maths](maths/basic_maths.py)
* [Binary Exp Mod](maths/binary_exp_mod.py)
* [Binary Exponentiation](maths/binary_exponentiation.py)
* [Binary Exponentiation 2](maths/binary_exponentiation_2.py)
* [Binary Exponentiation 3](maths/binary_exponentiation_3.py)
* [Binomial Coefficient](maths/binomial_coefficient.py)
* [Binomial Distribution](maths/binomial_distribution.py)
* [Bisection](maths/bisection.py)
* [Ceil](maths/ceil.py)
* [Check Polygon](maths/check_polygon.py)
* [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py)
* [Collatz Sequence](maths/collatz_sequence.py)
* [Combinations](maths/combinations.py)
* [Decimal Isolate](maths/decimal_isolate.py)
* [Double Factorial Iterative](maths/double_factorial_iterative.py)
* [Double Factorial Recursive](maths/double_factorial_recursive.py)
* [Entropy](maths/entropy.py)
* [Euclidean Distance](maths/euclidean_distance.py)
* [Euclidean Gcd](maths/euclidean_gcd.py)
* [Euler Method](maths/euler_method.py)
* [Euler Modified](maths/euler_modified.py)
* [Eulers Totient](maths/eulers_totient.py)
* [Extended Euclidean Algorithm](maths/extended_euclidean_algorithm.py)
* [Factorial Iterative](maths/factorial_iterative.py)
* [Factorial Recursive](maths/factorial_recursive.py)
* [Factors](maths/factors.py)
* [Fermat Little Theorem](maths/fermat_little_theorem.py)
* [Fibonacci](maths/fibonacci.py)
* [Find Max](maths/find_max.py)
* [Find Max Recursion](maths/find_max_recursion.py)
* [Find Min](maths/find_min.py)
* [Find Min Recursion](maths/find_min_recursion.py)
* [Floor](maths/floor.py)
* [Gamma](maths/gamma.py)
* [Gamma Recursive](maths/gamma_recursive.py)
* [Gaussian](maths/gaussian.py)
* [Greatest Common Divisor](maths/greatest_common_divisor.py)
* [Greedy Coin Change](maths/greedy_coin_change.py)
* [Hardy Ramanujanalgo](maths/hardy_ramanujanalgo.py)
* [Integration By Simpson Approx](maths/integration_by_simpson_approx.py)
* [Is Ip V4 Address Valid](maths/is_ip_v4_address_valid.py)
* [Is Square Free](maths/is_square_free.py)
* [Jaccard Similarity](maths/jaccard_similarity.py)
* [Kadanes](maths/kadanes.py)
* [Karatsuba](maths/karatsuba.py)
* [Krishnamurthy Number](maths/krishnamurthy_number.py)
* [Kth Lexicographic Permutation](maths/kth_lexicographic_permutation.py)
* [Largest Of Very Large Numbers](maths/largest_of_very_large_numbers.py)
* [Largest Subarray Sum](maths/largest_subarray_sum.py)
* [Least Common Multiple](maths/least_common_multiple.py)
* [Line Length](maths/line_length.py)
* [Lucas Lehmer Primality Test](maths/lucas_lehmer_primality_test.py)
* [Lucas Series](maths/lucas_series.py)
* [Matrix Exponentiation](maths/matrix_exponentiation.py)
* [Max Sum Sliding Window](maths/max_sum_sliding_window.py)
* [Median Of Two Arrays](maths/median_of_two_arrays.py)
* [Miller Rabin](maths/miller_rabin.py)
* [Mobius Function](maths/mobius_function.py)
* [Modular Exponential](maths/modular_exponential.py)
* [Monte Carlo](maths/monte_carlo.py)
* [Monte Carlo Dice](maths/monte_carlo_dice.py)
* [Nevilles Method](maths/nevilles_method.py)
* [Newton Raphson](maths/newton_raphson.py)
* [Number Of Digits](maths/number_of_digits.py)
* [Numerical Integration](maths/numerical_integration.py)
* [Perfect Cube](maths/perfect_cube.py)
* [Perfect Number](maths/perfect_number.py)
* [Perfect Square](maths/perfect_square.py)
* [Persistence](maths/persistence.py)
* [Pi Monte Carlo Estimation](maths/pi_monte_carlo_estimation.py)
* [Points Are Collinear 3D](maths/points_are_collinear_3d.py)
* [Pollard Rho](maths/pollard_rho.py)
* [Polynomial Evaluation](maths/polynomial_evaluation.py)
* [Power Using Recursion](maths/power_using_recursion.py)
* [Prime Check](maths/prime_check.py)
* [Prime Factors](maths/prime_factors.py)
* [Prime Numbers](maths/prime_numbers.py)
* [Prime Sieve Eratosthenes](maths/prime_sieve_eratosthenes.py)
* [Primelib](maths/primelib.py)
* [Proth Number](maths/proth_number.py)
* [Pythagoras](maths/pythagoras.py)
* [Qr Decomposition](maths/qr_decomposition.py)
* [Quadratic Equations Complex Numbers](maths/quadratic_equations_complex_numbers.py)
* [Radians](maths/radians.py)
* [Radix2 Fft](maths/radix2_fft.py)
* [Relu](maths/relu.py)
* [Runge Kutta](maths/runge_kutta.py)
* [Segmented Sieve](maths/segmented_sieve.py)
* Series
* [Arithmetic](maths/series/arithmetic.py)
* [Geometric](maths/series/geometric.py)
* [Geometric Series](maths/series/geometric_series.py)
* [Harmonic](maths/series/harmonic.py)
* [Harmonic Series](maths/series/harmonic_series.py)
* [Hexagonal Numbers](maths/series/hexagonal_numbers.py)
* [P Series](maths/series/p_series.py)
* [Sieve Of Eratosthenes](maths/sieve_of_eratosthenes.py)
* [Sigmoid](maths/sigmoid.py)
* [Simpson Rule](maths/simpson_rule.py)
* [Sin](maths/sin.py)
* [Sock Merchant](maths/sock_merchant.py)
* [Softmax](maths/softmax.py)
* [Square Root](maths/square_root.py)
* [Sum Of Arithmetic Series](maths/sum_of_arithmetic_series.py)
* [Sum Of Digits](maths/sum_of_digits.py)
* [Sum Of Geometric Progression](maths/sum_of_geometric_progression.py)
* [Sylvester Sequence](maths/sylvester_sequence.py)
* [Test Prime Check](maths/test_prime_check.py)
* [Trapezoidal Rule](maths/trapezoidal_rule.py)
* [Triplet Sum](maths/triplet_sum.py)
* [Two Pointer](maths/two_pointer.py)
* [Two Sum](maths/two_sum.py)
* [Ugly Numbers](maths/ugly_numbers.py)
* [Volume](maths/volume.py)
* [Zellers Congruence](maths/zellers_congruence.py)
## Matrix
* [Count Islands In Matrix](matrix/count_islands_in_matrix.py)
* [Inverse Of Matrix](matrix/inverse_of_matrix.py)
* [Matrix Class](matrix/matrix_class.py)
* [Matrix Operation](matrix/matrix_operation.py)
* [Nth Fibonacci Using Matrix Exponentiation](matrix/nth_fibonacci_using_matrix_exponentiation.py)
* [Rotate Matrix](matrix/rotate_matrix.py)
* [Searching In Sorted Matrix](matrix/searching_in_sorted_matrix.py)
* [Sherman Morrison](matrix/sherman_morrison.py)
* [Spiral Print](matrix/spiral_print.py)
* Tests
* [Test Matrix Operation](matrix/tests/test_matrix_operation.py)
## Networking Flow
* [Ford Fulkerson](networking_flow/ford_fulkerson.py)
* [Minimum Cut](networking_flow/minimum_cut.py)
## Neural Network
* [2 Hidden Layers Neural Network](neural_network/2_hidden_layers_neural_network.py)
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
* [Perceptron](neural_network/perceptron.py)
## Other
* [Activity Selection](other/activity_selection.py)
* [Alternative List Arrange](other/alternative_list_arrange.py)
* [Check Strong Password](other/check_strong_password.py)
* [Davisb Putnamb Logemannb Loveland](other/davisb_putnamb_logemannb_loveland.py)
* [Dijkstra Bankers Algorithm](other/dijkstra_bankers_algorithm.py)
* [Doomsday](other/doomsday.py)
* [Fischer Yates Shuffle](other/fischer_yates_shuffle.py)
* [Gauss Easter](other/gauss_easter.py)
* [Graham Scan](other/graham_scan.py)
* [Greedy](other/greedy.py)
* [Least Recently Used](other/least_recently_used.py)
* [Lfu Cache](other/lfu_cache.py)
* [Linear Congruential Generator](other/linear_congruential_generator.py)
* [Lru Cache](other/lru_cache.py)
* [Magicdiamondpattern](other/magicdiamondpattern.py)
* [Nested Brackets](other/nested_brackets.py)
* [Password Generator](other/password_generator.py)
* [Scoring Algorithm](other/scoring_algorithm.py)
* [Sdes](other/sdes.py)
* [Tower Of Hanoi](other/tower_of_hanoi.py)
## Physics
* [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py)
* [Lorenz Transformation Four Vector](physics/lorenz_transformation_four_vector.py)
* [N Body Simulation](physics/n_body_simulation.py)
* [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py)
## Project Euler
* Problem 001
* [Sol1](project_euler/problem_001/sol1.py)
* [Sol2](project_euler/problem_001/sol2.py)
* [Sol3](project_euler/problem_001/sol3.py)
* [Sol4](project_euler/problem_001/sol4.py)
* [Sol5](project_euler/problem_001/sol5.py)
* [Sol6](project_euler/problem_001/sol6.py)
* [Sol7](project_euler/problem_001/sol7.py)
* Problem 002
* [Sol1](project_euler/problem_002/sol1.py)
* [Sol2](project_euler/problem_002/sol2.py)
* [Sol3](project_euler/problem_002/sol3.py)
* [Sol4](project_euler/problem_002/sol4.py)
* [Sol5](project_euler/problem_002/sol5.py)
* Problem 003
* [Sol1](project_euler/problem_003/sol1.py)
* [Sol2](project_euler/problem_003/sol2.py)
* [Sol3](project_euler/problem_003/sol3.py)
* Problem 004
* [Sol1](project_euler/problem_004/sol1.py)
* [Sol2](project_euler/problem_004/sol2.py)
* Problem 005
* [Sol1](project_euler/problem_005/sol1.py)
* [Sol2](project_euler/problem_005/sol2.py)
* Problem 006
* [Sol1](project_euler/problem_006/sol1.py)
* [Sol2](project_euler/problem_006/sol2.py)
* [Sol3](project_euler/problem_006/sol3.py)
* [Sol4](project_euler/problem_006/sol4.py)
* Problem 007
* [Sol1](project_euler/problem_007/sol1.py)
* [Sol2](project_euler/problem_007/sol2.py)
* [Sol3](project_euler/problem_007/sol3.py)
* Problem 008
* [Sol1](project_euler/problem_008/sol1.py)
* [Sol2](project_euler/problem_008/sol2.py)
* [Sol3](project_euler/problem_008/sol3.py)
* Problem 009
* [Sol1](project_euler/problem_009/sol1.py)
* [Sol2](project_euler/problem_009/sol2.py)
* [Sol3](project_euler/problem_009/sol3.py)
* Problem 010
* [Sol1](project_euler/problem_010/sol1.py)
* [Sol2](project_euler/problem_010/sol2.py)
* [Sol3](project_euler/problem_010/sol3.py)
* Problem 011
* [Sol1](project_euler/problem_011/sol1.py)
* [Sol2](project_euler/problem_011/sol2.py)
* Problem 012
* [Sol1](project_euler/problem_012/sol1.py)
* [Sol2](project_euler/problem_012/sol2.py)
* Problem 013
* [Sol1](project_euler/problem_013/sol1.py)
* Problem 014
* [Sol1](project_euler/problem_014/sol1.py)
* [Sol2](project_euler/problem_014/sol2.py)
* Problem 015
* [Sol1](project_euler/problem_015/sol1.py)
* Problem 016
* [Sol1](project_euler/problem_016/sol1.py)
* [Sol2](project_euler/problem_016/sol2.py)
* Problem 017
* [Sol1](project_euler/problem_017/sol1.py)
* Problem 018
* [Solution](project_euler/problem_018/solution.py)
* Problem 019
* [Sol1](project_euler/problem_019/sol1.py)
* Problem 020
* [Sol1](project_euler/problem_020/sol1.py)
* [Sol2](project_euler/problem_020/sol2.py)
* [Sol3](project_euler/problem_020/sol3.py)
* [Sol4](project_euler/problem_020/sol4.py)
* Problem 021
* [Sol1](project_euler/problem_021/sol1.py)
* Problem 022
* [Sol1](project_euler/problem_022/sol1.py)
* [Sol2](project_euler/problem_022/sol2.py)
* Problem 023
* [Sol1](project_euler/problem_023/sol1.py)
* Problem 024
* [Sol1](project_euler/problem_024/sol1.py)
* Problem 025
* [Sol1](project_euler/problem_025/sol1.py)
* [Sol2](project_euler/problem_025/sol2.py)
* [Sol3](project_euler/problem_025/sol3.py)
* Problem 026
* [Sol1](project_euler/problem_026/sol1.py)
* Problem 027
* [Sol1](project_euler/problem_027/sol1.py)
* Problem 028
* [Sol1](project_euler/problem_028/sol1.py)
* Problem 029
* [Sol1](project_euler/problem_029/sol1.py)
* Problem 030
* [Sol1](project_euler/problem_030/sol1.py)
* Problem 031
* [Sol1](project_euler/problem_031/sol1.py)
* [Sol2](project_euler/problem_031/sol2.py)
* Problem 032
* [Sol32](project_euler/problem_032/sol32.py)
* Problem 033
* [Sol1](project_euler/problem_033/sol1.py)
* Problem 034
* [Sol1](project_euler/problem_034/sol1.py)
* Problem 035
* [Sol1](project_euler/problem_035/sol1.py)
* Problem 036
* [Sol1](project_euler/problem_036/sol1.py)
* Problem 037
* [Sol1](project_euler/problem_037/sol1.py)
* Problem 038
* [Sol1](project_euler/problem_038/sol1.py)
* Problem 039
* [Sol1](project_euler/problem_039/sol1.py)
* Problem 040
* [Sol1](project_euler/problem_040/sol1.py)
* Problem 041
* [Sol1](project_euler/problem_041/sol1.py)
* Problem 042
* [Solution42](project_euler/problem_042/solution42.py)
* Problem 043
* [Sol1](project_euler/problem_043/sol1.py)
* Problem 044
* [Sol1](project_euler/problem_044/sol1.py)
* Problem 045
* [Sol1](project_euler/problem_045/sol1.py)
* Problem 046
* [Sol1](project_euler/problem_046/sol1.py)
* Problem 047
* [Sol1](project_euler/problem_047/sol1.py)
* Problem 048
* [Sol1](project_euler/problem_048/sol1.py)
* Problem 049
* [Sol1](project_euler/problem_049/sol1.py)
* Problem 050
* [Sol1](project_euler/problem_050/sol1.py)
* Problem 051
* [Sol1](project_euler/problem_051/sol1.py)
* Problem 052
* [Sol1](project_euler/problem_052/sol1.py)
* Problem 053
* [Sol1](project_euler/problem_053/sol1.py)
* Problem 054
* [Sol1](project_euler/problem_054/sol1.py)
* [Test Poker Hand](project_euler/problem_054/test_poker_hand.py)
* Problem 055
* [Sol1](project_euler/problem_055/sol1.py)
* Problem 056
* [Sol1](project_euler/problem_056/sol1.py)
* Problem 057
* [Sol1](project_euler/problem_057/sol1.py)
* Problem 058
* [Sol1](project_euler/problem_058/sol1.py)
* Problem 059
* [Sol1](project_euler/problem_059/sol1.py)
* Problem 062
* [Sol1](project_euler/problem_062/sol1.py)
* Problem 063
* [Sol1](project_euler/problem_063/sol1.py)
* Problem 064
* [Sol1](project_euler/problem_064/sol1.py)
* Problem 065
* [Sol1](project_euler/problem_065/sol1.py)
* Problem 067
* [Sol1](project_euler/problem_067/sol1.py)
* [Sol2](project_euler/problem_067/sol2.py)
* Problem 068
* [Sol1](project_euler/problem_068/sol1.py)
* Problem 069
* [Sol1](project_euler/problem_069/sol1.py)
* Problem 070
* [Sol1](project_euler/problem_070/sol1.py)
* Problem 071
* [Sol1](project_euler/problem_071/sol1.py)
* Problem 072
* [Sol1](project_euler/problem_072/sol1.py)
* [Sol2](project_euler/problem_072/sol2.py)
* Problem 074
* [Sol1](project_euler/problem_074/sol1.py)
* [Sol2](project_euler/problem_074/sol2.py)
* Problem 075
* [Sol1](project_euler/problem_075/sol1.py)
* Problem 076
* [Sol1](project_euler/problem_076/sol1.py)
* Problem 077
* [Sol1](project_euler/problem_077/sol1.py)
* Problem 078
* [Sol1](project_euler/problem_078/sol1.py)
* Problem 080
* [Sol1](project_euler/problem_080/sol1.py)
* Problem 081
* [Sol1](project_euler/problem_081/sol1.py)
* Problem 085
* [Sol1](project_euler/problem_085/sol1.py)
* Problem 086
* [Sol1](project_euler/problem_086/sol1.py)
* Problem 087
* [Sol1](project_euler/problem_087/sol1.py)
* Problem 089
* [Sol1](project_euler/problem_089/sol1.py)
* Problem 091
* [Sol1](project_euler/problem_091/sol1.py)
* Problem 092
* [Sol1](project_euler/problem_092/sol1.py)
* Problem 097
* [Sol1](project_euler/problem_097/sol1.py)
* Problem 099
* [Sol1](project_euler/problem_099/sol1.py)
* Problem 101
* [Sol1](project_euler/problem_101/sol1.py)
* Problem 102
* [Sol1](project_euler/problem_102/sol1.py)
* Problem 104
* [Sol](project_euler/problem_104/sol.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 119
* [Sol1](project_euler/problem_119/sol1.py)
* Problem 120
* [Sol1](project_euler/problem_120/sol1.py)
* Problem 121
* [Sol1](project_euler/problem_121/sol1.py)
* Problem 123
* [Sol1](project_euler/problem_123/sol1.py)
* Problem 125
* [Sol1](project_euler/problem_125/sol1.py)
* Problem 129
* [Sol1](project_euler/problem_129/sol1.py)
* Problem 135
* [Sol1](project_euler/problem_135/sol1.py)
* Problem 144
* [Sol1](project_euler/problem_144/sol1.py)
* Problem 145
* [Sol1](project_euler/problem_145/sol1.py)
* Problem 173
* [Sol1](project_euler/problem_173/sol1.py)
* Problem 174
* [Sol1](project_euler/problem_174/sol1.py)
* Problem 180
* [Sol1](project_euler/problem_180/sol1.py)
* Problem 188
* [Sol1](project_euler/problem_188/sol1.py)
* Problem 191
* [Sol1](project_euler/problem_191/sol1.py)
* Problem 203
* [Sol1](project_euler/problem_203/sol1.py)
* Problem 205
* [Sol1](project_euler/problem_205/sol1.py)
* Problem 206
* [Sol1](project_euler/problem_206/sol1.py)
* Problem 207
* [Sol1](project_euler/problem_207/sol1.py)
* Problem 234
* [Sol1](project_euler/problem_234/sol1.py)
* Problem 301
* [Sol1](project_euler/problem_301/sol1.py)
* Problem 493
* [Sol1](project_euler/problem_493/sol1.py)
* Problem 551
* [Sol1](project_euler/problem_551/sol1.py)
* Problem 686
* [Sol1](project_euler/problem_686/sol1.py)
## Quantum
* [Deutsch Jozsa](quantum/deutsch_jozsa.py)
* [Half Adder](quantum/half_adder.py)
* [Not Gate](quantum/not_gate.py)
* [Quantum Entanglement](quantum/quantum_entanglement.py)
* [Ripple Adder Classic](quantum/ripple_adder_classic.py)
* [Single Qubit Measure](quantum/single_qubit_measure.py)
## Scheduling
* [First Come First Served](scheduling/first_come_first_served.py)
* [Highest Response Ratio Next](scheduling/highest_response_ratio_next.py)
* [Multi Level Feedback Queue](scheduling/multi_level_feedback_queue.py)
* [Non Preemptive Shortest Job First](scheduling/non_preemptive_shortest_job_first.py)
* [Round Robin](scheduling/round_robin.py)
* [Shortest Job First](scheduling/shortest_job_first.py)
## Searches
* [Binary Search](searches/binary_search.py)
* [Binary Tree Traversal](searches/binary_tree_traversal.py)
* [Double Linear Search](searches/double_linear_search.py)
* [Double Linear Search Recursion](searches/double_linear_search_recursion.py)
* [Fibonacci Search](searches/fibonacci_search.py)
* [Hill Climbing](searches/hill_climbing.py)
* [Interpolation Search](searches/interpolation_search.py)
* [Jump Search](searches/jump_search.py)
* [Linear Search](searches/linear_search.py)
* [Quick Select](searches/quick_select.py)
* [Sentinel Linear Search](searches/sentinel_linear_search.py)
* [Simple Binary Search](searches/simple_binary_search.py)
* [Simulated Annealing](searches/simulated_annealing.py)
* [Tabu Search](searches/tabu_search.py)
* [Ternary Search](searches/ternary_search.py)
## Sorts
* [Bead Sort](sorts/bead_sort.py)
* [Bitonic Sort](sorts/bitonic_sort.py)
* [Bogo Sort](sorts/bogo_sort.py)
* [Bubble Sort](sorts/bubble_sort.py)
* [Bucket Sort](sorts/bucket_sort.py)
* [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)
* [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)
* [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)
* [Check Pangram](strings/check_pangram.py)
* [Credit Card Validator](strings/credit_card_validator.py)
* [Detecting English Programmatically](strings/detecting_english_programmatically.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 Palindrome](strings/is_palindrome.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)
* [Split](strings/split.py)
* [Upper](strings/upper.py)
* [Wave](strings/wave.py)
* [Wildcard Pattern Matching](strings/wildcard_pattern_matching.py)
* [Word Occurrence](strings/word_occurrence.py)
* [Word Patterns](strings/word_patterns.py)
* [Z Function](strings/z_function.py)
## Web Programming
* [Co2 Emission](web_programming/co2_emission.py)
* [Covid Stats Via Xpath](web_programming/covid_stats_via_xpath.py)
* [Crawl Google Results](web_programming/crawl_google_results.py)
* [Crawl Google Scholar Citation](web_programming/crawl_google_scholar_citation.py)
* [Currency Converter](web_programming/currency_converter.py)
* [Current Stock Price](web_programming/current_stock_price.py)
* [Current Weather](web_programming/current_weather.py)
* [Daily Horoscope](web_programming/daily_horoscope.py)
* [Download Images From Google Query](web_programming/download_images_from_google_query.py)
* [Emails From Url](web_programming/emails_from_url.py)
* [Fetch Anime And Play](web_programming/fetch_anime_and_play.py)
* [Fetch Bbc News](web_programming/fetch_bbc_news.py)
* [Fetch Github Info](web_programming/fetch_github_info.py)
* [Fetch Jobs](web_programming/fetch_jobs.py)
* [Fetch Well Rx Price](web_programming/fetch_well_rx_price.py)
* [Get Imdb Top 250 Movies Csv](web_programming/get_imdb_top_250_movies_csv.py)
* [Get Imdbtop](web_programming/get_imdbtop.py)
* [Get Top 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)
* [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)
* [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)
* [Hamiltonian Cycle](backtracking/hamiltonian_cycle.py)
* [Knight Tour](backtracking/knight_tour.py)
* [Minimax](backtracking/minimax.py)
* [N Queens](backtracking/n_queens.py)
* [N Queens Math](backtracking/n_queens_math.py)
* [Rat In Maze](backtracking/rat_in_maze.py)
* [Sudoku](backtracking/sudoku.py)
* [Sum Of Subsets](backtracking/sum_of_subsets.py)
## Bit Manipulation
* [Binary And Operator](bit_manipulation/binary_and_operator.py)
* [Binary Count Setbits](bit_manipulation/binary_count_setbits.py)
* [Binary Count Trailing Zeros](bit_manipulation/binary_count_trailing_zeros.py)
* [Binary Or Operator](bit_manipulation/binary_or_operator.py)
* [Binary Shifts](bit_manipulation/binary_shifts.py)
* [Binary Twos Complement](bit_manipulation/binary_twos_complement.py)
* [Binary Xor Operator](bit_manipulation/binary_xor_operator.py)
* [Count 1S Brian Kernighan Method](bit_manipulation/count_1s_brian_kernighan_method.py)
* [Count Number Of One Bits](bit_manipulation/count_number_of_one_bits.py)
* [Gray Code Sequence](bit_manipulation/gray_code_sequence.py)
* [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
* [Quine Mc Cluskey](boolean_algebra/quine_mc_cluskey.py)
## Cellular Automata
* [Conways Game Of Life](cellular_automata/conways_game_of_life.py)
* [Game Of Life](cellular_automata/game_of_life.py)
* [Nagel Schrekenberg](cellular_automata/nagel_schrekenberg.py)
* [One Dimensional](cellular_automata/one_dimensional.py)
## Ciphers
* [A1Z26](ciphers/a1z26.py)
* [Affine Cipher](ciphers/affine_cipher.py)
* [Atbash](ciphers/atbash.py)
* [Baconian Cipher](ciphers/baconian_cipher.py)
* [Base16](ciphers/base16.py)
* [Base32](ciphers/base32.py)
* [Base64](ciphers/base64.py)
* [Base85](ciphers/base85.py)
* [Beaufort Cipher](ciphers/beaufort_cipher.py)
* [Bifid](ciphers/bifid.py)
* [Brute Force Caesar Cipher](ciphers/brute_force_caesar_cipher.py)
* [Caesar Cipher](ciphers/caesar_cipher.py)
* [Cryptomath Module](ciphers/cryptomath_module.py)
* [Decrypt Caesar With Chi Squared](ciphers/decrypt_caesar_with_chi_squared.py)
* [Deterministic Miller Rabin](ciphers/deterministic_miller_rabin.py)
* [Diffie](ciphers/diffie.py)
* [Diffie Hellman](ciphers/diffie_hellman.py)
* [Elgamal Key Generator](ciphers/elgamal_key_generator.py)
* [Enigma Machine2](ciphers/enigma_machine2.py)
* [Hill Cipher](ciphers/hill_cipher.py)
* [Mixed Keyword Cypher](ciphers/mixed_keyword_cypher.py)
* [Mono Alphabetic Ciphers](ciphers/mono_alphabetic_ciphers.py)
* [Morse Code](ciphers/morse_code.py)
* [Onepad Cipher](ciphers/onepad_cipher.py)
* [Playfair Cipher](ciphers/playfair_cipher.py)
* [Polybius](ciphers/polybius.py)
* [Porta Cipher](ciphers/porta_cipher.py)
* [Rabin Miller](ciphers/rabin_miller.py)
* [Rail Fence Cipher](ciphers/rail_fence_cipher.py)
* [Rot13](ciphers/rot13.py)
* [Rsa Cipher](ciphers/rsa_cipher.py)
* [Rsa Factorization](ciphers/rsa_factorization.py)
* [Rsa Key Generator](ciphers/rsa_key_generator.py)
* [Shuffled Shift Cipher](ciphers/shuffled_shift_cipher.py)
* [Simple Keyword Cypher](ciphers/simple_keyword_cypher.py)
* [Simple Substitution Cipher](ciphers/simple_substitution_cipher.py)
* [Trafid Cipher](ciphers/trafid_cipher.py)
* [Transposition Cipher](ciphers/transposition_cipher.py)
* [Transposition Cipher Encrypt Decrypt File](ciphers/transposition_cipher_encrypt_decrypt_file.py)
* [Vigenere Cipher](ciphers/vigenere_cipher.py)
* [Xor Cipher](ciphers/xor_cipher.py)
## Compression
* [Burrows Wheeler](compression/burrows_wheeler.py)
* [Huffman](compression/huffman.py)
* [Lempel Ziv](compression/lempel_ziv.py)
* [Lempel Ziv Decompress](compression/lempel_ziv_decompress.py)
* [Peak Signal To Noise Ratio](compression/peak_signal_to_noise_ratio.py)
## 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
* [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)
* [Temperature Conversions](conversions/temperature_conversions.py)
* [Volume Conversions](conversions/volume_conversions.py)
* [Weight Conversion](conversions/weight_conversion.py)
## Data Structures
* Binary Tree
* [Avl Tree](data_structures/binary_tree/avl_tree.py)
* [Basic Binary Tree](data_structures/binary_tree/basic_binary_tree.py)
* [Binary Search Tree](data_structures/binary_tree/binary_search_tree.py)
* [Binary Search Tree Recursive](data_structures/binary_tree/binary_search_tree_recursive.py)
* [Binary Tree Mirror](data_structures/binary_tree/binary_tree_mirror.py)
* [Binary Tree Traversals](data_structures/binary_tree/binary_tree_traversals.py)
* [Fenwick Tree](data_structures/binary_tree/fenwick_tree.py)
* [Lazy Segment Tree](data_structures/binary_tree/lazy_segment_tree.py)
* [Lowest Common Ancestor](data_structures/binary_tree/lowest_common_ancestor.py)
* [Merge Two Binary Trees](data_structures/binary_tree/merge_two_binary_trees.py)
* [Non Recursive Segment Tree](data_structures/binary_tree/non_recursive_segment_tree.py)
* [Number Of Possible Binary Trees](data_structures/binary_tree/number_of_possible_binary_trees.py)
* [Red Black Tree](data_structures/binary_tree/red_black_tree.py)
* [Segment Tree](data_structures/binary_tree/segment_tree.py)
* [Segment Tree Other](data_structures/binary_tree/segment_tree_other.py)
* [Treap](data_structures/binary_tree/treap.py)
* [Wavelet Tree](data_structures/binary_tree/wavelet_tree.py)
* Disjoint Set
* [Alternate Disjoint Set](data_structures/disjoint_set/alternate_disjoint_set.py)
* [Disjoint Set](data_structures/disjoint_set/disjoint_set.py)
* Hashing
* [Double Hash](data_structures/hashing/double_hash.py)
* [Hash Table](data_structures/hashing/hash_table.py)
* [Hash Table With Linked List](data_structures/hashing/hash_table_with_linked_list.py)
* Number Theory
* [Prime Numbers](data_structures/hashing/number_theory/prime_numbers.py)
* [Quadratic Probing](data_structures/hashing/quadratic_probing.py)
* Heap
* [Binomial Heap](data_structures/heap/binomial_heap.py)
* [Heap](data_structures/heap/heap.py)
* [Heap Generic](data_structures/heap/heap_generic.py)
* [Max Heap](data_structures/heap/max_heap.py)
* [Min Heap](data_structures/heap/min_heap.py)
* [Randomized Heap](data_structures/heap/randomized_heap.py)
* [Skew Heap](data_structures/heap/skew_heap.py)
* Linked List
* [Circular Linked List](data_structures/linked_list/circular_linked_list.py)
* [Deque Doubly](data_structures/linked_list/deque_doubly.py)
* [Doubly Linked List](data_structures/linked_list/doubly_linked_list.py)
* [Doubly Linked List Two](data_structures/linked_list/doubly_linked_list_two.py)
* [From Sequence](data_structures/linked_list/from_sequence.py)
* [Has Loop](data_structures/linked_list/has_loop.py)
* [Is Palindrome](data_structures/linked_list/is_palindrome.py)
* [Merge Two Lists](data_structures/linked_list/merge_two_lists.py)
* [Middle Element Of Linked List](data_structures/linked_list/middle_element_of_linked_list.py)
* [Print Reverse](data_structures/linked_list/print_reverse.py)
* [Singly Linked List](data_structures/linked_list/singly_linked_list.py)
* [Skip List](data_structures/linked_list/skip_list.py)
* [Swap Nodes](data_structures/linked_list/swap_nodes.py)
* Queue
* [Circular Queue](data_structures/queue/circular_queue.py)
* [Circular Queue Linked List](data_structures/queue/circular_queue_linked_list.py)
* [Double Ended Queue](data_structures/queue/double_ended_queue.py)
* [Linked Queue](data_structures/queue/linked_queue.py)
* [Priority Queue Using List](data_structures/queue/priority_queue_using_list.py)
* [Queue On List](data_structures/queue/queue_on_list.py)
* [Queue On Pseudo Stack](data_structures/queue/queue_on_pseudo_stack.py)
* Stacks
* [Balanced Parentheses](data_structures/stacks/balanced_parentheses.py)
* [Dijkstras Two Stack Algorithm](data_structures/stacks/dijkstras_two_stack_algorithm.py)
* [Evaluate Postfix Notations](data_structures/stacks/evaluate_postfix_notations.py)
* [Infix To Postfix Conversion](data_structures/stacks/infix_to_postfix_conversion.py)
* [Infix To Prefix Conversion](data_structures/stacks/infix_to_prefix_conversion.py)
* [Next Greater Element](data_structures/stacks/next_greater_element.py)
* [Postfix Evaluation](data_structures/stacks/postfix_evaluation.py)
* [Prefix Evaluation](data_structures/stacks/prefix_evaluation.py)
* [Stack](data_structures/stacks/stack.py)
* [Stack With Doubly Linked List](data_structures/stacks/stack_with_doubly_linked_list.py)
* [Stack With Singly Linked List](data_structures/stacks/stack_with_singly_linked_list.py)
* [Stock Span Problem](data_structures/stacks/stock_span_problem.py)
* Trie
* [Trie](data_structures/trie/trie.py)
## Digital Image Processing
* [Change Brightness](digital_image_processing/change_brightness.py)
* [Change Contrast](digital_image_processing/change_contrast.py)
* [Convert To Negative](digital_image_processing/convert_to_negative.py)
* Dithering
* [Burkes](digital_image_processing/dithering/burkes.py)
* Edge Detection
* [Canny](digital_image_processing/edge_detection/canny.py)
* Filters
* [Bilateral Filter](digital_image_processing/filters/bilateral_filter.py)
* [Convolve](digital_image_processing/filters/convolve.py)
* [Gabor Filter](digital_image_processing/filters/gabor_filter.py)
* [Gaussian Filter](digital_image_processing/filters/gaussian_filter.py)
* [Median Filter](digital_image_processing/filters/median_filter.py)
* [Sobel Filter](digital_image_processing/filters/sobel_filter.py)
* Histogram Equalization
* [Histogram Stretch](digital_image_processing/histogram_equalization/histogram_stretch.py)
* [Index Calculation](digital_image_processing/index_calculation.py)
* Morphological Operations
* [Dilation Operation](digital_image_processing/morphological_operations/dilation_operation.py)
* [Erosion Operation](digital_image_processing/morphological_operations/erosion_operation.py)
* Resize
* [Resize](digital_image_processing/resize/resize.py)
* Rotation
* [Rotation](digital_image_processing/rotation/rotation.py)
* [Sepia](digital_image_processing/sepia.py)
* [Test Digital Image Processing](digital_image_processing/test_digital_image_processing.py)
## Divide And Conquer
* [Closest Pair Of Points](divide_and_conquer/closest_pair_of_points.py)
* [Convex Hull](divide_and_conquer/convex_hull.py)
* [Heaps Algorithm](divide_and_conquer/heaps_algorithm.py)
* [Heaps Algorithm Iterative](divide_and_conquer/heaps_algorithm_iterative.py)
* [Inversions](divide_and_conquer/inversions.py)
* [Kth Order Statistic](divide_and_conquer/kth_order_statistic.py)
* [Max Difference Pair](divide_and_conquer/max_difference_pair.py)
* [Max Subarray Sum](divide_and_conquer/max_subarray_sum.py)
* [Mergesort](divide_and_conquer/mergesort.py)
* [Peak](divide_and_conquer/peak.py)
* [Power](divide_and_conquer/power.py)
* [Strassen Matrix Multiplication](divide_and_conquer/strassen_matrix_multiplication.py)
## Dynamic Programming
* [Abbreviation](dynamic_programming/abbreviation.py)
* [All Construct](dynamic_programming/all_construct.py)
* [Bitmask](dynamic_programming/bitmask.py)
* [Catalan Numbers](dynamic_programming/catalan_numbers.py)
* [Climbing Stairs](dynamic_programming/climbing_stairs.py)
* [Edit Distance](dynamic_programming/edit_distance.py)
* [Factorial](dynamic_programming/factorial.py)
* [Fast Fibonacci](dynamic_programming/fast_fibonacci.py)
* [Fibonacci](dynamic_programming/fibonacci.py)
* [Floyd Warshall](dynamic_programming/floyd_warshall.py)
* [Fractional Knapsack](dynamic_programming/fractional_knapsack.py)
* [Fractional Knapsack 2](dynamic_programming/fractional_knapsack_2.py)
* [Integer Partition](dynamic_programming/integer_partition.py)
* [Iterating Through Submasks](dynamic_programming/iterating_through_submasks.py)
* [Knapsack](dynamic_programming/knapsack.py)
* [Longest Common Subsequence](dynamic_programming/longest_common_subsequence.py)
* [Longest Increasing Subsequence](dynamic_programming/longest_increasing_subsequence.py)
* [Longest Increasing Subsequence O(Nlogn)](dynamic_programming/longest_increasing_subsequence_o(nlogn).py)
* [Longest Sub Array](dynamic_programming/longest_sub_array.py)
* [Matrix Chain Order](dynamic_programming/matrix_chain_order.py)
* [Max Non Adjacent Sum](dynamic_programming/max_non_adjacent_sum.py)
* [Max Sub Array](dynamic_programming/max_sub_array.py)
* [Max Sum Contiguous Subsequence](dynamic_programming/max_sum_contiguous_subsequence.py)
* [Minimum Coin Change](dynamic_programming/minimum_coin_change.py)
* [Minimum Cost Path](dynamic_programming/minimum_cost_path.py)
* [Minimum Partition](dynamic_programming/minimum_partition.py)
* [Minimum Steps To One](dynamic_programming/minimum_steps_to_one.py)
* [Optimal Binary Search Tree](dynamic_programming/optimal_binary_search_tree.py)
* [Rod Cutting](dynamic_programming/rod_cutting.py)
* [Subset Generation](dynamic_programming/subset_generation.py)
* [Sum Of Subset](dynamic_programming/sum_of_subset.py)
## Electronics
* [Carrier Concentration](electronics/carrier_concentration.py)
* [Coulombs Law](electronics/coulombs_law.py)
* [Electric Power](electronics/electric_power.py)
* [Ohms Law](electronics/ohms_law.py)
## File Transfer
* [Receive File](file_transfer/receive_file.py)
* [Send File](file_transfer/send_file.py)
* Tests
* [Test Send File](file_transfer/tests/test_send_file.py)
## Financial
* [Equated Monthly Installments](financial/equated_monthly_installments.py)
* [Interest](financial/interest.py)
## Fractals
* [Julia Sets](fractals/julia_sets.py)
* [Koch Snowflake](fractals/koch_snowflake.py)
* [Mandelbrot](fractals/mandelbrot.py)
* [Sierpinski Triangle](fractals/sierpinski_triangle.py)
## Fuzzy Logic
* [Fuzzy Operations](fuzzy_logic/fuzzy_operations.py)
## Genetic Algorithm
* [Basic String](genetic_algorithm/basic_string.py)
## Geodesy
* [Haversine Distance](geodesy/haversine_distance.py)
* [Lamberts Ellipsoidal Distance](geodesy/lamberts_ellipsoidal_distance.py)
## Graphics
* [Bezier Curve](graphics/bezier_curve.py)
* [Vector3 For 2D Rendering](graphics/vector3_for_2d_rendering.py)
## Graphs
* [A Star](graphs/a_star.py)
* [Articulation Points](graphs/articulation_points.py)
* [Basic Graphs](graphs/basic_graphs.py)
* [Bellman Ford](graphs/bellman_ford.py)
* [Bfs Shortest Path](graphs/bfs_shortest_path.py)
* [Bfs Zero One Shortest Path](graphs/bfs_zero_one_shortest_path.py)
* [Bidirectional A Star](graphs/bidirectional_a_star.py)
* [Bidirectional Breadth First Search](graphs/bidirectional_breadth_first_search.py)
* [Boruvka](graphs/boruvka.py)
* [Breadth First Search](graphs/breadth_first_search.py)
* [Breadth First Search 2](graphs/breadth_first_search_2.py)
* [Breadth First Search Shortest Path](graphs/breadth_first_search_shortest_path.py)
* [Check Bipartite Graph Bfs](graphs/check_bipartite_graph_bfs.py)
* [Check Bipartite Graph Dfs](graphs/check_bipartite_graph_dfs.py)
* [Check Cycle](graphs/check_cycle.py)
* [Connected Components](graphs/connected_components.py)
* [Depth First Search](graphs/depth_first_search.py)
* [Depth First Search 2](graphs/depth_first_search_2.py)
* [Dijkstra](graphs/dijkstra.py)
* [Dijkstra 2](graphs/dijkstra_2.py)
* [Dijkstra Algorithm](graphs/dijkstra_algorithm.py)
* [Dinic](graphs/dinic.py)
* [Directed And Undirected (Weighted) Graph](graphs/directed_and_undirected_(weighted)_graph.py)
* [Edmonds Karp Multiple Source And Sink](graphs/edmonds_karp_multiple_source_and_sink.py)
* [Eulerian Path And Circuit For Undirected Graph](graphs/eulerian_path_and_circuit_for_undirected_graph.py)
* [Even Tree](graphs/even_tree.py)
* [Finding Bridges](graphs/finding_bridges.py)
* [Frequent Pattern Graph Miner](graphs/frequent_pattern_graph_miner.py)
* [G Topological Sort](graphs/g_topological_sort.py)
* [Gale Shapley Bigraph](graphs/gale_shapley_bigraph.py)
* [Graph List](graphs/graph_list.py)
* [Graph Matrix](graphs/graph_matrix.py)
* [Graphs Floyd Warshall](graphs/graphs_floyd_warshall.py)
* [Greedy Best First](graphs/greedy_best_first.py)
* [Greedy Min Vertex Cover](graphs/greedy_min_vertex_cover.py)
* [Kahns Algorithm Long](graphs/kahns_algorithm_long.py)
* [Kahns Algorithm Topo](graphs/kahns_algorithm_topo.py)
* [Karger](graphs/karger.py)
* [Markov Chain](graphs/markov_chain.py)
* [Matching Min Vertex Cover](graphs/matching_min_vertex_cover.py)
* [Minimum Path Sum](graphs/minimum_path_sum.py)
* [Minimum Spanning Tree Boruvka](graphs/minimum_spanning_tree_boruvka.py)
* [Minimum Spanning Tree Kruskal](graphs/minimum_spanning_tree_kruskal.py)
* [Minimum Spanning Tree Kruskal2](graphs/minimum_spanning_tree_kruskal2.py)
* [Minimum Spanning Tree Prims](graphs/minimum_spanning_tree_prims.py)
* [Minimum Spanning Tree Prims2](graphs/minimum_spanning_tree_prims2.py)
* [Multi Heuristic Astar](graphs/multi_heuristic_astar.py)
* [Page Rank](graphs/page_rank.py)
* [Prim](graphs/prim.py)
* [Random Graph Generator](graphs/random_graph_generator.py)
* [Scc Kosaraju](graphs/scc_kosaraju.py)
* [Strongly Connected Components](graphs/strongly_connected_components.py)
* [Tarjans Scc](graphs/tarjans_scc.py)
* Tests
* [Test Min Spanning Tree Kruskal](graphs/tests/test_min_spanning_tree_kruskal.py)
* [Test Min Spanning Tree Prim](graphs/tests/test_min_spanning_tree_prim.py)
## Greedy Methods
* [Optimal Merge Pattern](greedy_methods/optimal_merge_pattern.py)
## Hashes
* [Adler32](hashes/adler32.py)
* [Chaos Machine](hashes/chaos_machine.py)
* [Djb2](hashes/djb2.py)
* [Enigma Machine](hashes/enigma_machine.py)
* [Hamming Code](hashes/hamming_code.py)
* [Luhn](hashes/luhn.py)
* [Md5](hashes/md5.py)
* [Sdbm](hashes/sdbm.py)
* [Sha1](hashes/sha1.py)
* [Sha256](hashes/sha256.py)
## Knapsack
* [Greedy Knapsack](knapsack/greedy_knapsack.py)
* [Knapsack](knapsack/knapsack.py)
* Tests
* [Test Greedy Knapsack](knapsack/tests/test_greedy_knapsack.py)
* [Test Knapsack](knapsack/tests/test_knapsack.py)
## Linear Algebra
* Src
* [Conjugate Gradient](linear_algebra/src/conjugate_gradient.py)
* [Lib](linear_algebra/src/lib.py)
* [Polynom For Points](linear_algebra/src/polynom_for_points.py)
* [Power Iteration](linear_algebra/src/power_iteration.py)
* [Rayleigh Quotient](linear_algebra/src/rayleigh_quotient.py)
* [Schur Complement](linear_algebra/src/schur_complement.py)
* [Test Linear Algebra](linear_algebra/src/test_linear_algebra.py)
* [Transformations 2D](linear_algebra/src/transformations_2d.py)
## Machine Learning
* [Astar](machine_learning/astar.py)
* [Data Transformations](machine_learning/data_transformations.py)
* [Decision Tree](machine_learning/decision_tree.py)
* Forecasting
* [Run](machine_learning/forecasting/run.py)
* [Gaussian Naive Bayes](machine_learning/gaussian_naive_bayes.py)
* [Gradient Boosting Regressor](machine_learning/gradient_boosting_regressor.py)
* [Gradient Descent](machine_learning/gradient_descent.py)
* [K Means Clust](machine_learning/k_means_clust.py)
* [K Nearest Neighbours](machine_learning/k_nearest_neighbours.py)
* [Knn Sklearn](machine_learning/knn_sklearn.py)
* [Linear Discriminant Analysis](machine_learning/linear_discriminant_analysis.py)
* [Linear Regression](machine_learning/linear_regression.py)
* Local Weighted Learning
* [Local Weighted Learning](machine_learning/local_weighted_learning/local_weighted_learning.py)
* [Logistic Regression](machine_learning/logistic_regression.py)
* Lstm
* [Lstm Prediction](machine_learning/lstm/lstm_prediction.py)
* [Multilayer Perceptron Classifier](machine_learning/multilayer_perceptron_classifier.py)
* [Polymonial Regression](machine_learning/polymonial_regression.py)
* [Random Forest Classifier](machine_learning/random_forest_classifier.py)
* [Random Forest Regressor](machine_learning/random_forest_regressor.py)
* [Scoring Functions](machine_learning/scoring_functions.py)
* [Sequential Minimum Optimization](machine_learning/sequential_minimum_optimization.py)
* [Similarity Search](machine_learning/similarity_search.py)
* [Word Frequency Functions](machine_learning/word_frequency_functions.py)
## Maths
* [3N Plus 1](maths/3n_plus_1.py)
* [Abs](maths/abs.py)
* [Abs Max](maths/abs_max.py)
* [Abs Min](maths/abs_min.py)
* [Add](maths/add.py)
* [Aliquot Sum](maths/aliquot_sum.py)
* [Allocation Number](maths/allocation_number.py)
* [Area](maths/area.py)
* [Area Under Curve](maths/area_under_curve.py)
* [Armstrong Numbers](maths/armstrong_numbers.py)
* [Average Absolute Deviation](maths/average_absolute_deviation.py)
* [Average Mean](maths/average_mean.py)
* [Average Median](maths/average_median.py)
* [Average Mode](maths/average_mode.py)
* [Bailey Borwein Plouffe](maths/bailey_borwein_plouffe.py)
* [Basic Maths](maths/basic_maths.py)
* [Binary Exp Mod](maths/binary_exp_mod.py)
* [Binary Exponentiation](maths/binary_exponentiation.py)
* [Binary Exponentiation 2](maths/binary_exponentiation_2.py)
* [Binary Exponentiation 3](maths/binary_exponentiation_3.py)
* [Binomial Coefficient](maths/binomial_coefficient.py)
* [Binomial Distribution](maths/binomial_distribution.py)
* [Bisection](maths/bisection.py)
* [Ceil](maths/ceil.py)
* [Check Polygon](maths/check_polygon.py)
* [Chudnovsky Algorithm](maths/chudnovsky_algorithm.py)
* [Collatz Sequence](maths/collatz_sequence.py)
* [Combinations](maths/combinations.py)
* [Decimal Isolate](maths/decimal_isolate.py)
* [Double Factorial Iterative](maths/double_factorial_iterative.py)
* [Double Factorial Recursive](maths/double_factorial_recursive.py)
* [Entropy](maths/entropy.py)
* [Euclidean Distance](maths/euclidean_distance.py)
* [Euclidean Gcd](maths/euclidean_gcd.py)
* [Euler Method](maths/euler_method.py)
* [Euler Modified](maths/euler_modified.py)
* [Eulers Totient](maths/eulers_totient.py)
* [Extended Euclidean Algorithm](maths/extended_euclidean_algorithm.py)
* [Factorial Iterative](maths/factorial_iterative.py)
* [Factorial Recursive](maths/factorial_recursive.py)
* [Factors](maths/factors.py)
* [Fermat Little Theorem](maths/fermat_little_theorem.py)
* [Fibonacci](maths/fibonacci.py)
* [Find Max](maths/find_max.py)
* [Find Max Recursion](maths/find_max_recursion.py)
* [Find Min](maths/find_min.py)
* [Find Min Recursion](maths/find_min_recursion.py)
* [Floor](maths/floor.py)
* [Gamma](maths/gamma.py)
* [Gamma Recursive](maths/gamma_recursive.py)
* [Gaussian](maths/gaussian.py)
* [Greatest Common Divisor](maths/greatest_common_divisor.py)
* [Greedy Coin Change](maths/greedy_coin_change.py)
* [Hardy Ramanujanalgo](maths/hardy_ramanujanalgo.py)
* [Integration By Simpson Approx](maths/integration_by_simpson_approx.py)
* [Is Ip V4 Address Valid](maths/is_ip_v4_address_valid.py)
* [Is Square Free](maths/is_square_free.py)
* [Jaccard Similarity](maths/jaccard_similarity.py)
* [Kadanes](maths/kadanes.py)
* [Karatsuba](maths/karatsuba.py)
* [Krishnamurthy Number](maths/krishnamurthy_number.py)
* [Kth Lexicographic Permutation](maths/kth_lexicographic_permutation.py)
* [Largest Of Very Large Numbers](maths/largest_of_very_large_numbers.py)
* [Largest Subarray Sum](maths/largest_subarray_sum.py)
* [Least Common Multiple](maths/least_common_multiple.py)
* [Line Length](maths/line_length.py)
* [Lucas Lehmer Primality Test](maths/lucas_lehmer_primality_test.py)
* [Lucas Series](maths/lucas_series.py)
* [Matrix Exponentiation](maths/matrix_exponentiation.py)
* [Max Sum Sliding Window](maths/max_sum_sliding_window.py)
* [Median Of Two Arrays](maths/median_of_two_arrays.py)
* [Miller Rabin](maths/miller_rabin.py)
* [Mobius Function](maths/mobius_function.py)
* [Modular Exponential](maths/modular_exponential.py)
* [Monte Carlo](maths/monte_carlo.py)
* [Monte Carlo Dice](maths/monte_carlo_dice.py)
* [Nevilles Method](maths/nevilles_method.py)
* [Newton Raphson](maths/newton_raphson.py)
* [Number Of Digits](maths/number_of_digits.py)
* [Numerical Integration](maths/numerical_integration.py)
* [Perfect Cube](maths/perfect_cube.py)
* [Perfect Number](maths/perfect_number.py)
* [Perfect Square](maths/perfect_square.py)
* [Persistence](maths/persistence.py)
* [Pi Monte Carlo Estimation](maths/pi_monte_carlo_estimation.py)
* [Points Are Collinear 3D](maths/points_are_collinear_3d.py)
* [Pollard Rho](maths/pollard_rho.py)
* [Polynomial Evaluation](maths/polynomial_evaluation.py)
* [Power Using Recursion](maths/power_using_recursion.py)
* [Prime Check](maths/prime_check.py)
* [Prime Factors](maths/prime_factors.py)
* [Prime Numbers](maths/prime_numbers.py)
* [Prime Sieve Eratosthenes](maths/prime_sieve_eratosthenes.py)
* [Primelib](maths/primelib.py)
* [Proth Number](maths/proth_number.py)
* [Pythagoras](maths/pythagoras.py)
* [Qr Decomposition](maths/qr_decomposition.py)
* [Quadratic Equations Complex Numbers](maths/quadratic_equations_complex_numbers.py)
* [Radians](maths/radians.py)
* [Radix2 Fft](maths/radix2_fft.py)
* [Relu](maths/relu.py)
* [Runge Kutta](maths/runge_kutta.py)
* [Segmented Sieve](maths/segmented_sieve.py)
* Series
* [Arithmetic](maths/series/arithmetic.py)
* [Geometric](maths/series/geometric.py)
* [Geometric Series](maths/series/geometric_series.py)
* [Harmonic](maths/series/harmonic.py)
* [Harmonic Series](maths/series/harmonic_series.py)
* [Hexagonal Numbers](maths/series/hexagonal_numbers.py)
* [P Series](maths/series/p_series.py)
* [Sieve Of Eratosthenes](maths/sieve_of_eratosthenes.py)
* [Sigmoid](maths/sigmoid.py)
* [Simpson Rule](maths/simpson_rule.py)
* [Sin](maths/sin.py)
* [Sock Merchant](maths/sock_merchant.py)
* [Softmax](maths/softmax.py)
* [Square Root](maths/square_root.py)
* [Sum Of Arithmetic Series](maths/sum_of_arithmetic_series.py)
* [Sum Of Digits](maths/sum_of_digits.py)
* [Sum Of Geometric Progression](maths/sum_of_geometric_progression.py)
* [Sylvester Sequence](maths/sylvester_sequence.py)
* [Test Prime Check](maths/test_prime_check.py)
* [Trapezoidal Rule](maths/trapezoidal_rule.py)
* [Triplet Sum](maths/triplet_sum.py)
* [Two Pointer](maths/two_pointer.py)
* [Two Sum](maths/two_sum.py)
* [Ugly Numbers](maths/ugly_numbers.py)
* [Volume](maths/volume.py)
* [Zellers Congruence](maths/zellers_congruence.py)
## Matrix
* [Count Islands In Matrix](matrix/count_islands_in_matrix.py)
* [Inverse Of Matrix](matrix/inverse_of_matrix.py)
* [Matrix Class](matrix/matrix_class.py)
* [Matrix Operation](matrix/matrix_operation.py)
* [Nth Fibonacci Using Matrix Exponentiation](matrix/nth_fibonacci_using_matrix_exponentiation.py)
* [Rotate Matrix](matrix/rotate_matrix.py)
* [Searching In Sorted Matrix](matrix/searching_in_sorted_matrix.py)
* [Sherman Morrison](matrix/sherman_morrison.py)
* [Spiral Print](matrix/spiral_print.py)
* Tests
* [Test Matrix Operation](matrix/tests/test_matrix_operation.py)
## Networking Flow
* [Ford Fulkerson](networking_flow/ford_fulkerson.py)
* [Minimum Cut](networking_flow/minimum_cut.py)
## Neural Network
* [2 Hidden Layers Neural Network](neural_network/2_hidden_layers_neural_network.py)
* [Back Propagation Neural Network](neural_network/back_propagation_neural_network.py)
* [Convolution Neural Network](neural_network/convolution_neural_network.py)
* [Perceptron](neural_network/perceptron.py)
## Other
* [Activity Selection](other/activity_selection.py)
* [Alternative List Arrange](other/alternative_list_arrange.py)
* [Check Strong Password](other/check_strong_password.py)
* [Davisb Putnamb Logemannb Loveland](other/davisb_putnamb_logemannb_loveland.py)
* [Dijkstra Bankers Algorithm](other/dijkstra_bankers_algorithm.py)
* [Doomsday](other/doomsday.py)
* [Fischer Yates Shuffle](other/fischer_yates_shuffle.py)
* [Gauss Easter](other/gauss_easter.py)
* [Graham Scan](other/graham_scan.py)
* [Greedy](other/greedy.py)
* [Least Recently Used](other/least_recently_used.py)
* [Lfu Cache](other/lfu_cache.py)
* [Linear Congruential Generator](other/linear_congruential_generator.py)
* [Lru Cache](other/lru_cache.py)
* [Magicdiamondpattern](other/magicdiamondpattern.py)
* [Nested Brackets](other/nested_brackets.py)
* [Password Generator](other/password_generator.py)
* [Scoring Algorithm](other/scoring_algorithm.py)
* [Sdes](other/sdes.py)
* [Tower Of Hanoi](other/tower_of_hanoi.py)
## Physics
* [Horizontal Projectile Motion](physics/horizontal_projectile_motion.py)
* [Lorenz Transformation Four Vector](physics/lorenz_transformation_four_vector.py)
* [N Body Simulation](physics/n_body_simulation.py)
* [Newtons Second Law Of Motion](physics/newtons_second_law_of_motion.py)
## Project Euler
* Problem 001
* [Sol1](project_euler/problem_001/sol1.py)
* [Sol2](project_euler/problem_001/sol2.py)
* [Sol3](project_euler/problem_001/sol3.py)
* [Sol4](project_euler/problem_001/sol4.py)
* [Sol5](project_euler/problem_001/sol5.py)
* [Sol6](project_euler/problem_001/sol6.py)
* [Sol7](project_euler/problem_001/sol7.py)
* Problem 002
* [Sol1](project_euler/problem_002/sol1.py)
* [Sol2](project_euler/problem_002/sol2.py)
* [Sol3](project_euler/problem_002/sol3.py)
* [Sol4](project_euler/problem_002/sol4.py)
* [Sol5](project_euler/problem_002/sol5.py)
* Problem 003
* [Sol1](project_euler/problem_003/sol1.py)
* [Sol2](project_euler/problem_003/sol2.py)
* [Sol3](project_euler/problem_003/sol3.py)
* Problem 004
* [Sol1](project_euler/problem_004/sol1.py)
* [Sol2](project_euler/problem_004/sol2.py)
* Problem 005
* [Sol1](project_euler/problem_005/sol1.py)
* [Sol2](project_euler/problem_005/sol2.py)
* Problem 006
* [Sol1](project_euler/problem_006/sol1.py)
* [Sol2](project_euler/problem_006/sol2.py)
* [Sol3](project_euler/problem_006/sol3.py)
* [Sol4](project_euler/problem_006/sol4.py)
* Problem 007
* [Sol1](project_euler/problem_007/sol1.py)
* [Sol2](project_euler/problem_007/sol2.py)
* [Sol3](project_euler/problem_007/sol3.py)
* Problem 008
* [Sol1](project_euler/problem_008/sol1.py)
* [Sol2](project_euler/problem_008/sol2.py)
* [Sol3](project_euler/problem_008/sol3.py)
* Problem 009
* [Sol1](project_euler/problem_009/sol1.py)
* [Sol2](project_euler/problem_009/sol2.py)
* [Sol3](project_euler/problem_009/sol3.py)
* Problem 010
* [Sol1](project_euler/problem_010/sol1.py)
* [Sol2](project_euler/problem_010/sol2.py)
* [Sol3](project_euler/problem_010/sol3.py)
* Problem 011
* [Sol1](project_euler/problem_011/sol1.py)
* [Sol2](project_euler/problem_011/sol2.py)
* Problem 012
* [Sol1](project_euler/problem_012/sol1.py)
* [Sol2](project_euler/problem_012/sol2.py)
* Problem 013
* [Sol1](project_euler/problem_013/sol1.py)
* Problem 014
* [Sol1](project_euler/problem_014/sol1.py)
* [Sol2](project_euler/problem_014/sol2.py)
* Problem 015
* [Sol1](project_euler/problem_015/sol1.py)
* Problem 016
* [Sol1](project_euler/problem_016/sol1.py)
* [Sol2](project_euler/problem_016/sol2.py)
* Problem 017
* [Sol1](project_euler/problem_017/sol1.py)
* Problem 018
* [Solution](project_euler/problem_018/solution.py)
* Problem 019
* [Sol1](project_euler/problem_019/sol1.py)
* Problem 020
* [Sol1](project_euler/problem_020/sol1.py)
* [Sol2](project_euler/problem_020/sol2.py)
* [Sol3](project_euler/problem_020/sol3.py)
* [Sol4](project_euler/problem_020/sol4.py)
* Problem 021
* [Sol1](project_euler/problem_021/sol1.py)
* Problem 022
* [Sol1](project_euler/problem_022/sol1.py)
* [Sol2](project_euler/problem_022/sol2.py)
* Problem 023
* [Sol1](project_euler/problem_023/sol1.py)
* Problem 024
* [Sol1](project_euler/problem_024/sol1.py)
* Problem 025
* [Sol1](project_euler/problem_025/sol1.py)
* [Sol2](project_euler/problem_025/sol2.py)
* [Sol3](project_euler/problem_025/sol3.py)
* Problem 026
* [Sol1](project_euler/problem_026/sol1.py)
* Problem 027
* [Sol1](project_euler/problem_027/sol1.py)
* Problem 028
* [Sol1](project_euler/problem_028/sol1.py)
* Problem 029
* [Sol1](project_euler/problem_029/sol1.py)
* Problem 030
* [Sol1](project_euler/problem_030/sol1.py)
* Problem 031
* [Sol1](project_euler/problem_031/sol1.py)
* [Sol2](project_euler/problem_031/sol2.py)
* Problem 032
* [Sol32](project_euler/problem_032/sol32.py)
* Problem 033
* [Sol1](project_euler/problem_033/sol1.py)
* Problem 034
* [Sol1](project_euler/problem_034/sol1.py)
* Problem 035
* [Sol1](project_euler/problem_035/sol1.py)
* Problem 036
* [Sol1](project_euler/problem_036/sol1.py)
* Problem 037
* [Sol1](project_euler/problem_037/sol1.py)
* Problem 038
* [Sol1](project_euler/problem_038/sol1.py)
* Problem 039
* [Sol1](project_euler/problem_039/sol1.py)
* Problem 040
* [Sol1](project_euler/problem_040/sol1.py)
* Problem 041
* [Sol1](project_euler/problem_041/sol1.py)
* Problem 042
* [Solution42](project_euler/problem_042/solution42.py)
* Problem 043
* [Sol1](project_euler/problem_043/sol1.py)
* Problem 044
* [Sol1](project_euler/problem_044/sol1.py)
* Problem 045
* [Sol1](project_euler/problem_045/sol1.py)
* Problem 046
* [Sol1](project_euler/problem_046/sol1.py)
* Problem 047
* [Sol1](project_euler/problem_047/sol1.py)
* Problem 048
* [Sol1](project_euler/problem_048/sol1.py)
* Problem 049
* [Sol1](project_euler/problem_049/sol1.py)
* Problem 050
* [Sol1](project_euler/problem_050/sol1.py)
* Problem 051
* [Sol1](project_euler/problem_051/sol1.py)
* Problem 052
* [Sol1](project_euler/problem_052/sol1.py)
* Problem 053
* [Sol1](project_euler/problem_053/sol1.py)
* Problem 054
* [Sol1](project_euler/problem_054/sol1.py)
* [Test Poker Hand](project_euler/problem_054/test_poker_hand.py)
* Problem 055
* [Sol1](project_euler/problem_055/sol1.py)
* Problem 056
* [Sol1](project_euler/problem_056/sol1.py)
* Problem 057
* [Sol1](project_euler/problem_057/sol1.py)
* Problem 058
* [Sol1](project_euler/problem_058/sol1.py)
* Problem 059
* [Sol1](project_euler/problem_059/sol1.py)
* Problem 062
* [Sol1](project_euler/problem_062/sol1.py)
* Problem 063
* [Sol1](project_euler/problem_063/sol1.py)
* Problem 064
* [Sol1](project_euler/problem_064/sol1.py)
* Problem 065
* [Sol1](project_euler/problem_065/sol1.py)
* Problem 067
* [Sol1](project_euler/problem_067/sol1.py)
* [Sol2](project_euler/problem_067/sol2.py)
* Problem 068
* [Sol1](project_euler/problem_068/sol1.py)
* Problem 069
* [Sol1](project_euler/problem_069/sol1.py)
* Problem 070
* [Sol1](project_euler/problem_070/sol1.py)
* Problem 071
* [Sol1](project_euler/problem_071/sol1.py)
* Problem 072
* [Sol1](project_euler/problem_072/sol1.py)
* [Sol2](project_euler/problem_072/sol2.py)
* Problem 074
* [Sol1](project_euler/problem_074/sol1.py)
* [Sol2](project_euler/problem_074/sol2.py)
* Problem 075
* [Sol1](project_euler/problem_075/sol1.py)
* Problem 076
* [Sol1](project_euler/problem_076/sol1.py)
* Problem 077
* [Sol1](project_euler/problem_077/sol1.py)
* Problem 078
* [Sol1](project_euler/problem_078/sol1.py)
* Problem 080
* [Sol1](project_euler/problem_080/sol1.py)
* Problem 081
* [Sol1](project_euler/problem_081/sol1.py)
* Problem 085
* [Sol1](project_euler/problem_085/sol1.py)
* Problem 086
* [Sol1](project_euler/problem_086/sol1.py)
* Problem 087
* [Sol1](project_euler/problem_087/sol1.py)
* Problem 089
* [Sol1](project_euler/problem_089/sol1.py)
* Problem 091
* [Sol1](project_euler/problem_091/sol1.py)
* Problem 092
* [Sol1](project_euler/problem_092/sol1.py)
* Problem 097
* [Sol1](project_euler/problem_097/sol1.py)
* Problem 099
* [Sol1](project_euler/problem_099/sol1.py)
* Problem 101
* [Sol1](project_euler/problem_101/sol1.py)
* Problem 102
* [Sol1](project_euler/problem_102/sol1.py)
* Problem 104
* [Sol](project_euler/problem_104/sol.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 119
* [Sol1](project_euler/problem_119/sol1.py)
* Problem 120
* [Sol1](project_euler/problem_120/sol1.py)
* Problem 121
* [Sol1](project_euler/problem_121/sol1.py)
* Problem 123
* [Sol1](project_euler/problem_123/sol1.py)
* Problem 125
* [Sol1](project_euler/problem_125/sol1.py)
* Problem 129
* [Sol1](project_euler/problem_129/sol1.py)
* Problem 135
* [Sol1](project_euler/problem_135/sol1.py)
* Problem 144
* [Sol1](project_euler/problem_144/sol1.py)
* Problem 145
* [Sol1](project_euler/problem_145/sol1.py)
* Problem 173
* [Sol1](project_euler/problem_173/sol1.py)
* Problem 174
* [Sol1](project_euler/problem_174/sol1.py)
* Problem 180
* [Sol1](project_euler/problem_180/sol1.py)
* Problem 188
* [Sol1](project_euler/problem_188/sol1.py)
* Problem 191
* [Sol1](project_euler/problem_191/sol1.py)
* Problem 203
* [Sol1](project_euler/problem_203/sol1.py)
* Problem 205
* [Sol1](project_euler/problem_205/sol1.py)
* Problem 206
* [Sol1](project_euler/problem_206/sol1.py)
* Problem 207
* [Sol1](project_euler/problem_207/sol1.py)
* Problem 234
* [Sol1](project_euler/problem_234/sol1.py)
* Problem 301
* [Sol1](project_euler/problem_301/sol1.py)
* Problem 493
* [Sol1](project_euler/problem_493/sol1.py)
* Problem 551
* [Sol1](project_euler/problem_551/sol1.py)
* Problem 686
* [Sol1](project_euler/problem_686/sol1.py)
## Quantum
* [Deutsch Jozsa](quantum/deutsch_jozsa.py)
* [Half Adder](quantum/half_adder.py)
* [Not Gate](quantum/not_gate.py)
* [Quantum Entanglement](quantum/quantum_entanglement.py)
* [Ripple Adder Classic](quantum/ripple_adder_classic.py)
* [Single Qubit Measure](quantum/single_qubit_measure.py)
## Scheduling
* [First Come First Served](scheduling/first_come_first_served.py)
* [Highest Response Ratio Next](scheduling/highest_response_ratio_next.py)
* [Multi Level Feedback Queue](scheduling/multi_level_feedback_queue.py)
* [Non Preemptive Shortest Job First](scheduling/non_preemptive_shortest_job_first.py)
* [Round Robin](scheduling/round_robin.py)
* [Shortest Job First](scheduling/shortest_job_first.py)
## Searches
* [Binary Search](searches/binary_search.py)
* [Binary Tree Traversal](searches/binary_tree_traversal.py)
* [Double Linear Search](searches/double_linear_search.py)
* [Double Linear Search Recursion](searches/double_linear_search_recursion.py)
* [Fibonacci Search](searches/fibonacci_search.py)
* [Hill Climbing](searches/hill_climbing.py)
* [Interpolation Search](searches/interpolation_search.py)
* [Jump Search](searches/jump_search.py)
* [Linear Search](searches/linear_search.py)
* [Quick Select](searches/quick_select.py)
* [Sentinel Linear Search](searches/sentinel_linear_search.py)
* [Simple Binary Search](searches/simple_binary_search.py)
* [Simulated Annealing](searches/simulated_annealing.py)
* [Tabu Search](searches/tabu_search.py)
* [Ternary Search](searches/ternary_search.py)
## Sorts
* [Bead Sort](sorts/bead_sort.py)
* [Bitonic Sort](sorts/bitonic_sort.py)
* [Bogo Sort](sorts/bogo_sort.py)
* [Bubble Sort](sorts/bubble_sort.py)
* [Bucket Sort](sorts/bucket_sort.py)
* [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)
* [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)
* [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)
* [Check Pangram](strings/check_pangram.py)
* [Credit Card Validator](strings/credit_card_validator.py)
* [Detecting English Programmatically](strings/detecting_english_programmatically.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 Palindrome](strings/is_palindrome.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)
* [Split](strings/split.py)
* [Upper](strings/upper.py)
* [Wave](strings/wave.py)
* [Wildcard Pattern Matching](strings/wildcard_pattern_matching.py)
* [Word Occurrence](strings/word_occurrence.py)
* [Word Patterns](strings/word_patterns.py)
* [Z Function](strings/z_function.py)
## Web Programming
* [Co2 Emission](web_programming/co2_emission.py)
* [Covid Stats Via Xpath](web_programming/covid_stats_via_xpath.py)
* [Crawl Google Results](web_programming/crawl_google_results.py)
* [Crawl Google Scholar Citation](web_programming/crawl_google_scholar_citation.py)
* [Currency Converter](web_programming/currency_converter.py)
* [Current Stock Price](web_programming/current_stock_price.py)
* [Current Weather](web_programming/current_weather.py)
* [Daily Horoscope](web_programming/daily_horoscope.py)
* [Download Images From Google Query](web_programming/download_images_from_google_query.py)
* [Emails From Url](web_programming/emails_from_url.py)
* [Fetch Anime And Play](web_programming/fetch_anime_and_play.py)
* [Fetch Bbc News](web_programming/fetch_bbc_news.py)
* [Fetch Github Info](web_programming/fetch_github_info.py)
* [Fetch Jobs](web_programming/fetch_jobs.py)
* [Fetch Well Rx Price](web_programming/fetch_well_rx_price.py)
* [Get Imdb Top 250 Movies Csv](web_programming/get_imdb_top_250_movies_csv.py)
* [Get Imdbtop](web_programming/get_imdbtop.py)
* [Get Top 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)
* [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 | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/env python3
from .hash_table import HashTable
from .number_theory.prime_numbers import check_prime, next_prime
class DoubleHash(HashTable):
"""
Hash Table example with open addressing and Double Hash
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __hash_function_2(self, value, data):
next_prime_gt = (
next_prime(value % self.size_table)
if not check_prime(value % self.size_table)
else value % self.size_table
) # gt = bigger than
return next_prime_gt - (data % next_prime_gt)
def __hash_double_function(self, key, data, increment):
return (increment * self.__hash_function_2(key, data)) % self.size_table
def _collision_resolution(self, key, data=None):
i = 1
new_key = self.hash_function(data)
while self.values[new_key] is not None and self.values[new_key] != key:
new_key = (
self.__hash_double_function(key, data, i)
if self.balanced_factor() >= self.lim_charge
else None
)
if new_key is None:
break
else:
i += 1
return new_key
| #!/usr/bin/env python3
from .hash_table import HashTable
from .number_theory.prime_numbers import is_prime, next_prime
class DoubleHash(HashTable):
"""
Hash Table example with open addressing and Double Hash
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __hash_function_2(self, value, data):
next_prime_gt = (
next_prime(value % self.size_table)
if not is_prime(value % self.size_table)
else value % self.size_table
) # gt = bigger than
return next_prime_gt - (data % next_prime_gt)
def __hash_double_function(self, key, data, increment):
return (increment * self.__hash_function_2(key, data)) % self.size_table
def _collision_resolution(self, key, data=None):
i = 1
new_key = self.hash_function(data)
while self.values[new_key] is not None and self.values[new_key] != key:
new_key = (
self.__hash_double_function(key, data, i)
if self.balanced_factor() >= self.lim_charge
else None
)
if new_key is None:
break
else:
i += 1
return new_key
| 1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/env python3
"""
module to operations with prime numbers
"""
def check_prime(number):
"""
it's not the best solution
"""
special_non_primes = [0, 1, 2]
if number in special_non_primes[:2]:
return 2
elif number == special_non_primes[-1]:
return 3
return all(number % i for i in range(2, number))
def next_prime(value, factor=1, **kwargs):
value = factor * value
first_value_val = value
while not check_prime(value):
value += 1 if not ("desc" in kwargs.keys() and kwargs["desc"] is True) else -1
if value == first_value_val:
return next_prime(value + 1, **kwargs)
return value
| #!/usr/bin/env python3
"""
module to operations with prime numbers
"""
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
"""
# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or not number % 2:
# Negatives, 0, 1 and all even numbers are not primes
return False
odd_numbers = range(3, int(math.sqrt(number) + 1), 2)
return not any(not number % i for i in odd_numbers)
def next_prime(value, factor=1, **kwargs):
value = factor * value
first_value_val = value
while not is_prime(value):
value += 1 if not ("desc" in kwargs.keys() and kwargs["desc"] is True) else -1
if value == first_value_val:
return next_prime(value + 1, **kwargs)
return value
| 1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """Prime Check."""
import math
import unittest
def prime_check(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.
>>> prime_check(0)
False
>>> prime_check(1)
False
>>> prime_check(2)
True
>>> prime_check(3)
True
>>> prime_check(27)
False
>>> prime_check(87)
False
>>> prime_check(563)
True
>>> prime_check(2999)
True
>>> prime_check(67483)
False
"""
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or not number % 2:
# Negatives, 0, 1 and all even numbers are not primes
return False
odd_numbers = range(3, int(math.sqrt(number) + 1), 2)
return not any(not number % i for i in odd_numbers)
class Test(unittest.TestCase):
def test_primes(self):
self.assertTrue(prime_check(2))
self.assertTrue(prime_check(3))
self.assertTrue(prime_check(5))
self.assertTrue(prime_check(7))
self.assertTrue(prime_check(11))
self.assertTrue(prime_check(13))
self.assertTrue(prime_check(17))
self.assertTrue(prime_check(19))
self.assertTrue(prime_check(23))
self.assertTrue(prime_check(29))
def test_not_primes(self):
self.assertFalse(
prime_check(-19),
"Negative numbers are excluded by definition of prime numbers.",
)
self.assertFalse(
prime_check(0),
"Zero doesn't have any positive factors, primes must have exactly two.",
)
self.assertFalse(
prime_check(1),
"One only has 1 positive factor, primes must have exactly two.",
)
self.assertFalse(prime_check(2 * 2))
self.assertFalse(prime_check(2 * 3))
self.assertFalse(prime_check(3 * 3))
self.assertFalse(prime_check(3 * 5))
self.assertFalse(prime_check(3 * 5 * 7))
if __name__ == "__main__":
unittest.main()
| """Prime Check."""
import math
import unittest
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
"""
# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or not number % 2:
# Negatives, 0, 1 and all even numbers are not primes
return False
odd_numbers = range(3, int(math.sqrt(number) + 1), 2)
return not any(not number % i for i in odd_numbers)
class Test(unittest.TestCase):
def test_primes(self):
self.assertTrue(is_prime(2))
self.assertTrue(is_prime(3))
self.assertTrue(is_prime(5))
self.assertTrue(is_prime(7))
self.assertTrue(is_prime(11))
self.assertTrue(is_prime(13))
self.assertTrue(is_prime(17))
self.assertTrue(is_prime(19))
self.assertTrue(is_prime(23))
self.assertTrue(is_prime(29))
def test_not_primes(self):
self.assertFalse(
is_prime(-19),
"Negative numbers are excluded by definition of prime numbers.",
)
self.assertFalse(
is_prime(0),
"Zero doesn't have any positive factors, primes must have exactly two.",
)
self.assertFalse(
is_prime(1),
"One only has 1 positive factor, primes must have exactly two.",
)
self.assertFalse(is_prime(2 * 2))
self.assertFalse(is_prime(2 * 3))
self.assertFalse(is_prime(3 * 3))
self.assertFalse(is_prime(3 * 5))
self.assertFalse(is_prime(3 * 5 * 7))
if __name__ == "__main__":
unittest.main()
| 1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Created on Thu Oct 5 16:44:23 2017
@author: Christian Bender
This Python library contains some useful functions to deal with
prime numbers and whole numbers.
Overview:
isPrime(number)
sieveEr(N)
getPrimeNumbers(N)
primeFactorization(number)
greatestPrimeFactor(number)
smallestPrimeFactor(number)
getPrime(n)
getPrimesBetween(pNumber1, pNumber2)
----
isEven(number)
isOdd(number)
gcd(number1, number2) // greatest common divisor
kgV(number1, number2) // least common multiple
getDivisors(number) // all divisors of 'number' inclusive 1, number
isPerfectNumber(number)
NEW-FUNCTIONS
simplifyFraction(numerator, denominator)
factorial (n) // n!
fib (n) // calculate the n-th fibonacci term.
-----
goldbach(number) // Goldbach's assumption
"""
from math import sqrt
def isPrime(number):
"""
input: positive integer 'number'
returns true if 'number' is prime otherwise false.
"""
# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
status = True
# 0 and 1 are none primes.
if number <= 1:
status = False
for divisor in range(2, int(round(sqrt(number))) + 1):
# if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop.
if number % divisor == 0:
status = False
break
# precondition
assert isinstance(status, bool), "'status' must been from type bool"
return status
# ------------------------------------------
def sieveEr(N):
"""
input: positive integer 'N' > 2
returns a list of prime numbers from 2 up to N.
This function implements the algorithm called
sieve of erathostenes.
"""
# precondition
assert isinstance(N, int) and (N > 2), "'N' must been an int and > 2"
# beginList: contains all natural numbers from 2 up to N
beginList = [x for x in range(2, N + 1)]
ans = [] # this list will be returns.
# actual sieve of erathostenes
for i in range(len(beginList)):
for j in range(i + 1, len(beginList)):
if (beginList[i] != 0) and (beginList[j] % beginList[i] == 0):
beginList[j] = 0
# filters actual prime numbers.
ans = [x for x in beginList if x != 0]
# precondition
assert isinstance(ans, list), "'ans' must been from type list"
return ans
# --------------------------------
def getPrimeNumbers(N):
"""
input: positive integer 'N' > 2
returns a list of prime numbers from 2 up to N (inclusive)
This function is more efficient as function 'sieveEr(...)'
"""
# precondition
assert isinstance(N, int) and (N > 2), "'N' must been an int and > 2"
ans = []
# iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans'
for number in range(2, N + 1):
if isPrime(number):
ans.append(number)
# precondition
assert isinstance(ans, list), "'ans' must been from type list"
return ans
# -----------------------------------------
def primeFactorization(number):
"""
input: positive integer 'number'
returns a list of the prime number factors of 'number'
"""
# precondition
assert isinstance(number, int) and number >= 0, "'number' must been an int and >= 0"
ans = [] # this list will be returns of the function.
# potential prime number factors.
factor = 2
quotient = number
if number == 0 or number == 1:
ans.append(number)
# if 'number' not prime then builds the prime factorization of 'number'
elif not isPrime(number):
while quotient != 1:
if isPrime(factor) and (quotient % factor == 0):
ans.append(factor)
quotient /= factor
else:
factor += 1
else:
ans.append(number)
# precondition
assert isinstance(ans, list), "'ans' must been from type list"
return ans
# -----------------------------------------
def greatestPrimeFactor(number):
"""
input: positive integer 'number' >= 0
returns the greatest prime number factor of 'number'
"""
# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' bust been an int and >= 0"
ans = 0
# prime factorization of 'number'
primeFactors = primeFactorization(number)
ans = max(primeFactors)
# precondition
assert isinstance(ans, int), "'ans' must been from type int"
return ans
# ----------------------------------------------
def smallestPrimeFactor(number):
"""
input: integer 'number' >= 0
returns the smallest prime number factor of 'number'
"""
# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' bust been an int and >= 0"
ans = 0
# prime factorization of 'number'
primeFactors = primeFactorization(number)
ans = min(primeFactors)
# precondition
assert isinstance(ans, int), "'ans' must been from type int"
return ans
# ----------------------
def isEven(number):
"""
input: integer 'number'
returns true if 'number' is even, otherwise false.
"""
# precondition
assert isinstance(number, int), "'number' must been an int"
assert isinstance(number % 2 == 0, bool), "compare bust been from type bool"
return number % 2 == 0
# ------------------------
def isOdd(number):
"""
input: integer 'number'
returns true if 'number' is odd, otherwise false.
"""
# precondition
assert isinstance(number, int), "'number' must been an int"
assert isinstance(number % 2 != 0, bool), "compare bust been from type bool"
return number % 2 != 0
# ------------------------
def goldbach(number):
"""
Goldbach's assumption
input: a even positive integer 'number' > 2
returns a list of two prime numbers whose sum is equal to 'number'
"""
# precondition
assert (
isinstance(number, int) and (number > 2) and isEven(number)
), "'number' must been an int, even and > 2"
ans = [] # this list will returned
# creates a list of prime numbers between 2 up to 'number'
primeNumbers = getPrimeNumbers(number)
lenPN = len(primeNumbers)
# run variable for while-loops.
i = 0
j = None
# exit variable. for break up the loops
loop = True
while i < lenPN and loop:
j = i + 1
while j < lenPN and loop:
if primeNumbers[i] + primeNumbers[j] == number:
loop = False
ans.append(primeNumbers[i])
ans.append(primeNumbers[j])
j += 1
i += 1
# precondition
assert (
isinstance(ans, list)
and (len(ans) == 2)
and (ans[0] + ans[1] == number)
and isPrime(ans[0])
and isPrime(ans[1])
), "'ans' must contains two primes. And sum of elements must been eq 'number'"
return ans
# ----------------------------------------------
def gcd(number1, number2):
"""
Greatest common divisor
input: two positive integer 'number1' and 'number2'
returns the greatest common divisor of 'number1' and 'number2'
"""
# precondition
assert (
isinstance(number1, int)
and isinstance(number2, int)
and (number1 >= 0)
and (number2 >= 0)
), "'number1' and 'number2' must been positive integer."
rest = 0
while number2 != 0:
rest = number1 % number2
number1 = number2
number2 = rest
# precondition
assert isinstance(number1, int) and (
number1 >= 0
), "'number' must been from type int and positive"
return number1
# ----------------------------------------------------
def kgV(number1, number2):
"""
Least common multiple
input: two positive integer 'number1' and 'number2'
returns the least common multiple of 'number1' and 'number2'
"""
# precondition
assert (
isinstance(number1, int)
and isinstance(number2, int)
and (number1 >= 1)
and (number2 >= 1)
), "'number1' and 'number2' must been positive integer."
ans = 1 # actual answer that will be return.
# for kgV (x,1)
if number1 > 1 and number2 > 1:
# builds the prime factorization of 'number1' and 'number2'
primeFac1 = primeFactorization(number1)
primeFac2 = primeFactorization(number2)
elif number1 == 1 or number2 == 1:
primeFac1 = []
primeFac2 = []
ans = max(number1, number2)
count1 = 0
count2 = 0
done = [] # captured numbers int both 'primeFac1' and 'primeFac2'
# iterates through primeFac1
for n in primeFac1:
if n not in done:
if n in primeFac2:
count1 = primeFac1.count(n)
count2 = primeFac2.count(n)
for i in range(max(count1, count2)):
ans *= n
else:
count1 = primeFac1.count(n)
for i in range(count1):
ans *= n
done.append(n)
# iterates through primeFac2
for n in primeFac2:
if n not in done:
count2 = primeFac2.count(n)
for i in range(count2):
ans *= n
done.append(n)
# precondition
assert isinstance(ans, int) and (
ans >= 0
), "'ans' must been from type int and positive"
return ans
# ----------------------------------
def getPrime(n):
"""
Gets the n-th prime number.
input: positive integer 'n' >= 0
returns the n-th prime number, beginning at index 0
"""
# precondition
assert isinstance(n, int) and (n >= 0), "'number' must been a positive int"
index = 0
ans = 2 # this variable holds the answer
while index < n:
index += 1
ans += 1 # counts to the next number
# if ans not prime then
# runs to the next prime number.
while not isPrime(ans):
ans += 1
# precondition
assert isinstance(ans, int) and isPrime(
ans
), "'ans' must been a prime number and from type int"
return ans
# ---------------------------------------------------
def getPrimesBetween(pNumber1, pNumber2):
"""
input: prime numbers 'pNumber1' and 'pNumber2'
pNumber1 < pNumber2
returns a list of all prime numbers between 'pNumber1' (exclusive)
and 'pNumber2' (exclusive)
"""
# precondition
assert (
isPrime(pNumber1) and isPrime(pNumber2) and (pNumber1 < pNumber2)
), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"
number = pNumber1 + 1 # jump to the next number
ans = [] # this list will be returns.
# if number is not prime then
# fetch the next prime number.
while not isPrime(number):
number += 1
while number < pNumber2:
ans.append(number)
number += 1
# fetch the next prime number.
while not isPrime(number):
number += 1
# precondition
assert (
isinstance(ans, list) and ans[0] != pNumber1 and ans[len(ans) - 1] != pNumber2
), "'ans' must been a list without the arguments"
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
# ----------------------------------------------------
def getDivisors(n):
"""
input: positive integer 'n' >= 1
returns all divisors of n (inclusive 1 and 'n')
"""
# precondition
assert isinstance(n, int) and (n >= 1), "'n' must been int and >= 1"
ans = [] # will be returned.
for divisor in range(1, n + 1):
if n % divisor == 0:
ans.append(divisor)
# precondition
assert ans[0] == 1 and ans[len(ans) - 1] == n, "Error in function getDivisiors(...)"
return ans
# ----------------------------------------------------
def isPerfectNumber(number):
"""
input: positive integer 'number' > 1
returns true if 'number' is a perfect number otherwise false.
"""
# precondition
assert isinstance(number, int) and (
number > 1
), "'number' must been an int and >= 1"
divisors = getDivisors(number)
# precondition
assert (
isinstance(divisors, list)
and (divisors[0] == 1)
and (divisors[len(divisors) - 1] == number)
), "Error in help-function getDivisiors(...)"
# summed all divisors up to 'number' (exclusive), hence [:-1]
return sum(divisors[:-1]) == number
# ------------------------------------------------------------
def simplifyFraction(numerator, denominator):
"""
input: two integer 'numerator' and 'denominator'
assumes: 'denominator' != 0
returns: a tuple with simplify numerator and denominator.
"""
# precondition
assert (
isinstance(numerator, int)
and isinstance(denominator, int)
and (denominator != 0)
), "The arguments must been from type int and 'denominator' != 0"
# build the greatest common divisor of numerator and denominator.
gcdOfFraction = gcd(abs(numerator), abs(denominator))
# precondition
assert (
isinstance(gcdOfFraction, int)
and (numerator % gcdOfFraction == 0)
and (denominator % gcdOfFraction == 0)
), "Error in function gcd(...,...)"
return (numerator // gcdOfFraction, denominator // gcdOfFraction)
# -----------------------------------------------------------------
def factorial(n):
"""
input: positive integer 'n'
returns the factorial of 'n' (n!)
"""
# precondition
assert isinstance(n, int) and (n >= 0), "'n' must been a int and >= 0"
ans = 1 # this will be return.
for factor in range(1, n + 1):
ans *= factor
return ans
# -------------------------------------------------------------------
def fib(n):
"""
input: positive integer 'n'
returns the n-th fibonacci term , indexing by 0
"""
# precondition
assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0"
tmp = 0
fib1 = 1
ans = 1 # this will be return
for i in range(n - 1):
tmp = ans
ans += fib1
fib1 = tmp
return ans
| """
Created on Thu Oct 5 16:44:23 2017
@author: Christian Bender
This Python library contains some useful functions to deal with
prime numbers and whole numbers.
Overview:
isPrime(number)
sieveEr(N)
getPrimeNumbers(N)
primeFactorization(number)
greatestPrimeFactor(number)
smallestPrimeFactor(number)
getPrime(n)
getPrimesBetween(pNumber1, pNumber2)
----
isEven(number)
isOdd(number)
gcd(number1, number2) // greatest common divisor
kgV(number1, number2) // least common multiple
getDivisors(number) // all divisors of 'number' inclusive 1, number
isPerfectNumber(number)
NEW-FUNCTIONS
simplifyFraction(numerator, denominator)
factorial (n) // n!
fib (n) // calculate the n-th fibonacci term.
-----
goldbach(number) // Goldbach's assumption
"""
from math import sqrt
def is_prime(number: int) -> bool:
"""
input: positive integer 'number'
returns true if 'number' is prime otherwise false.
"""
# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' must been an int and positive"
status = True
# 0 and 1 are none primes.
if number <= 1:
status = False
for divisor in range(2, int(round(sqrt(number))) + 1):
# if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop.
if number % divisor == 0:
status = False
break
# precondition
assert isinstance(status, bool), "'status' must been from type bool"
return status
# ------------------------------------------
def sieveEr(N):
"""
input: positive integer 'N' > 2
returns a list of prime numbers from 2 up to N.
This function implements the algorithm called
sieve of erathostenes.
"""
# precondition
assert isinstance(N, int) and (N > 2), "'N' must been an int and > 2"
# beginList: contains all natural numbers from 2 up to N
beginList = [x for x in range(2, N + 1)]
ans = [] # this list will be returns.
# actual sieve of erathostenes
for i in range(len(beginList)):
for j in range(i + 1, len(beginList)):
if (beginList[i] != 0) and (beginList[j] % beginList[i] == 0):
beginList[j] = 0
# filters actual prime numbers.
ans = [x for x in beginList if x != 0]
# precondition
assert isinstance(ans, list), "'ans' must been from type list"
return ans
# --------------------------------
def getPrimeNumbers(N):
"""
input: positive integer 'N' > 2
returns a list of prime numbers from 2 up to N (inclusive)
This function is more efficient as function 'sieveEr(...)'
"""
# precondition
assert isinstance(N, int) and (N > 2), "'N' must been an int and > 2"
ans = []
# iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans'
for number in range(2, N + 1):
if is_prime(number):
ans.append(number)
# precondition
assert isinstance(ans, list), "'ans' must been from type list"
return ans
# -----------------------------------------
def primeFactorization(number):
"""
input: positive integer 'number'
returns a list of the prime number factors of 'number'
"""
# precondition
assert isinstance(number, int) and number >= 0, "'number' must been an int and >= 0"
ans = [] # this list will be returns of the function.
# potential prime number factors.
factor = 2
quotient = number
if number == 0 or number == 1:
ans.append(number)
# if 'number' not prime then builds the prime factorization of 'number'
elif not is_prime(number):
while quotient != 1:
if is_prime(factor) and (quotient % factor == 0):
ans.append(factor)
quotient /= factor
else:
factor += 1
else:
ans.append(number)
# precondition
assert isinstance(ans, list), "'ans' must been from type list"
return ans
# -----------------------------------------
def greatestPrimeFactor(number):
"""
input: positive integer 'number' >= 0
returns the greatest prime number factor of 'number'
"""
# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' bust been an int and >= 0"
ans = 0
# prime factorization of 'number'
primeFactors = primeFactorization(number)
ans = max(primeFactors)
# precondition
assert isinstance(ans, int), "'ans' must been from type int"
return ans
# ----------------------------------------------
def smallestPrimeFactor(number):
"""
input: integer 'number' >= 0
returns the smallest prime number factor of 'number'
"""
# precondition
assert isinstance(number, int) and (
number >= 0
), "'number' bust been an int and >= 0"
ans = 0
# prime factorization of 'number'
primeFactors = primeFactorization(number)
ans = min(primeFactors)
# precondition
assert isinstance(ans, int), "'ans' must been from type int"
return ans
# ----------------------
def isEven(number):
"""
input: integer 'number'
returns true if 'number' is even, otherwise false.
"""
# precondition
assert isinstance(number, int), "'number' must been an int"
assert isinstance(number % 2 == 0, bool), "compare bust been from type bool"
return number % 2 == 0
# ------------------------
def isOdd(number):
"""
input: integer 'number'
returns true if 'number' is odd, otherwise false.
"""
# precondition
assert isinstance(number, int), "'number' must been an int"
assert isinstance(number % 2 != 0, bool), "compare bust been from type bool"
return number % 2 != 0
# ------------------------
def goldbach(number):
"""
Goldbach's assumption
input: a even positive integer 'number' > 2
returns a list of two prime numbers whose sum is equal to 'number'
"""
# precondition
assert (
isinstance(number, int) and (number > 2) and isEven(number)
), "'number' must been an int, even and > 2"
ans = [] # this list will returned
# creates a list of prime numbers between 2 up to 'number'
primeNumbers = getPrimeNumbers(number)
lenPN = len(primeNumbers)
# run variable for while-loops.
i = 0
j = None
# exit variable. for break up the loops
loop = True
while i < lenPN and loop:
j = i + 1
while j < lenPN and loop:
if primeNumbers[i] + primeNumbers[j] == number:
loop = False
ans.append(primeNumbers[i])
ans.append(primeNumbers[j])
j += 1
i += 1
# precondition
assert (
isinstance(ans, list)
and (len(ans) == 2)
and (ans[0] + ans[1] == number)
and is_prime(ans[0])
and is_prime(ans[1])
), "'ans' must contains two primes. And sum of elements must been eq 'number'"
return ans
# ----------------------------------------------
def gcd(number1, number2):
"""
Greatest common divisor
input: two positive integer 'number1' and 'number2'
returns the greatest common divisor of 'number1' and 'number2'
"""
# precondition
assert (
isinstance(number1, int)
and isinstance(number2, int)
and (number1 >= 0)
and (number2 >= 0)
), "'number1' and 'number2' must been positive integer."
rest = 0
while number2 != 0:
rest = number1 % number2
number1 = number2
number2 = rest
# precondition
assert isinstance(number1, int) and (
number1 >= 0
), "'number' must been from type int and positive"
return number1
# ----------------------------------------------------
def kgV(number1, number2):
"""
Least common multiple
input: two positive integer 'number1' and 'number2'
returns the least common multiple of 'number1' and 'number2'
"""
# precondition
assert (
isinstance(number1, int)
and isinstance(number2, int)
and (number1 >= 1)
and (number2 >= 1)
), "'number1' and 'number2' must been positive integer."
ans = 1 # actual answer that will be return.
# for kgV (x,1)
if number1 > 1 and number2 > 1:
# builds the prime factorization of 'number1' and 'number2'
primeFac1 = primeFactorization(number1)
primeFac2 = primeFactorization(number2)
elif number1 == 1 or number2 == 1:
primeFac1 = []
primeFac2 = []
ans = max(number1, number2)
count1 = 0
count2 = 0
done = [] # captured numbers int both 'primeFac1' and 'primeFac2'
# iterates through primeFac1
for n in primeFac1:
if n not in done:
if n in primeFac2:
count1 = primeFac1.count(n)
count2 = primeFac2.count(n)
for i in range(max(count1, count2)):
ans *= n
else:
count1 = primeFac1.count(n)
for i in range(count1):
ans *= n
done.append(n)
# iterates through primeFac2
for n in primeFac2:
if n not in done:
count2 = primeFac2.count(n)
for i in range(count2):
ans *= n
done.append(n)
# precondition
assert isinstance(ans, int) and (
ans >= 0
), "'ans' must been from type int and positive"
return ans
# ----------------------------------
def getPrime(n):
"""
Gets the n-th prime number.
input: positive integer 'n' >= 0
returns the n-th prime number, beginning at index 0
"""
# precondition
assert isinstance(n, int) and (n >= 0), "'number' must been a positive int"
index = 0
ans = 2 # this variable holds the answer
while index < n:
index += 1
ans += 1 # counts to the next number
# if ans not prime then
# runs to the next prime number.
while not is_prime(ans):
ans += 1
# precondition
assert isinstance(ans, int) and is_prime(
ans
), "'ans' must been a prime number and from type int"
return ans
# ---------------------------------------------------
def getPrimesBetween(pNumber1, pNumber2):
"""
input: prime numbers 'pNumber1' and 'pNumber2'
pNumber1 < pNumber2
returns a list of all prime numbers between 'pNumber1' (exclusive)
and 'pNumber2' (exclusive)
"""
# precondition
assert (
is_prime(pNumber1) and is_prime(pNumber2) and (pNumber1 < pNumber2)
), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"
number = pNumber1 + 1 # jump to the next number
ans = [] # this list will be returns.
# if number is not prime then
# fetch the next prime number.
while not is_prime(number):
number += 1
while number < pNumber2:
ans.append(number)
number += 1
# fetch the next prime number.
while not is_prime(number):
number += 1
# precondition
assert (
isinstance(ans, list) and ans[0] != pNumber1 and ans[len(ans) - 1] != pNumber2
), "'ans' must been a list without the arguments"
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
# ----------------------------------------------------
def getDivisors(n):
"""
input: positive integer 'n' >= 1
returns all divisors of n (inclusive 1 and 'n')
"""
# precondition
assert isinstance(n, int) and (n >= 1), "'n' must been int and >= 1"
ans = [] # will be returned.
for divisor in range(1, n + 1):
if n % divisor == 0:
ans.append(divisor)
# precondition
assert ans[0] == 1 and ans[len(ans) - 1] == n, "Error in function getDivisiors(...)"
return ans
# ----------------------------------------------------
def isPerfectNumber(number):
"""
input: positive integer 'number' > 1
returns true if 'number' is a perfect number otherwise false.
"""
# precondition
assert isinstance(number, int) and (
number > 1
), "'number' must been an int and >= 1"
divisors = getDivisors(number)
# precondition
assert (
isinstance(divisors, list)
and (divisors[0] == 1)
and (divisors[len(divisors) - 1] == number)
), "Error in help-function getDivisiors(...)"
# summed all divisors up to 'number' (exclusive), hence [:-1]
return sum(divisors[:-1]) == number
# ------------------------------------------------------------
def simplifyFraction(numerator, denominator):
"""
input: two integer 'numerator' and 'denominator'
assumes: 'denominator' != 0
returns: a tuple with simplify numerator and denominator.
"""
# precondition
assert (
isinstance(numerator, int)
and isinstance(denominator, int)
and (denominator != 0)
), "The arguments must been from type int and 'denominator' != 0"
# build the greatest common divisor of numerator and denominator.
gcdOfFraction = gcd(abs(numerator), abs(denominator))
# precondition
assert (
isinstance(gcdOfFraction, int)
and (numerator % gcdOfFraction == 0)
and (denominator % gcdOfFraction == 0)
), "Error in function gcd(...,...)"
return (numerator // gcdOfFraction, denominator // gcdOfFraction)
# -----------------------------------------------------------------
def factorial(n):
"""
input: positive integer 'n'
returns the factorial of 'n' (n!)
"""
# precondition
assert isinstance(n, int) and (n >= 0), "'n' must been a int and >= 0"
ans = 1 # this will be return.
for factor in range(1, n + 1):
ans *= factor
return ans
# -------------------------------------------------------------------
def fib(n):
"""
input: positive integer 'n'
returns the n-th fibonacci term , indexing by 0
"""
# precondition
assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0"
tmp = 0
fib1 = 1
ans = 1 # this will be return
for i in range(n - 1):
tmp = ans
ans += fib1
fib1 = tmp
return ans
| 1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
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 | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/python
"""
A Framework of Back Propagation Neural Network(BP) model
Easy to use:
* add many layers as you want !!!
* clearly see how the loss decreasing
Easy to expand:
* more activation functions
* more loss functions
* more optimization method
Author: Stephen Lee
Github : https://github.com/RiptideBo
Date: 2017.11.23
"""
import numpy as np
from matplotlib import pyplot as plt
def sigmoid(x):
return 1 / (1 + np.exp(-1 * x))
class DenseLayer:
"""
Layers of BP neural network
"""
def __init__(
self, units, activation=None, learning_rate=None, is_input_layer=False
):
"""
common connected layer of bp network
:param units: numbers of neural units
:param activation: activation function
:param learning_rate: learning rate for paras
:param is_input_layer: whether it is input layer or not
"""
self.units = units
self.weight = None
self.bias = None
self.activation = activation
if learning_rate is None:
learning_rate = 0.3
self.learn_rate = learning_rate
self.is_input_layer = is_input_layer
def initializer(self, back_units):
self.weight = np.asmatrix(np.random.normal(0, 0.5, (self.units, back_units)))
self.bias = np.asmatrix(np.random.normal(0, 0.5, self.units)).T
if self.activation is None:
self.activation = sigmoid
def cal_gradient(self):
# activation function may be sigmoid or linear
if self.activation == sigmoid:
gradient_mat = np.dot(self.output, (1 - self.output).T)
gradient_activation = np.diag(np.diag(gradient_mat))
else:
gradient_activation = 1
return gradient_activation
def forward_propagation(self, xdata):
self.xdata = xdata
if self.is_input_layer:
# input layer
self.wx_plus_b = xdata
self.output = xdata
return xdata
else:
self.wx_plus_b = np.dot(self.weight, self.xdata) - self.bias
self.output = self.activation(self.wx_plus_b)
return self.output
def back_propagation(self, gradient):
gradient_activation = self.cal_gradient() # i * i 维
gradient = np.asmatrix(np.dot(gradient.T, gradient_activation))
self._gradient_weight = np.asmatrix(self.xdata)
self._gradient_bias = -1
self._gradient_x = self.weight
self.gradient_weight = np.dot(gradient.T, self._gradient_weight.T)
self.gradient_bias = gradient * self._gradient_bias
self.gradient = np.dot(gradient, self._gradient_x).T
# upgrade: the Negative gradient direction
self.weight = self.weight - self.learn_rate * self.gradient_weight
self.bias = self.bias - self.learn_rate * self.gradient_bias.T
# updates the weights and bias according to learning rate (0.3 if undefined)
return self.gradient
class BPNN:
"""
Back Propagation Neural Network model
"""
def __init__(self):
self.layers = []
self.train_mse = []
self.fig_loss = plt.figure()
self.ax_loss = self.fig_loss.add_subplot(1, 1, 1)
def add_layer(self, layer):
self.layers.append(layer)
def build(self):
for i, layer in enumerate(self.layers[:]):
if i < 1:
layer.is_input_layer = True
else:
layer.initializer(self.layers[i - 1].units)
def summary(self):
for i, layer in enumerate(self.layers[:]):
print("------- layer %d -------" % i)
print("weight.shape ", np.shape(layer.weight))
print("bias.shape ", np.shape(layer.bias))
def train(self, xdata, ydata, train_round, accuracy):
self.train_round = train_round
self.accuracy = accuracy
self.ax_loss.hlines(self.accuracy, 0, self.train_round * 1.1)
x_shape = np.shape(xdata)
for round_i in range(train_round):
all_loss = 0
for row in range(x_shape[0]):
_xdata = np.asmatrix(xdata[row, :]).T
_ydata = np.asmatrix(ydata[row, :]).T
# forward propagation
for layer in self.layers:
_xdata = layer.forward_propagation(_xdata)
loss, gradient = self.cal_loss(_ydata, _xdata)
all_loss = all_loss + loss
# back propagation: the input_layer does not upgrade
for layer in self.layers[:0:-1]:
gradient = layer.back_propagation(gradient)
mse = all_loss / x_shape[0]
self.train_mse.append(mse)
self.plot_loss()
if mse < self.accuracy:
print("----达到精度----")
return mse
def cal_loss(self, ydata, ydata_):
self.loss = np.sum(np.power((ydata - ydata_), 2))
self.loss_gradient = 2 * (ydata_ - ydata)
# vector (shape is the same as _ydata.shape)
return self.loss, self.loss_gradient
def plot_loss(self):
if self.ax_loss.lines:
self.ax_loss.lines.remove(self.ax_loss.lines[0])
self.ax_loss.plot(self.train_mse, "r-")
plt.ion()
plt.xlabel("step")
plt.ylabel("loss")
plt.show()
plt.pause(0.1)
def example():
x = np.random.randn(10, 10)
y = np.asarray(
[
[0.8, 0.4],
[0.4, 0.3],
[0.34, 0.45],
[0.67, 0.32],
[0.88, 0.67],
[0.78, 0.77],
[0.55, 0.66],
[0.55, 0.43],
[0.54, 0.1],
[0.1, 0.5],
]
)
model = BPNN()
for i in (10, 20, 30, 2):
model.add_layer(DenseLayer(i))
model.build()
model.summary()
model.train(xdata=x, ydata=y, train_round=100, accuracy=0.01)
if __name__ == "__main__":
example()
| #!/usr/bin/python
"""
A Framework of Back Propagation Neural Network(BP) model
Easy to use:
* add many layers as you want !!!
* clearly see how the loss decreasing
Easy to expand:
* more activation functions
* more loss functions
* more optimization method
Author: Stephen Lee
Github : https://github.com/RiptideBo
Date: 2017.11.23
"""
import numpy as np
from matplotlib import pyplot as plt
def sigmoid(x):
return 1 / (1 + np.exp(-1 * x))
class DenseLayer:
"""
Layers of BP neural network
"""
def __init__(
self, units, activation=None, learning_rate=None, is_input_layer=False
):
"""
common connected layer of bp network
:param units: numbers of neural units
:param activation: activation function
:param learning_rate: learning rate for paras
:param is_input_layer: whether it is input layer or not
"""
self.units = units
self.weight = None
self.bias = None
self.activation = activation
if learning_rate is None:
learning_rate = 0.3
self.learn_rate = learning_rate
self.is_input_layer = is_input_layer
def initializer(self, back_units):
self.weight = np.asmatrix(np.random.normal(0, 0.5, (self.units, back_units)))
self.bias = np.asmatrix(np.random.normal(0, 0.5, self.units)).T
if self.activation is None:
self.activation = sigmoid
def cal_gradient(self):
# activation function may be sigmoid or linear
if self.activation == sigmoid:
gradient_mat = np.dot(self.output, (1 - self.output).T)
gradient_activation = np.diag(np.diag(gradient_mat))
else:
gradient_activation = 1
return gradient_activation
def forward_propagation(self, xdata):
self.xdata = xdata
if self.is_input_layer:
# input layer
self.wx_plus_b = xdata
self.output = xdata
return xdata
else:
self.wx_plus_b = np.dot(self.weight, self.xdata) - self.bias
self.output = self.activation(self.wx_plus_b)
return self.output
def back_propagation(self, gradient):
gradient_activation = self.cal_gradient() # i * i 维
gradient = np.asmatrix(np.dot(gradient.T, gradient_activation))
self._gradient_weight = np.asmatrix(self.xdata)
self._gradient_bias = -1
self._gradient_x = self.weight
self.gradient_weight = np.dot(gradient.T, self._gradient_weight.T)
self.gradient_bias = gradient * self._gradient_bias
self.gradient = np.dot(gradient, self._gradient_x).T
# upgrade: the Negative gradient direction
self.weight = self.weight - self.learn_rate * self.gradient_weight
self.bias = self.bias - self.learn_rate * self.gradient_bias.T
# updates the weights and bias according to learning rate (0.3 if undefined)
return self.gradient
class BPNN:
"""
Back Propagation Neural Network model
"""
def __init__(self):
self.layers = []
self.train_mse = []
self.fig_loss = plt.figure()
self.ax_loss = self.fig_loss.add_subplot(1, 1, 1)
def add_layer(self, layer):
self.layers.append(layer)
def build(self):
for i, layer in enumerate(self.layers[:]):
if i < 1:
layer.is_input_layer = True
else:
layer.initializer(self.layers[i - 1].units)
def summary(self):
for i, layer in enumerate(self.layers[:]):
print("------- layer %d -------" % i)
print("weight.shape ", np.shape(layer.weight))
print("bias.shape ", np.shape(layer.bias))
def train(self, xdata, ydata, train_round, accuracy):
self.train_round = train_round
self.accuracy = accuracy
self.ax_loss.hlines(self.accuracy, 0, self.train_round * 1.1)
x_shape = np.shape(xdata)
for round_i in range(train_round):
all_loss = 0
for row in range(x_shape[0]):
_xdata = np.asmatrix(xdata[row, :]).T
_ydata = np.asmatrix(ydata[row, :]).T
# forward propagation
for layer in self.layers:
_xdata = layer.forward_propagation(_xdata)
loss, gradient = self.cal_loss(_ydata, _xdata)
all_loss = all_loss + loss
# back propagation: the input_layer does not upgrade
for layer in self.layers[:0:-1]:
gradient = layer.back_propagation(gradient)
mse = all_loss / x_shape[0]
self.train_mse.append(mse)
self.plot_loss()
if mse < self.accuracy:
print("----达到精度----")
return mse
def cal_loss(self, ydata, ydata_):
self.loss = np.sum(np.power((ydata - ydata_), 2))
self.loss_gradient = 2 * (ydata_ - ydata)
# vector (shape is the same as _ydata.shape)
return self.loss, self.loss_gradient
def plot_loss(self):
if self.ax_loss.lines:
self.ax_loss.lines.remove(self.ax_loss.lines[0])
self.ax_loss.plot(self.train_mse, "r-")
plt.ion()
plt.xlabel("step")
plt.ylabel("loss")
plt.show()
plt.pause(0.1)
def example():
x = np.random.randn(10, 10)
y = np.asarray(
[
[0.8, 0.4],
[0.4, 0.3],
[0.34, 0.45],
[0.67, 0.32],
[0.88, 0.67],
[0.78, 0.77],
[0.55, 0.66],
[0.55, 0.43],
[0.54, 0.1],
[0.1, 0.5],
]
)
model = BPNN()
for i in (10, 20, 30, 2):
model.add_layer(DenseLayer(i))
model.build()
model.summary()
model.train(xdata=x, ydata=y, train_round=100, accuracy=0.01)
if __name__ == "__main__":
example()
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Finding the shortest path in 0-1-graph in O(E + V) which is faster than dijkstra.
0-1-graph is the weighted graph with the weights equal to 0 or 1.
Link: https://codeforces.com/blog/entry/22276
"""
from __future__ import annotations
from collections import deque
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class Edge:
"""Weighted directed graph edge."""
destination_vertex: int
weight: int
class AdjacencyList:
"""Graph adjacency list."""
def __init__(self, size: int):
self._graph: list[list[Edge]] = [[] for _ in range(size)]
self._size = size
def __getitem__(self, vertex: int) -> Iterator[Edge]:
"""Get all the vertices adjacent to the given one."""
return iter(self._graph[vertex])
@property
def size(self):
return self._size
def add_edge(self, from_vertex: int, to_vertex: int, weight: int):
"""
>>> g = AdjacencyList(2)
>>> g.add_edge(0, 1, 0)
>>> g.add_edge(1, 0, 1)
>>> list(g[0])
[Edge(destination_vertex=1, weight=0)]
>>> list(g[1])
[Edge(destination_vertex=0, weight=1)]
>>> g.add_edge(0, 1, 2)
Traceback (most recent call last):
...
ValueError: Edge weight must be either 0 or 1.
>>> g.add_edge(0, 2, 1)
Traceback (most recent call last):
...
ValueError: Vertex indexes must be in [0; size).
"""
if weight not in (0, 1):
raise ValueError("Edge weight must be either 0 or 1.")
if to_vertex < 0 or to_vertex >= self.size:
raise ValueError("Vertex indexes must be in [0; size).")
self._graph[from_vertex].append(Edge(to_vertex, weight))
def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> int | None:
"""
Return the shortest distance from start_vertex to finish_vertex in 0-1-graph.
1 1 1
0--------->3 6--------7>------->8
| ^ ^ ^ |1
| | | |0 v
0| |0 1| 9-------->10
| | | ^ 1
v | | |0
1--------->2<-------4------->5
0 1 1
>>> g = AdjacencyList(11)
>>> g.add_edge(0, 1, 0)
>>> g.add_edge(0, 3, 1)
>>> g.add_edge(1, 2, 0)
>>> g.add_edge(2, 3, 0)
>>> g.add_edge(4, 2, 1)
>>> g.add_edge(4, 5, 1)
>>> g.add_edge(4, 6, 1)
>>> g.add_edge(5, 9, 0)
>>> g.add_edge(6, 7, 1)
>>> g.add_edge(7, 8, 1)
>>> g.add_edge(8, 10, 1)
>>> g.add_edge(9, 7, 0)
>>> g.add_edge(9, 10, 1)
>>> g.add_edge(1, 2, 2)
Traceback (most recent call last):
...
ValueError: Edge weight must be either 0 or 1.
>>> g.get_shortest_path(0, 3)
0
>>> g.get_shortest_path(0, 4)
Traceback (most recent call last):
...
ValueError: No path from start_vertex to finish_vertex.
>>> g.get_shortest_path(4, 10)
2
>>> g.get_shortest_path(4, 8)
2
>>> g.get_shortest_path(0, 1)
0
>>> g.get_shortest_path(1, 0)
Traceback (most recent call last):
...
ValueError: No path from start_vertex to finish_vertex.
"""
queue = deque([start_vertex])
distances: list[int | None] = [None] * self.size
distances[start_vertex] = 0
while queue:
current_vertex = queue.popleft()
current_distance = distances[current_vertex]
if current_distance is None:
continue
for edge in self[current_vertex]:
new_distance = current_distance + edge.weight
dest_vertex_distance = distances[edge.destination_vertex]
if (
isinstance(dest_vertex_distance, int)
and new_distance >= dest_vertex_distance
):
continue
distances[edge.destination_vertex] = new_distance
if edge.weight == 0:
queue.appendleft(edge.destination_vertex)
else:
queue.append(edge.destination_vertex)
if distances[finish_vertex] is None:
raise ValueError("No path from start_vertex to finish_vertex.")
return distances[finish_vertex]
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Finding the shortest path in 0-1-graph in O(E + V) which is faster than dijkstra.
0-1-graph is the weighted graph with the weights equal to 0 or 1.
Link: https://codeforces.com/blog/entry/22276
"""
from __future__ import annotations
from collections import deque
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class Edge:
"""Weighted directed graph edge."""
destination_vertex: int
weight: int
class AdjacencyList:
"""Graph adjacency list."""
def __init__(self, size: int):
self._graph: list[list[Edge]] = [[] for _ in range(size)]
self._size = size
def __getitem__(self, vertex: int) -> Iterator[Edge]:
"""Get all the vertices adjacent to the given one."""
return iter(self._graph[vertex])
@property
def size(self):
return self._size
def add_edge(self, from_vertex: int, to_vertex: int, weight: int):
"""
>>> g = AdjacencyList(2)
>>> g.add_edge(0, 1, 0)
>>> g.add_edge(1, 0, 1)
>>> list(g[0])
[Edge(destination_vertex=1, weight=0)]
>>> list(g[1])
[Edge(destination_vertex=0, weight=1)]
>>> g.add_edge(0, 1, 2)
Traceback (most recent call last):
...
ValueError: Edge weight must be either 0 or 1.
>>> g.add_edge(0, 2, 1)
Traceback (most recent call last):
...
ValueError: Vertex indexes must be in [0; size).
"""
if weight not in (0, 1):
raise ValueError("Edge weight must be either 0 or 1.")
if to_vertex < 0 or to_vertex >= self.size:
raise ValueError("Vertex indexes must be in [0; size).")
self._graph[from_vertex].append(Edge(to_vertex, weight))
def get_shortest_path(self, start_vertex: int, finish_vertex: int) -> int | None:
"""
Return the shortest distance from start_vertex to finish_vertex in 0-1-graph.
1 1 1
0--------->3 6--------7>------->8
| ^ ^ ^ |1
| | | |0 v
0| |0 1| 9-------->10
| | | ^ 1
v | | |0
1--------->2<-------4------->5
0 1 1
>>> g = AdjacencyList(11)
>>> g.add_edge(0, 1, 0)
>>> g.add_edge(0, 3, 1)
>>> g.add_edge(1, 2, 0)
>>> g.add_edge(2, 3, 0)
>>> g.add_edge(4, 2, 1)
>>> g.add_edge(4, 5, 1)
>>> g.add_edge(4, 6, 1)
>>> g.add_edge(5, 9, 0)
>>> g.add_edge(6, 7, 1)
>>> g.add_edge(7, 8, 1)
>>> g.add_edge(8, 10, 1)
>>> g.add_edge(9, 7, 0)
>>> g.add_edge(9, 10, 1)
>>> g.add_edge(1, 2, 2)
Traceback (most recent call last):
...
ValueError: Edge weight must be either 0 or 1.
>>> g.get_shortest_path(0, 3)
0
>>> g.get_shortest_path(0, 4)
Traceback (most recent call last):
...
ValueError: No path from start_vertex to finish_vertex.
>>> g.get_shortest_path(4, 10)
2
>>> g.get_shortest_path(4, 8)
2
>>> g.get_shortest_path(0, 1)
0
>>> g.get_shortest_path(1, 0)
Traceback (most recent call last):
...
ValueError: No path from start_vertex to finish_vertex.
"""
queue = deque([start_vertex])
distances: list[int | None] = [None] * self.size
distances[start_vertex] = 0
while queue:
current_vertex = queue.popleft()
current_distance = distances[current_vertex]
if current_distance is None:
continue
for edge in self[current_vertex]:
new_distance = current_distance + edge.weight
dest_vertex_distance = distances[edge.destination_vertex]
if (
isinstance(dest_vertex_distance, int)
and new_distance >= dest_vertex_distance
):
continue
distances[edge.destination_vertex] = new_distance
if edge.weight == 0:
queue.appendleft(edge.destination_vertex)
else:
queue.append(edge.destination_vertex)
if distances[finish_vertex] is None:
raise ValueError("No path from start_vertex to finish_vertex.")
return distances[finish_vertex]
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 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 | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
This is a pure Python implementation of the selection sort algorithm
For doctests run following command:
python -m doctest -v selection_sort.py
or
python3 -m doctest -v selection_sort.py
For manual testing run:
python selection_sort.py
"""
def selection_sort(collection):
"""Pure implementation of the selection sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> selection_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> selection_sort([])
[]
>>> selection_sort([-2, -5, -45])
[-45, -5, -2]
"""
length = len(collection)
for i in range(length - 1):
least = i
for k in range(i + 1, length):
if collection[k] < collection[least]:
least = k
if least != i:
collection[least], collection[i] = (collection[i], collection[least])
return collection
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(selection_sort(unsorted))
| """
This is a pure Python implementation of the selection sort algorithm
For doctests run following command:
python -m doctest -v selection_sort.py
or
python3 -m doctest -v selection_sort.py
For manual testing run:
python selection_sort.py
"""
def selection_sort(collection):
"""Pure implementation of the selection sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> selection_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> selection_sort([])
[]
>>> selection_sort([-2, -5, -45])
[-45, -5, -2]
"""
length = len(collection)
for i in range(length - 1):
least = i
for k in range(i + 1, length):
if collection[k] < collection[least]:
least = k
if least != i:
collection[least], collection[i] = (collection[i], collection[least])
return collection
if __name__ == "__main__":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(selection_sort(unsorted))
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from __future__ import annotations
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 | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| def bin_exp_mod(a, n, b):
"""
>>> bin_exp_mod(3, 4, 5)
1
>>> bin_exp_mod(7, 13, 10)
7
"""
# mod b
assert not (b == 0), "This cannot accept modulo that is == 0"
if n == 0:
return 1
if n % 2 == 1:
return (bin_exp_mod(a, n - 1, b) * a) % b
r = bin_exp_mod(a, n / 2, b)
return (r * r) % b
if __name__ == "__main__":
try:
BASE = int(input("Enter Base : ").strip())
POWER = int(input("Enter Power : ").strip())
MODULO = int(input("Enter Modulo : ").strip())
except ValueError:
print("Invalid literal for integer")
print(bin_exp_mod(BASE, POWER, MODULO))
| def bin_exp_mod(a, n, b):
"""
>>> bin_exp_mod(3, 4, 5)
1
>>> bin_exp_mod(7, 13, 10)
7
"""
# mod b
assert not (b == 0), "This cannot accept modulo that is == 0"
if n == 0:
return 1
if n % 2 == 1:
return (bin_exp_mod(a, n - 1, b) * a) % b
r = bin_exp_mod(a, n / 2, b)
return (r * r) % b
if __name__ == "__main__":
try:
BASE = int(input("Enter Base : ").strip())
POWER = int(input("Enter Power : ").strip())
MODULO = int(input("Enter Modulo : ").strip())
except ValueError:
print("Invalid literal for integer")
print(bin_exp_mod(BASE, POWER, MODULO))
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Sieve of Eratosthones
The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or
equal to a given value.
Illustration:
https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif
Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich)
Also thanks to Dmitry (https://github.com/LizardWizzard) for finding the problem
"""
from __future__ import annotations
import math
def prime_sieve(num: int) -> list[int]:
"""
Returns a list with all prime numbers up to n.
>>> prime_sieve(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> prime_sieve(25)
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> prime_sieve(10)
[2, 3, 5, 7]
>>> prime_sieve(9)
[2, 3, 5, 7]
>>> prime_sieve(2)
[2]
>>> prime_sieve(1)
[]
"""
if num <= 0:
raise ValueError(f"{num}: Invalid input, please enter a positive integer.")
sieve = [True] * (num + 1)
prime = []
start = 2
end = int(math.sqrt(num))
while start <= end:
# If start is a prime
if sieve[start] is True:
prime.append(start)
# Set multiples of start be False
for i in range(start * start, num + 1, start):
if sieve[i] is True:
sieve[i] = False
start += 1
for j in range(end + 1, num + 1):
if sieve[j] is True:
prime.append(j)
return prime
if __name__ == "__main__":
print(prime_sieve(int(input("Enter a positive integer: ").strip())))
| """
Sieve of Eratosthones
The sieve of Eratosthenes is an algorithm used to find prime numbers, less than or
equal to a given value.
Illustration:
https://upload.wikimedia.org/wikipedia/commons/b/b9/Sieve_of_Eratosthenes_animation.gif
Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
doctest provider: Bruno Simas Hadlich (https://github.com/brunohadlich)
Also thanks to Dmitry (https://github.com/LizardWizzard) for finding the problem
"""
from __future__ import annotations
import math
def prime_sieve(num: int) -> list[int]:
"""
Returns a list with all prime numbers up to n.
>>> prime_sieve(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
>>> prime_sieve(25)
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> prime_sieve(10)
[2, 3, 5, 7]
>>> prime_sieve(9)
[2, 3, 5, 7]
>>> prime_sieve(2)
[2]
>>> prime_sieve(1)
[]
"""
if num <= 0:
raise ValueError(f"{num}: Invalid input, please enter a positive integer.")
sieve = [True] * (num + 1)
prime = []
start = 2
end = int(math.sqrt(num))
while start <= end:
# If start is a prime
if sieve[start] is True:
prime.append(start)
# Set multiples of start be False
for i in range(start * start, num + 1, start):
if sieve[i] is True:
sieve[i] = False
start += 1
for j in range(end + 1, num + 1):
if sieve[j] is True:
prime.append(j)
return prime
if __name__ == "__main__":
print(prime_sieve(int(input("Enter a positive integer: ").strip())))
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Is IP v4 address valid?
A valid IP address must be four octets in the form of A.B.C.D,
where A,B,C and D are numbers from 0-254
for example: 192.168.23.1, 172.254.254.254 are valid IP address
192.168.255.0, 255.192.3.121 are invalid IP address
"""
def is_ip_v4_address_valid(ip_v4_address: str) -> bool:
"""
print "Valid IP address" If IP is valid.
or
print "Invalid IP address" If IP is invalid.
>>> is_ip_v4_address_valid("192.168.0.23")
True
>>> is_ip_v4_address_valid("192.255.15.8")
False
>>> is_ip_v4_address_valid("172.100.0.8")
True
>>> is_ip_v4_address_valid("254.255.0.255")
False
>>> is_ip_v4_address_valid("1.2.33333333.4")
False
>>> is_ip_v4_address_valid("1.2.-3.4")
False
>>> is_ip_v4_address_valid("1.2.3")
False
>>> is_ip_v4_address_valid("1.2.3.4.5")
False
>>> is_ip_v4_address_valid("1.2.A.4")
False
>>> is_ip_v4_address_valid("0.0.0.0")
True
>>> is_ip_v4_address_valid("1.2.3.")
False
"""
octets = [int(i) for i in ip_v4_address.split(".") if i.isdigit()]
return len(octets) == 4 and all(0 <= int(octet) <= 254 for octet in octets)
if __name__ == "__main__":
ip = input().strip()
valid_or_invalid = "valid" if is_ip_v4_address_valid(ip) else "invalid"
print(f"{ip} is a {valid_or_invalid} IP v4 address.")
| """
Is IP v4 address valid?
A valid IP address must be four octets in the form of A.B.C.D,
where A,B,C and D are numbers from 0-254
for example: 192.168.23.1, 172.254.254.254 are valid IP address
192.168.255.0, 255.192.3.121 are invalid IP address
"""
def is_ip_v4_address_valid(ip_v4_address: str) -> bool:
"""
print "Valid IP address" If IP is valid.
or
print "Invalid IP address" If IP is invalid.
>>> is_ip_v4_address_valid("192.168.0.23")
True
>>> is_ip_v4_address_valid("192.255.15.8")
False
>>> is_ip_v4_address_valid("172.100.0.8")
True
>>> is_ip_v4_address_valid("254.255.0.255")
False
>>> is_ip_v4_address_valid("1.2.33333333.4")
False
>>> is_ip_v4_address_valid("1.2.-3.4")
False
>>> is_ip_v4_address_valid("1.2.3")
False
>>> is_ip_v4_address_valid("1.2.3.4.5")
False
>>> is_ip_v4_address_valid("1.2.A.4")
False
>>> is_ip_v4_address_valid("0.0.0.0")
True
>>> is_ip_v4_address_valid("1.2.3.")
False
"""
octets = [int(i) for i in ip_v4_address.split(".") if i.isdigit()]
return len(octets) == 4 and all(0 <= int(octet) <= 254 for octet in octets)
if __name__ == "__main__":
ip = input().strip()
valid_or_invalid = "valid" if is_ip_v4_address_valid(ip) else "invalid"
print(f"{ip} is a {valid_or_invalid} IP v4 address.")
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Program to join a list of strings with a given separator
"""
def join(separator: str, separated: list[str]) -> str:
"""
>>> join("", ["a", "b", "c", "d"])
'abcd'
>>> join("#", ["a", "b", "c", "d"])
'a#b#c#d'
>>> join("#", "a")
'a'
>>> join(" ", ["You", "are", "amazing!"])
'You are amazing!'
>>> join("#", ["a", "b", "c", 1])
Traceback (most recent call last):
...
Exception: join() accepts only strings to be joined
"""
joined = ""
for word_or_phrase in separated:
if not isinstance(word_or_phrase, str):
raise Exception("join() accepts only strings to be joined")
joined += word_or_phrase + separator
return joined.strip(separator)
if __name__ == "__main__":
from doctest import testmod
testmod()
| """
Program to join a list of strings with a given separator
"""
def join(separator: str, separated: list[str]) -> str:
"""
>>> join("", ["a", "b", "c", "d"])
'abcd'
>>> join("#", ["a", "b", "c", "d"])
'a#b#c#d'
>>> join("#", "a")
'a'
>>> join(" ", ["You", "are", "amazing!"])
'You are amazing!'
>>> join("#", ["a", "b", "c", 1])
Traceback (most recent call last):
...
Exception: join() accepts only strings to be joined
"""
joined = ""
for word_or_phrase in separated:
if not isinstance(word_or_phrase, str):
raise Exception("join() accepts only strings to be joined")
joined += word_or_phrase + separator
return joined.strip(separator)
if __name__ == "__main__":
from doctest import testmod
testmod()
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Jacobi Iteration Method - https://en.wikipedia.org/wiki/Jacobi_method
"""
from __future__ import annotations
import numpy as np
from numpy import float64
from numpy.typing import NDArray
# Method to find solution of system of linear equations
def jacobi_iteration_method(
coefficient_matrix: NDArray[float64],
constant_matrix: NDArray[float64],
init_val: list[int],
iterations: int,
) -> list[float]:
"""
Jacobi Iteration Method:
An iterative algorithm to determine the solutions of strictly diagonally dominant
system of linear equations
4x1 + x2 + x3 = 2
x1 + 5x2 + 2x3 = -6
x1 + 2x2 + 4x3 = -4
x_init = [0.5, -0.5 , -0.5]
Examples:
>>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])
>>> constant = np.array([[2], [-6], [-4]])
>>> init_val = [0.5, -0.5, -0.5]
>>> iterations = 3
>>> jacobi_iteration_method(coefficient, constant, init_val, iterations)
[0.909375, -1.14375, -0.7484375]
>>> coefficient = np.array([[4, 1, 1], [1, 5, 2]])
>>> constant = np.array([[2], [-6], [-4]])
>>> init_val = [0.5, -0.5, -0.5]
>>> iterations = 3
>>> jacobi_iteration_method(coefficient, constant, init_val, iterations)
Traceback (most recent call last):
...
ValueError: Coefficient matrix dimensions must be nxn but received 2x3
>>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])
>>> constant = np.array([[2], [-6]])
>>> init_val = [0.5, -0.5, -0.5]
>>> iterations = 3
>>> jacobi_iteration_method(coefficient, constant, init_val, iterations)
Traceback (most recent call last):
...
ValueError: Coefficient and constant matrices dimensions must be nxn and nx1 but
received 3x3 and 2x1
>>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])
>>> constant = np.array([[2], [-6], [-4]])
>>> init_val = [0.5, -0.5]
>>> iterations = 3
>>> jacobi_iteration_method(coefficient, constant, init_val, iterations)
Traceback (most recent call last):
...
ValueError: Number of initial values must be equal to number of rows in coefficient
matrix but received 2 and 3
>>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])
>>> constant = np.array([[2], [-6], [-4]])
>>> init_val = [0.5, -0.5, -0.5]
>>> iterations = 0
>>> jacobi_iteration_method(coefficient, constant, init_val, iterations)
Traceback (most recent call last):
...
ValueError: Iterations must be at least 1
"""
rows1, cols1 = coefficient_matrix.shape
rows2, cols2 = constant_matrix.shape
if rows1 != cols1:
raise ValueError(
f"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}"
)
if cols2 != 1:
raise ValueError(f"Constant matrix must be nx1 but received {rows2}x{cols2}")
if rows1 != rows2:
raise ValueError(
f"""Coefficient and constant matrices dimensions must be nxn and nx1 but
received {rows1}x{cols1} and {rows2}x{cols2}"""
)
if len(init_val) != rows1:
raise ValueError(
f"""Number of initial values must be equal to number of rows in coefficient
matrix but received {len(init_val)} and {rows1}"""
)
if iterations <= 0:
raise ValueError("Iterations must be at least 1")
table: NDArray[float64] = np.concatenate(
(coefficient_matrix, constant_matrix), axis=1
)
rows, cols = table.shape
strictly_diagonally_dominant(table)
# Iterates the whole matrix for given number of times
for i in range(iterations):
new_val = []
for row in range(rows):
temp = 0
for col in range(cols):
if col == row:
denom = table[row][col]
elif col == cols - 1:
val = table[row][col]
else:
temp += (-1) * table[row][col] * init_val[col]
temp = (temp + val) / denom
new_val.append(temp)
init_val = new_val
return [float(i) for i in new_val]
# Checks if the given matrix is strictly diagonally dominant
def strictly_diagonally_dominant(table: NDArray[float64]) -> bool:
"""
>>> table = np.array([[4, 1, 1, 2], [1, 5, 2, -6], [1, 2, 4, -4]])
>>> strictly_diagonally_dominant(table)
True
>>> table = np.array([[4, 1, 1, 2], [1, 5, 2, -6], [1, 2, 3, -4]])
>>> strictly_diagonally_dominant(table)
Traceback (most recent call last):
...
ValueError: Coefficient matrix is not strictly diagonally dominant
"""
rows, cols = table.shape
is_diagonally_dominant = True
for i in range(0, rows):
sum = 0
for j in range(0, cols - 1):
if i == j:
continue
else:
sum += table[i][j]
if table[i][i] <= sum:
raise ValueError("Coefficient matrix is not strictly diagonally dominant")
return is_diagonally_dominant
# Test Cases
if __name__ == "__main__":
import doctest
doctest.testmod()
| """
Jacobi Iteration Method - https://en.wikipedia.org/wiki/Jacobi_method
"""
from __future__ import annotations
import numpy as np
from numpy import float64
from numpy.typing import NDArray
# Method to find solution of system of linear equations
def jacobi_iteration_method(
coefficient_matrix: NDArray[float64],
constant_matrix: NDArray[float64],
init_val: list[int],
iterations: int,
) -> list[float]:
"""
Jacobi Iteration Method:
An iterative algorithm to determine the solutions of strictly diagonally dominant
system of linear equations
4x1 + x2 + x3 = 2
x1 + 5x2 + 2x3 = -6
x1 + 2x2 + 4x3 = -4
x_init = [0.5, -0.5 , -0.5]
Examples:
>>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])
>>> constant = np.array([[2], [-6], [-4]])
>>> init_val = [0.5, -0.5, -0.5]
>>> iterations = 3
>>> jacobi_iteration_method(coefficient, constant, init_val, iterations)
[0.909375, -1.14375, -0.7484375]
>>> coefficient = np.array([[4, 1, 1], [1, 5, 2]])
>>> constant = np.array([[2], [-6], [-4]])
>>> init_val = [0.5, -0.5, -0.5]
>>> iterations = 3
>>> jacobi_iteration_method(coefficient, constant, init_val, iterations)
Traceback (most recent call last):
...
ValueError: Coefficient matrix dimensions must be nxn but received 2x3
>>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])
>>> constant = np.array([[2], [-6]])
>>> init_val = [0.5, -0.5, -0.5]
>>> iterations = 3
>>> jacobi_iteration_method(coefficient, constant, init_val, iterations)
Traceback (most recent call last):
...
ValueError: Coefficient and constant matrices dimensions must be nxn and nx1 but
received 3x3 and 2x1
>>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])
>>> constant = np.array([[2], [-6], [-4]])
>>> init_val = [0.5, -0.5]
>>> iterations = 3
>>> jacobi_iteration_method(coefficient, constant, init_val, iterations)
Traceback (most recent call last):
...
ValueError: Number of initial values must be equal to number of rows in coefficient
matrix but received 2 and 3
>>> coefficient = np.array([[4, 1, 1], [1, 5, 2], [1, 2, 4]])
>>> constant = np.array([[2], [-6], [-4]])
>>> init_val = [0.5, -0.5, -0.5]
>>> iterations = 0
>>> jacobi_iteration_method(coefficient, constant, init_val, iterations)
Traceback (most recent call last):
...
ValueError: Iterations must be at least 1
"""
rows1, cols1 = coefficient_matrix.shape
rows2, cols2 = constant_matrix.shape
if rows1 != cols1:
raise ValueError(
f"Coefficient matrix dimensions must be nxn but received {rows1}x{cols1}"
)
if cols2 != 1:
raise ValueError(f"Constant matrix must be nx1 but received {rows2}x{cols2}")
if rows1 != rows2:
raise ValueError(
f"""Coefficient and constant matrices dimensions must be nxn and nx1 but
received {rows1}x{cols1} and {rows2}x{cols2}"""
)
if len(init_val) != rows1:
raise ValueError(
f"""Number of initial values must be equal to number of rows in coefficient
matrix but received {len(init_val)} and {rows1}"""
)
if iterations <= 0:
raise ValueError("Iterations must be at least 1")
table: NDArray[float64] = np.concatenate(
(coefficient_matrix, constant_matrix), axis=1
)
rows, cols = table.shape
strictly_diagonally_dominant(table)
# Iterates the whole matrix for given number of times
for i in range(iterations):
new_val = []
for row in range(rows):
temp = 0
for col in range(cols):
if col == row:
denom = table[row][col]
elif col == cols - 1:
val = table[row][col]
else:
temp += (-1) * table[row][col] * init_val[col]
temp = (temp + val) / denom
new_val.append(temp)
init_val = new_val
return [float(i) for i in new_val]
# Checks if the given matrix is strictly diagonally dominant
def strictly_diagonally_dominant(table: NDArray[float64]) -> bool:
"""
>>> table = np.array([[4, 1, 1, 2], [1, 5, 2, -6], [1, 2, 4, -4]])
>>> strictly_diagonally_dominant(table)
True
>>> table = np.array([[4, 1, 1, 2], [1, 5, 2, -6], [1, 2, 3, -4]])
>>> strictly_diagonally_dominant(table)
Traceback (most recent call last):
...
ValueError: Coefficient matrix is not strictly diagonally dominant
"""
rows, cols = table.shape
is_diagonally_dominant = True
for i in range(0, rows):
sum = 0
for j in range(0, cols - 1):
if i == j:
continue
else:
sum += table[i][j]
if table[i][i] <= sum:
raise ValueError("Coefficient matrix is not strictly diagonally dominant")
return is_diagonally_dominant
# Test Cases
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| class Heap:
"""
A generic Heap class, can be used as min or max by passing the key function
accordingly.
"""
def __init__(self, key=None):
# Stores actual heap items.
self.arr = list()
# Stores indexes of each item for supporting updates and deletion.
self.pos_map = {}
# Stores current size of heap.
self.size = 0
# Stores function used to evaluate the score of an item on which basis ordering
# will be done.
self.key = key or (lambda x: x)
def _parent(self, i):
"""Returns parent index of given index if exists else None"""
return int((i - 1) / 2) if i > 0 else None
def _left(self, i):
"""Returns left-child-index of given index if exists else None"""
left = int(2 * i + 1)
return left if 0 < left < self.size else None
def _right(self, i):
"""Returns right-child-index of given index if exists else None"""
right = int(2 * i + 2)
return right if 0 < right < self.size else None
def _swap(self, i, j):
"""Performs changes required for swapping two elements in the heap"""
# First update the indexes of the items in index map.
self.pos_map[self.arr[i][0]], self.pos_map[self.arr[j][0]] = (
self.pos_map[self.arr[j][0]],
self.pos_map[self.arr[i][0]],
)
# Then swap the items in the list.
self.arr[i], self.arr[j] = self.arr[j], self.arr[i]
def _cmp(self, i, j):
"""Compares the two items using default comparison"""
return self.arr[i][1] < self.arr[j][1]
def _get_valid_parent(self, i):
"""
Returns index of valid parent as per desired ordering among given index and
both it's children
"""
left = self._left(i)
right = self._right(i)
valid_parent = i
if left is not None and not self._cmp(left, valid_parent):
valid_parent = left
if right is not None and not self._cmp(right, valid_parent):
valid_parent = right
return valid_parent
def _heapify_up(self, index):
"""Fixes the heap in upward direction of given index"""
parent = self._parent(index)
while parent is not None and not self._cmp(index, parent):
self._swap(index, parent)
index, parent = parent, self._parent(parent)
def _heapify_down(self, index):
"""Fixes the heap in downward direction of given index"""
valid_parent = self._get_valid_parent(index)
while valid_parent != index:
self._swap(index, valid_parent)
index, valid_parent = valid_parent, self._get_valid_parent(valid_parent)
def update_item(self, item, item_value):
"""Updates given item value in heap if present"""
if item not in self.pos_map:
return
index = self.pos_map[item]
self.arr[index] = [item, self.key(item_value)]
# Make sure heap is right in both up and down direction.
# Ideally only one of them will make any change.
self._heapify_up(index)
self._heapify_down(index)
def delete_item(self, item):
"""Deletes given item from heap if present"""
if item not in self.pos_map:
return
index = self.pos_map[item]
del self.pos_map[item]
self.arr[index] = self.arr[self.size - 1]
self.pos_map[self.arr[self.size - 1][0]] = index
self.size -= 1
# Make sure heap is right in both up and down direction. Ideally only one
# of them will make any change- so no performance loss in calling both.
if self.size > index:
self._heapify_up(index)
self._heapify_down(index)
def insert_item(self, item, item_value):
"""Inserts given item with given value in heap"""
arr_len = len(self.arr)
if arr_len == self.size:
self.arr.append([item, self.key(item_value)])
else:
self.arr[self.size] = [item, self.key(item_value)]
self.pos_map[item] = self.size
self.size += 1
self._heapify_up(self.size - 1)
def get_top(self):
"""Returns top item tuple (Calculated value, item) from heap if present"""
return self.arr[0] if self.size else None
def extract_top(self):
"""
Return top item tuple (Calculated value, item) from heap and removes it as well
if present
"""
top_item_tuple = self.get_top()
if top_item_tuple:
self.delete_item(top_item_tuple[0])
return top_item_tuple
def test_heap() -> None:
"""
>>> h = Heap() # Max-heap
>>> h.insert_item(5, 34)
>>> h.insert_item(6, 31)
>>> h.insert_item(7, 37)
>>> h.get_top()
[7, 37]
>>> h.extract_top()
[7, 37]
>>> h.extract_top()
[5, 34]
>>> h.extract_top()
[6, 31]
>>> h = Heap(key=lambda x: -x) # Min heap
>>> h.insert_item(5, 34)
>>> h.insert_item(6, 31)
>>> h.insert_item(7, 37)
>>> h.get_top()
[6, -31]
>>> h.extract_top()
[6, -31]
>>> h.extract_top()
[5, -34]
>>> h.extract_top()
[7, -37]
>>> h.insert_item(8, 45)
>>> h.insert_item(9, 40)
>>> h.insert_item(10, 50)
>>> h.get_top()
[9, -40]
>>> h.update_item(10, 30)
>>> h.get_top()
[10, -30]
>>> h.delete_item(10)
>>> h.get_top()
[9, -40]
"""
pass
if __name__ == "__main__":
import doctest
doctest.testmod()
| class Heap:
"""
A generic Heap class, can be used as min or max by passing the key function
accordingly.
"""
def __init__(self, key=None):
# Stores actual heap items.
self.arr = list()
# Stores indexes of each item for supporting updates and deletion.
self.pos_map = {}
# Stores current size of heap.
self.size = 0
# Stores function used to evaluate the score of an item on which basis ordering
# will be done.
self.key = key or (lambda x: x)
def _parent(self, i):
"""Returns parent index of given index if exists else None"""
return int((i - 1) / 2) if i > 0 else None
def _left(self, i):
"""Returns left-child-index of given index if exists else None"""
left = int(2 * i + 1)
return left if 0 < left < self.size else None
def _right(self, i):
"""Returns right-child-index of given index if exists else None"""
right = int(2 * i + 2)
return right if 0 < right < self.size else None
def _swap(self, i, j):
"""Performs changes required for swapping two elements in the heap"""
# First update the indexes of the items in index map.
self.pos_map[self.arr[i][0]], self.pos_map[self.arr[j][0]] = (
self.pos_map[self.arr[j][0]],
self.pos_map[self.arr[i][0]],
)
# Then swap the items in the list.
self.arr[i], self.arr[j] = self.arr[j], self.arr[i]
def _cmp(self, i, j):
"""Compares the two items using default comparison"""
return self.arr[i][1] < self.arr[j][1]
def _get_valid_parent(self, i):
"""
Returns index of valid parent as per desired ordering among given index and
both it's children
"""
left = self._left(i)
right = self._right(i)
valid_parent = i
if left is not None and not self._cmp(left, valid_parent):
valid_parent = left
if right is not None and not self._cmp(right, valid_parent):
valid_parent = right
return valid_parent
def _heapify_up(self, index):
"""Fixes the heap in upward direction of given index"""
parent = self._parent(index)
while parent is not None and not self._cmp(index, parent):
self._swap(index, parent)
index, parent = parent, self._parent(parent)
def _heapify_down(self, index):
"""Fixes the heap in downward direction of given index"""
valid_parent = self._get_valid_parent(index)
while valid_parent != index:
self._swap(index, valid_parent)
index, valid_parent = valid_parent, self._get_valid_parent(valid_parent)
def update_item(self, item, item_value):
"""Updates given item value in heap if present"""
if item not in self.pos_map:
return
index = self.pos_map[item]
self.arr[index] = [item, self.key(item_value)]
# Make sure heap is right in both up and down direction.
# Ideally only one of them will make any change.
self._heapify_up(index)
self._heapify_down(index)
def delete_item(self, item):
"""Deletes given item from heap if present"""
if item not in self.pos_map:
return
index = self.pos_map[item]
del self.pos_map[item]
self.arr[index] = self.arr[self.size - 1]
self.pos_map[self.arr[self.size - 1][0]] = index
self.size -= 1
# Make sure heap is right in both up and down direction. Ideally only one
# of them will make any change- so no performance loss in calling both.
if self.size > index:
self._heapify_up(index)
self._heapify_down(index)
def insert_item(self, item, item_value):
"""Inserts given item with given value in heap"""
arr_len = len(self.arr)
if arr_len == self.size:
self.arr.append([item, self.key(item_value)])
else:
self.arr[self.size] = [item, self.key(item_value)]
self.pos_map[item] = self.size
self.size += 1
self._heapify_up(self.size - 1)
def get_top(self):
"""Returns top item tuple (Calculated value, item) from heap if present"""
return self.arr[0] if self.size else None
def extract_top(self):
"""
Return top item tuple (Calculated value, item) from heap and removes it as well
if present
"""
top_item_tuple = self.get_top()
if top_item_tuple:
self.delete_item(top_item_tuple[0])
return top_item_tuple
def test_heap() -> None:
"""
>>> h = Heap() # Max-heap
>>> h.insert_item(5, 34)
>>> h.insert_item(6, 31)
>>> h.insert_item(7, 37)
>>> h.get_top()
[7, 37]
>>> h.extract_top()
[7, 37]
>>> h.extract_top()
[5, 34]
>>> h.extract_top()
[6, 31]
>>> h = Heap(key=lambda x: -x) # Min heap
>>> h.insert_item(5, 34)
>>> h.insert_item(6, 31)
>>> h.insert_item(7, 37)
>>> h.get_top()
[6, -31]
>>> h.extract_top()
[6, -31]
>>> h.extract_top()
[5, -34]
>>> h.extract_top()
[7, -37]
>>> h.insert_item(8, 45)
>>> h.insert_item(9, 40)
>>> h.insert_item(10, 50)
>>> h.get_top()
[9, -40]
>>> h.update_item(10, 30)
>>> h.get_top()
[10, -30]
>>> h.delete_item(10)
>>> h.get_top()
[9, -40]
"""
pass
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import base64
def base16_encode(inp: str) -> bytes:
"""
Encodes a given utf-8 string into base-16.
>>> base16_encode('Hello World!')
b'48656C6C6F20576F726C6421'
>>> base16_encode('HELLO WORLD!')
b'48454C4C4F20574F524C4421'
>>> base16_encode('')
b''
"""
# encode the input into a bytes-like object and then encode b16encode that
return base64.b16encode(inp.encode("utf-8"))
def base16_decode(b16encoded: bytes) -> str:
"""
Decodes from base-16 to a utf-8 string.
>>> base16_decode(b'48656C6C6F20576F726C6421')
'Hello World!'
>>> base16_decode(b'48454C4C4F20574F524C4421')
'HELLO WORLD!'
>>> base16_decode(b'')
''
"""
# b16decode the input into bytes and decode that into a human readable string
return base64.b16decode(b16encoded).decode("utf-8")
if __name__ == "__main__":
import doctest
doctest.testmod()
| import base64
def base16_encode(inp: str) -> bytes:
"""
Encodes a given utf-8 string into base-16.
>>> base16_encode('Hello World!')
b'48656C6C6F20576F726C6421'
>>> base16_encode('HELLO WORLD!')
b'48454C4C4F20574F524C4421'
>>> base16_encode('')
b''
"""
# encode the input into a bytes-like object and then encode b16encode that
return base64.b16encode(inp.encode("utf-8"))
def base16_decode(b16encoded: bytes) -> str:
"""
Decodes from base-16 to a utf-8 string.
>>> base16_decode(b'48656C6C6F20576F726C6421')
'Hello World!'
>>> base16_decode(b'48454C4C4F20574F524C4421')
'HELLO WORLD!'
>>> base16_decode(b'')
''
"""
# b16decode the input into bytes and decode that into a human readable string
return base64.b16decode(b16encoded).decode("utf-8")
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Ford-Fulkerson Algorithm for Maximum Flow Problem
"""
Description:
(1) Start with initial flow as 0;
(2) Choose augmenting path from source to sink and add path to flow;
"""
def BFS(graph, s, t, parent):
# Return True if there is node that has not iterated.
visited = [False] * len(graph)
queue = []
queue.append(s)
visited[s] = True
while queue:
u = queue.pop(0)
for ind in range(len(graph[u])):
if visited[ind] is False and graph[u][ind] > 0:
queue.append(ind)
visited[ind] = True
parent[ind] = u
return True if visited[t] else False
def FordFulkerson(graph, source, sink):
# This array is filled by BFS and to store path
parent = [-1] * (len(graph))
max_flow = 0
while BFS(graph, source, sink, parent):
path_flow = float("Inf")
s = sink
while s != source:
# Find the minimum value in select path
path_flow = min(path_flow, graph[parent[s]][s])
s = parent[s]
max_flow += path_flow
v = sink
while v != source:
u = parent[v]
graph[u][v] -= path_flow
graph[v][u] += path_flow
v = parent[v]
return max_flow
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0],
]
source, sink = 0, 5
print(FordFulkerson(graph, source, sink))
| # Ford-Fulkerson Algorithm for Maximum Flow Problem
"""
Description:
(1) Start with initial flow as 0;
(2) Choose augmenting path from source to sink and add path to flow;
"""
def BFS(graph, s, t, parent):
# Return True if there is node that has not iterated.
visited = [False] * len(graph)
queue = []
queue.append(s)
visited[s] = True
while queue:
u = queue.pop(0)
for ind in range(len(graph[u])):
if visited[ind] is False and graph[u][ind] > 0:
queue.append(ind)
visited[ind] = True
parent[ind] = u
return True if visited[t] else False
def FordFulkerson(graph, source, sink):
# This array is filled by BFS and to store path
parent = [-1] * (len(graph))
max_flow = 0
while BFS(graph, source, sink, parent):
path_flow = float("Inf")
s = sink
while s != source:
# Find the minimum value in select path
path_flow = min(path_flow, graph[parent[s]][s])
s = parent[s]
max_flow += path_flow
v = sink
while v != source:
u = parent[v]
graph[u][v] -= path_flow
graph[v][u] += path_flow
v = parent[v]
return max_flow
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0],
]
source, sink = 0, 5
print(FordFulkerson(graph, source, sink))
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Python program for generating diamond pattern in Python 3.7+
# Function to print upper half of diamond (pyramid)
def floyd(n):
"""
Parameters:
n : size of pattern
"""
for i in range(0, n):
for j in range(0, n - i - 1): # printing spaces
print(" ", end="")
for k in range(0, i + 1): # printing stars
print("* ", end="")
print()
# Function to print lower half of diamond (pyramid)
def reverse_floyd(n):
"""
Parameters:
n : size of pattern
"""
for i in range(n, 0, -1):
for j in range(i, 0, -1): # printing stars
print("* ", end="")
print()
for k in range(n - i + 1, 0, -1): # printing spaces
print(" ", end="")
# Function to print complete diamond pattern of "*"
def pretty_print(n):
"""
Parameters:
n : size of pattern
"""
if n <= 0:
print(" ... .... nothing printing :(")
return
floyd(n) # upper half
reverse_floyd(n) # lower half
if __name__ == "__main__":
print(r"| /\ | |- | |- |--| |\ /| |-")
print(r"|/ \| |- |_ |_ |__| | \/ | |_")
K = 1
while K:
user_number = int(input("enter the number and , and see the magic : "))
print()
pretty_print(user_number)
K = int(input("press 0 to exit... and 1 to continue..."))
print("Good Bye...")
| # Python program for generating diamond pattern in Python 3.7+
# Function to print upper half of diamond (pyramid)
def floyd(n):
"""
Parameters:
n : size of pattern
"""
for i in range(0, n):
for j in range(0, n - i - 1): # printing spaces
print(" ", end="")
for k in range(0, i + 1): # printing stars
print("* ", end="")
print()
# Function to print lower half of diamond (pyramid)
def reverse_floyd(n):
"""
Parameters:
n : size of pattern
"""
for i in range(n, 0, -1):
for j in range(i, 0, -1): # printing stars
print("* ", end="")
print()
for k in range(n - i + 1, 0, -1): # printing spaces
print(" ", end="")
# Function to print complete diamond pattern of "*"
def pretty_print(n):
"""
Parameters:
n : size of pattern
"""
if n <= 0:
print(" ... .... nothing printing :(")
return
floyd(n) # upper half
reverse_floyd(n) # lower half
if __name__ == "__main__":
print(r"| /\ | |- | |- |--| |\ /| |-")
print(r"|/ \| |- |_ |_ |__| | \/ | |_")
K = 1
while K:
user_number = int(input("enter the number and , and see the magic : "))
print()
pretty_print(user_number)
K = int(input("press 0 to exit... and 1 to continue..."))
print("Good Bye...")
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from math import atan, cos, radians, sin, tan
from .haversine_distance import haversine_distance
def lamberts_ellipsoidal_distance(
lat1: float, lon1: float, lat2: float, lon2: float
) -> float:
"""
Calculate the shortest distance along the surface of an ellipsoid between
two points on the surface of earth given longitudes and latitudes
https://en.wikipedia.org/wiki/Geographical_distance#Lambert's_formula_for_long_lines
NOTE: This algorithm uses geodesy/haversine_distance.py to compute central angle,
sigma
Representing the earth as an ellipsoid allows us to approximate distances between
points on the surface much better than a sphere. Ellipsoidal formulas treat the
Earth as an oblate ellipsoid which means accounting for the flattening that happens
at the North and South poles. Lambert's formulae provide accuracy on the order of
10 meteres over thousands of kilometeres. Other methods can provide
millimeter-level accuracy but this is a simpler method to calculate long range
distances without increasing computational intensity.
Args:
lat1, lon1: latitude and longitude of coordinate 1
lat2, lon2: latitude and longitude of coordinate 2
Returns:
geographical distance between two points in metres
>>> from collections import namedtuple
>>> point_2d = namedtuple("point_2d", "lat lon")
>>> SAN_FRANCISCO = point_2d(37.774856, -122.424227)
>>> YOSEMITE = point_2d(37.864742, -119.537521)
>>> NEW_YORK = point_2d(40.713019, -74.012647)
>>> VENICE = point_2d(45.443012, 12.313071)
>>> f"{lamberts_ellipsoidal_distance(*SAN_FRANCISCO, *YOSEMITE):0,.0f} meters"
'254,351 meters'
>>> f"{lamberts_ellipsoidal_distance(*SAN_FRANCISCO, *NEW_YORK):0,.0f} meters"
'4,138,992 meters'
>>> f"{lamberts_ellipsoidal_distance(*SAN_FRANCISCO, *VENICE):0,.0f} meters"
'9,737,326 meters'
"""
# CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System
# Distance in metres(m)
AXIS_A = 6378137.0
AXIS_B = 6356752.314245
EQUATORIAL_RADIUS = 6378137
# Equation Parameters
# https://en.wikipedia.org/wiki/Geographical_distance#Lambert's_formula_for_long_lines
flattening = (AXIS_A - AXIS_B) / AXIS_A
# Parametric latitudes
# https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude
b_lat1 = atan((1 - flattening) * tan(radians(lat1)))
b_lat2 = atan((1 - flattening) * tan(radians(lat2)))
# Compute central angle between two points
# using haversine theta. sigma = haversine_distance / equatorial radius
sigma = haversine_distance(lat1, lon1, lat2, lon2) / EQUATORIAL_RADIUS
# Intermediate P and Q values
P_value = (b_lat1 + b_lat2) / 2
Q_value = (b_lat2 - b_lat1) / 2
# Intermediate X value
# X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2)
X_numerator = (sin(P_value) ** 2) * (cos(Q_value) ** 2)
X_demonimator = cos(sigma / 2) ** 2
X_value = (sigma - sin(sigma)) * (X_numerator / X_demonimator)
# Intermediate Y value
# Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2)
Y_numerator = (cos(P_value) ** 2) * (sin(Q_value) ** 2)
Y_denominator = sin(sigma / 2) ** 2
Y_value = (sigma + sin(sigma)) * (Y_numerator / Y_denominator)
return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (X_value + Y_value)))
if __name__ == "__main__":
import doctest
doctest.testmod()
| from math import atan, cos, radians, sin, tan
from .haversine_distance import haversine_distance
def lamberts_ellipsoidal_distance(
lat1: float, lon1: float, lat2: float, lon2: float
) -> float:
"""
Calculate the shortest distance along the surface of an ellipsoid between
two points on the surface of earth given longitudes and latitudes
https://en.wikipedia.org/wiki/Geographical_distance#Lambert's_formula_for_long_lines
NOTE: This algorithm uses geodesy/haversine_distance.py to compute central angle,
sigma
Representing the earth as an ellipsoid allows us to approximate distances between
points on the surface much better than a sphere. Ellipsoidal formulas treat the
Earth as an oblate ellipsoid which means accounting for the flattening that happens
at the North and South poles. Lambert's formulae provide accuracy on the order of
10 meteres over thousands of kilometeres. Other methods can provide
millimeter-level accuracy but this is a simpler method to calculate long range
distances without increasing computational intensity.
Args:
lat1, lon1: latitude and longitude of coordinate 1
lat2, lon2: latitude and longitude of coordinate 2
Returns:
geographical distance between two points in metres
>>> from collections import namedtuple
>>> point_2d = namedtuple("point_2d", "lat lon")
>>> SAN_FRANCISCO = point_2d(37.774856, -122.424227)
>>> YOSEMITE = point_2d(37.864742, -119.537521)
>>> NEW_YORK = point_2d(40.713019, -74.012647)
>>> VENICE = point_2d(45.443012, 12.313071)
>>> f"{lamberts_ellipsoidal_distance(*SAN_FRANCISCO, *YOSEMITE):0,.0f} meters"
'254,351 meters'
>>> f"{lamberts_ellipsoidal_distance(*SAN_FRANCISCO, *NEW_YORK):0,.0f} meters"
'4,138,992 meters'
>>> f"{lamberts_ellipsoidal_distance(*SAN_FRANCISCO, *VENICE):0,.0f} meters"
'9,737,326 meters'
"""
# CONSTANTS per WGS84 https://en.wikipedia.org/wiki/World_Geodetic_System
# Distance in metres(m)
AXIS_A = 6378137.0
AXIS_B = 6356752.314245
EQUATORIAL_RADIUS = 6378137
# Equation Parameters
# https://en.wikipedia.org/wiki/Geographical_distance#Lambert's_formula_for_long_lines
flattening = (AXIS_A - AXIS_B) / AXIS_A
# Parametric latitudes
# https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude
b_lat1 = atan((1 - flattening) * tan(radians(lat1)))
b_lat2 = atan((1 - flattening) * tan(radians(lat2)))
# Compute central angle between two points
# using haversine theta. sigma = haversine_distance / equatorial radius
sigma = haversine_distance(lat1, lon1, lat2, lon2) / EQUATORIAL_RADIUS
# Intermediate P and Q values
P_value = (b_lat1 + b_lat2) / 2
Q_value = (b_lat2 - b_lat1) / 2
# Intermediate X value
# X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2)
X_numerator = (sin(P_value) ** 2) * (cos(Q_value) ** 2)
X_demonimator = cos(sigma / 2) ** 2
X_value = (sigma - sin(sigma)) * (X_numerator / X_demonimator)
# Intermediate Y value
# Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2)
Y_numerator = (cos(P_value) ** 2) * (sin(Q_value) ** 2)
Y_denominator = sin(sigma / 2) ** 2
Y_value = (sigma + sin(sigma)) * (Y_numerator / Y_denominator)
return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (X_value + Y_value)))
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
The Mandelbrot set is the set of complex numbers "c" for which the series
"z_(n+1) = z_n * z_n + c" does not diverge, i.e. remains bounded. Thus, a
complex number "c" is a member of the Mandelbrot set if, when starting with
"z_0 = 0" and applying the iteration repeatedly, the absolute value of
"z_n" remains bounded for all "n > 0". Complex numbers can be written as
"a + b*i": "a" is the real component, usually drawn on the x-axis, and "b*i"
is the imaginary component, usually drawn on the y-axis. Most visualizations
of the Mandelbrot set use a color-coding to indicate after how many steps in
the series the numbers outside the set diverge. Images of the Mandelbrot set
exhibit an elaborate and infinitely complicated boundary that reveals
progressively ever-finer recursive detail at increasing magnifications, making
the boundary of the Mandelbrot set a fractal curve.
(description adapted from https://en.wikipedia.org/wiki/Mandelbrot_set )
(see also https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set )
"""
import colorsys
from PIL import Image # type: ignore
def get_distance(x: float, y: float, max_step: int) -> float:
"""
Return the relative distance (= step/max_step) after which the complex number
constituted by this x-y-pair diverges. Members of the Mandelbrot set do not
diverge so their distance is 1.
>>> get_distance(0, 0, 50)
1.0
>>> get_distance(0.5, 0.5, 50)
0.061224489795918366
>>> get_distance(2, 0, 50)
0.0
"""
a = x
b = y
for step in range(max_step):
a_new = a * a - b * b + x
b = 2 * a * b + y
a = a_new
# divergence happens for all complex number with an absolute value
# greater than 4
if a * a + b * b > 4:
break
return step / (max_step - 1)
def get_black_and_white_rgb(distance: float) -> tuple:
"""
Black&white color-coding that ignores the relative distance. The Mandelbrot
set is black, everything else is white.
>>> get_black_and_white_rgb(0)
(255, 255, 255)
>>> get_black_and_white_rgb(0.5)
(255, 255, 255)
>>> get_black_and_white_rgb(1)
(0, 0, 0)
"""
if distance == 1:
return (0, 0, 0)
else:
return (255, 255, 255)
def get_color_coded_rgb(distance: float) -> tuple:
"""
Color-coding taking the relative distance into account. The Mandelbrot set
is black.
>>> get_color_coded_rgb(0)
(255, 0, 0)
>>> get_color_coded_rgb(0.5)
(0, 255, 255)
>>> get_color_coded_rgb(1)
(0, 0, 0)
"""
if distance == 1:
return (0, 0, 0)
else:
return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(distance, 1, 1))
def get_image(
image_width: int = 800,
image_height: int = 600,
figure_center_x: float = -0.6,
figure_center_y: float = 0,
figure_width: float = 3.2,
max_step: int = 50,
use_distance_color_coding: bool = True,
) -> Image.Image:
"""
Function to generate the image of the Mandelbrot set. Two types of coordinates
are used: image-coordinates that refer to the pixels and figure-coordinates
that refer to the complex numbers inside and outside the Mandelbrot set. The
figure-coordinates in the arguments of this function determine which section
of the Mandelbrot set is viewed. The main area of the Mandelbrot set is
roughly between "-1.5 < x < 0.5" and "-1 < y < 1" in the figure-coordinates.
Commenting out tests that slow down pytest...
# 13.35s call fractals/mandelbrot.py::mandelbrot.get_image
# >>> get_image().load()[0,0]
(255, 0, 0)
# >>> get_image(use_distance_color_coding = False).load()[0,0]
(255, 255, 255)
"""
img = Image.new("RGB", (image_width, image_height))
pixels = img.load()
# loop through the image-coordinates
for image_x in range(image_width):
for image_y in range(image_height):
# determine the figure-coordinates based on the image-coordinates
figure_height = figure_width / image_width * image_height
figure_x = figure_center_x + (image_x / image_width - 0.5) * figure_width
figure_y = figure_center_y + (image_y / image_height - 0.5) * figure_height
distance = get_distance(figure_x, figure_y, max_step)
# color the corresponding pixel based on the selected coloring-function
if use_distance_color_coding:
pixels[image_x, image_y] = get_color_coded_rgb(distance)
else:
pixels[image_x, image_y] = get_black_and_white_rgb(distance)
return img
if __name__ == "__main__":
import doctest
doctest.testmod()
# colored version, full figure
img = get_image()
# uncomment for colored version, different section, zoomed in
# img = get_image(figure_center_x = -0.6, figure_center_y = -0.4,
# figure_width = 0.8)
# uncomment for black and white version, full figure
# img = get_image(use_distance_color_coding = False)
# uncomment to save the image
# img.save("mandelbrot.png")
img.show()
| """
The Mandelbrot set is the set of complex numbers "c" for which the series
"z_(n+1) = z_n * z_n + c" does not diverge, i.e. remains bounded. Thus, a
complex number "c" is a member of the Mandelbrot set if, when starting with
"z_0 = 0" and applying the iteration repeatedly, the absolute value of
"z_n" remains bounded for all "n > 0". Complex numbers can be written as
"a + b*i": "a" is the real component, usually drawn on the x-axis, and "b*i"
is the imaginary component, usually drawn on the y-axis. Most visualizations
of the Mandelbrot set use a color-coding to indicate after how many steps in
the series the numbers outside the set diverge. Images of the Mandelbrot set
exhibit an elaborate and infinitely complicated boundary that reveals
progressively ever-finer recursive detail at increasing magnifications, making
the boundary of the Mandelbrot set a fractal curve.
(description adapted from https://en.wikipedia.org/wiki/Mandelbrot_set )
(see also https://en.wikipedia.org/wiki/Plotting_algorithms_for_the_Mandelbrot_set )
"""
import colorsys
from PIL import Image # type: ignore
def get_distance(x: float, y: float, max_step: int) -> float:
"""
Return the relative distance (= step/max_step) after which the complex number
constituted by this x-y-pair diverges. Members of the Mandelbrot set do not
diverge so their distance is 1.
>>> get_distance(0, 0, 50)
1.0
>>> get_distance(0.5, 0.5, 50)
0.061224489795918366
>>> get_distance(2, 0, 50)
0.0
"""
a = x
b = y
for step in range(max_step):
a_new = a * a - b * b + x
b = 2 * a * b + y
a = a_new
# divergence happens for all complex number with an absolute value
# greater than 4
if a * a + b * b > 4:
break
return step / (max_step - 1)
def get_black_and_white_rgb(distance: float) -> tuple:
"""
Black&white color-coding that ignores the relative distance. The Mandelbrot
set is black, everything else is white.
>>> get_black_and_white_rgb(0)
(255, 255, 255)
>>> get_black_and_white_rgb(0.5)
(255, 255, 255)
>>> get_black_and_white_rgb(1)
(0, 0, 0)
"""
if distance == 1:
return (0, 0, 0)
else:
return (255, 255, 255)
def get_color_coded_rgb(distance: float) -> tuple:
"""
Color-coding taking the relative distance into account. The Mandelbrot set
is black.
>>> get_color_coded_rgb(0)
(255, 0, 0)
>>> get_color_coded_rgb(0.5)
(0, 255, 255)
>>> get_color_coded_rgb(1)
(0, 0, 0)
"""
if distance == 1:
return (0, 0, 0)
else:
return tuple(round(i * 255) for i in colorsys.hsv_to_rgb(distance, 1, 1))
def get_image(
image_width: int = 800,
image_height: int = 600,
figure_center_x: float = -0.6,
figure_center_y: float = 0,
figure_width: float = 3.2,
max_step: int = 50,
use_distance_color_coding: bool = True,
) -> Image.Image:
"""
Function to generate the image of the Mandelbrot set. Two types of coordinates
are used: image-coordinates that refer to the pixels and figure-coordinates
that refer to the complex numbers inside and outside the Mandelbrot set. The
figure-coordinates in the arguments of this function determine which section
of the Mandelbrot set is viewed. The main area of the Mandelbrot set is
roughly between "-1.5 < x < 0.5" and "-1 < y < 1" in the figure-coordinates.
Commenting out tests that slow down pytest...
# 13.35s call fractals/mandelbrot.py::mandelbrot.get_image
# >>> get_image().load()[0,0]
(255, 0, 0)
# >>> get_image(use_distance_color_coding = False).load()[0,0]
(255, 255, 255)
"""
img = Image.new("RGB", (image_width, image_height))
pixels = img.load()
# loop through the image-coordinates
for image_x in range(image_width):
for image_y in range(image_height):
# determine the figure-coordinates based on the image-coordinates
figure_height = figure_width / image_width * image_height
figure_x = figure_center_x + (image_x / image_width - 0.5) * figure_width
figure_y = figure_center_y + (image_y / image_height - 0.5) * figure_height
distance = get_distance(figure_x, figure_y, max_step)
# color the corresponding pixel based on the selected coloring-function
if use_distance_color_coding:
pixels[image_x, image_y] = get_color_coded_rgb(distance)
else:
pixels[image_x, image_y] = get_black_and_white_rgb(distance)
return img
if __name__ == "__main__":
import doctest
doctest.testmod()
# colored version, full figure
img = get_image()
# uncomment for colored version, different section, zoomed in
# img = get_image(figure_center_x = -0.6, figure_center_y = -0.4,
# figure_width = 0.8)
# uncomment for black and white version, full figure
# img = get_image(use_distance_color_coding = False)
# uncomment to save the image
# img.save("mandelbrot.png")
img.show()
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
This is pure Python implementation of interpolation search algorithm
"""
def interpolation_search(sorted_collection, item):
"""Pure implementation of interpolation search algorithm in Python
Be careful collection must be ascending sorted, otherwise result will be
unpredictable
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:return: index of found item or None if item is not found
"""
left = 0
right = len(sorted_collection) - 1
while left <= right:
# avoid divided by 0 during interpolation
if sorted_collection[left] == sorted_collection[right]:
if sorted_collection[left] == item:
return left
else:
return None
point = left + ((item - sorted_collection[left]) * (right - left)) // (
sorted_collection[right] - sorted_collection[left]
)
# out of range check
if point < 0 or point >= len(sorted_collection):
return None
current_item = sorted_collection[point]
if current_item == item:
return point
else:
if point < left:
right = left
left = point
elif point > right:
left = right
right = point
else:
if item < current_item:
right = point - 1
else:
left = point + 1
return None
def interpolation_search_by_recursion(sorted_collection, item, left, right):
"""Pure implementation of interpolation search algorithm in Python by recursion
Be careful collection must be ascending sorted, otherwise result will be
unpredictable
First recursion should be started with left=0 and right=(len(sorted_collection)-1)
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:return: index of found item or None if item is not found
"""
# avoid divided by 0 during interpolation
if sorted_collection[left] == sorted_collection[right]:
if sorted_collection[left] == item:
return left
else:
return None
point = left + ((item - sorted_collection[left]) * (right - left)) // (
sorted_collection[right] - sorted_collection[left]
)
# out of range check
if point < 0 or point >= len(sorted_collection):
return None
if sorted_collection[point] == item:
return point
elif point < left:
return interpolation_search_by_recursion(sorted_collection, item, point, left)
elif point > right:
return interpolation_search_by_recursion(sorted_collection, item, right, left)
else:
if sorted_collection[point] > item:
return interpolation_search_by_recursion(
sorted_collection, item, left, point - 1
)
else:
return interpolation_search_by_recursion(
sorted_collection, item, point + 1, right
)
def __assert_sorted(collection):
"""Check if collection is ascending sorted, if not - raises :py:class:`ValueError`
:param collection: collection
:return: True if collection is ascending sorted
:raise: :py:class:`ValueError` if collection is not ascending sorted
Examples:
>>> __assert_sorted([0, 1, 2, 4])
True
>>> __assert_sorted([10, -1, 5])
Traceback (most recent call last):
...
ValueError: Collection must be ascending sorted
"""
if collection != sorted(collection):
raise ValueError("Collection must be ascending sorted")
return True
if __name__ == "__main__":
import sys
"""
user_input = input('Enter numbers separated by comma:\n').strip()
collection = [int(item) for item in user_input.split(',')]
try:
__assert_sorted(collection)
except ValueError:
sys.exit('Sequence must be ascending sorted to apply interpolation search')
target_input = input('Enter a single number to be found in the list:\n')
target = int(target_input)
"""
debug = 0
if debug == 1:
collection = [10, 30, 40, 45, 50, 66, 77, 93]
try:
__assert_sorted(collection)
except ValueError:
sys.exit("Sequence must be ascending sorted to apply interpolation search")
target = 67
result = interpolation_search(collection, target)
if result is not None:
print(f"{target} found at positions: {result}")
else:
print("Not found")
| """
This is pure Python implementation of interpolation search algorithm
"""
def interpolation_search(sorted_collection, item):
"""Pure implementation of interpolation search algorithm in Python
Be careful collection must be ascending sorted, otherwise result will be
unpredictable
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:return: index of found item or None if item is not found
"""
left = 0
right = len(sorted_collection) - 1
while left <= right:
# avoid divided by 0 during interpolation
if sorted_collection[left] == sorted_collection[right]:
if sorted_collection[left] == item:
return left
else:
return None
point = left + ((item - sorted_collection[left]) * (right - left)) // (
sorted_collection[right] - sorted_collection[left]
)
# out of range check
if point < 0 or point >= len(sorted_collection):
return None
current_item = sorted_collection[point]
if current_item == item:
return point
else:
if point < left:
right = left
left = point
elif point > right:
left = right
right = point
else:
if item < current_item:
right = point - 1
else:
left = point + 1
return None
def interpolation_search_by_recursion(sorted_collection, item, left, right):
"""Pure implementation of interpolation search algorithm in Python by recursion
Be careful collection must be ascending sorted, otherwise result will be
unpredictable
First recursion should be started with left=0 and right=(len(sorted_collection)-1)
:param sorted_collection: some ascending sorted collection with comparable items
:param item: item value to search
:return: index of found item or None if item is not found
"""
# avoid divided by 0 during interpolation
if sorted_collection[left] == sorted_collection[right]:
if sorted_collection[left] == item:
return left
else:
return None
point = left + ((item - sorted_collection[left]) * (right - left)) // (
sorted_collection[right] - sorted_collection[left]
)
# out of range check
if point < 0 or point >= len(sorted_collection):
return None
if sorted_collection[point] == item:
return point
elif point < left:
return interpolation_search_by_recursion(sorted_collection, item, point, left)
elif point > right:
return interpolation_search_by_recursion(sorted_collection, item, right, left)
else:
if sorted_collection[point] > item:
return interpolation_search_by_recursion(
sorted_collection, item, left, point - 1
)
else:
return interpolation_search_by_recursion(
sorted_collection, item, point + 1, right
)
def __assert_sorted(collection):
"""Check if collection is ascending sorted, if not - raises :py:class:`ValueError`
:param collection: collection
:return: True if collection is ascending sorted
:raise: :py:class:`ValueError` if collection is not ascending sorted
Examples:
>>> __assert_sorted([0, 1, 2, 4])
True
>>> __assert_sorted([10, -1, 5])
Traceback (most recent call last):
...
ValueError: Collection must be ascending sorted
"""
if collection != sorted(collection):
raise ValueError("Collection must be ascending sorted")
return True
if __name__ == "__main__":
import sys
"""
user_input = input('Enter numbers separated by comma:\n').strip()
collection = [int(item) for item in user_input.split(',')]
try:
__assert_sorted(collection)
except ValueError:
sys.exit('Sequence must be ascending sorted to apply interpolation search')
target_input = input('Enter a single number to be found in the list:\n')
target = int(target_input)
"""
debug = 0
if debug == 1:
collection = [10, 30, 40, 45, 50, 66, 77, 93]
try:
__assert_sorted(collection)
except ValueError:
sys.exit("Sequence must be ascending sorted to apply interpolation search")
target = 67
result = interpolation_search(collection, target)
if result is not None:
print(f"{target} found at positions: {result}")
else:
print("Not found")
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Find the area of various geometric shapes
"""
from math import pi, sqrt
def surface_area_cube(side_length: float) -> float:
"""
Calculate the Surface Area of a Cube.
>>> surface_area_cube(1)
6
>>> surface_area_cube(3)
54
>>> surface_area_cube(-1)
Traceback (most recent call last):
...
ValueError: surface_area_cube() only accepts non-negative values
"""
if side_length < 0:
raise ValueError("surface_area_cube() only accepts non-negative values")
return 6 * side_length**2
def surface_area_sphere(radius: float) -> float:
"""
Calculate the Surface Area of a Sphere.
Wikipedia reference: https://en.wikipedia.org/wiki/Sphere
Formula: 4 * pi * r^2
>>> surface_area_sphere(5)
314.1592653589793
>>> surface_area_sphere(1)
12.566370614359172
>>> surface_area_sphere(-1)
Traceback (most recent call last):
...
ValueError: surface_area_sphere() only accepts non-negative values
"""
if radius < 0:
raise ValueError("surface_area_sphere() only accepts non-negative values")
return 4 * pi * radius**2
def surface_area_hemisphere(radius: float) -> float:
"""
Calculate the Surface Area of a Hemisphere.
Formula: 3 * pi * r^2
>>> surface_area_hemisphere(5)
235.61944901923448
>>> surface_area_hemisphere(1)
9.42477796076938
>>> surface_area_hemisphere(0)
0.0
>>> surface_area_hemisphere(1.1)
11.40398133253095
>>> surface_area_hemisphere(-1)
Traceback (most recent call last):
...
ValueError: surface_area_hemisphere() only accepts non-negative values
"""
if radius < 0:
raise ValueError("surface_area_hemisphere() only accepts non-negative values")
return 3 * pi * radius**2
def surface_area_cone(radius: float, height: float) -> float:
"""
Calculate the Surface Area of a Cone.
Wikipedia reference: https://en.wikipedia.org/wiki/Cone
Formula: pi * r * (r + (h ** 2 + r ** 2) ** 0.5)
>>> surface_area_cone(10, 24)
1130.9733552923256
>>> surface_area_cone(6, 8)
301.59289474462014
>>> surface_area_cone(-1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
>>> surface_area_cone(1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
>>> surface_area_cone(-1, 2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
"""
if radius < 0 or height < 0:
raise ValueError("surface_area_cone() only accepts non-negative values")
return pi * radius * (radius + (height**2 + radius**2) ** 0.5)
def surface_area_cylinder(radius: float, height: float) -> float:
"""
Calculate the Surface Area of a Cylinder.
Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder
Formula: 2 * pi * r * (h + r)
>>> surface_area_cylinder(7, 10)
747.6990515543707
>>> surface_area_cylinder(6, 8)
527.7875658030853
>>> surface_area_cylinder(-1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cylinder() only accepts non-negative values
>>> surface_area_cylinder(1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cylinder() only accepts non-negative values
>>> surface_area_cylinder(-1, 2)
Traceback (most recent call last):
...
ValueError: surface_area_cylinder() only accepts non-negative values
"""
if radius < 0 or height < 0:
raise ValueError("surface_area_cylinder() only accepts non-negative values")
return 2 * pi * radius * (height + radius)
def area_rectangle(length: float, width: float) -> float:
"""
Calculate the area of a rectangle.
>>> area_rectangle(10, 20)
200
>>> area_rectangle(-1, -2)
Traceback (most recent call last):
...
ValueError: area_rectangle() only accepts non-negative values
>>> area_rectangle(1, -2)
Traceback (most recent call last):
...
ValueError: area_rectangle() only accepts non-negative values
>>> area_rectangle(-1, 2)
Traceback (most recent call last):
...
ValueError: area_rectangle() only accepts non-negative values
"""
if length < 0 or width < 0:
raise ValueError("area_rectangle() only accepts non-negative values")
return length * width
def area_square(side_length: float) -> float:
"""
Calculate the area of a square.
>>> area_square(10)
100
>>> area_square(-1)
Traceback (most recent call last):
...
ValueError: area_square() only accepts non-negative values
"""
if side_length < 0:
raise ValueError("area_square() only accepts non-negative values")
return side_length**2
def area_triangle(base: float, height: float) -> float:
"""
Calculate the area of a triangle given the base and height.
>>> area_triangle(10, 10)
50.0
>>> area_triangle(-1, -2)
Traceback (most recent call last):
...
ValueError: area_triangle() only accepts non-negative values
>>> area_triangle(1, -2)
Traceback (most recent call last):
...
ValueError: area_triangle() only accepts non-negative values
>>> area_triangle(-1, 2)
Traceback (most recent call last):
...
ValueError: area_triangle() only accepts non-negative values
"""
if base < 0 or height < 0:
raise ValueError("area_triangle() only accepts non-negative values")
return (base * height) / 2
def area_triangle_three_sides(side1: float, side2: float, side3: float) -> float:
"""
Calculate area of triangle when the length of 3 sides are known.
This function uses Heron's formula: https://en.wikipedia.org/wiki/Heron%27s_formula
>>> area_triangle_three_sides(5, 12, 13)
30.0
>>> area_triangle_three_sides(10, 11, 12)
51.521233486786784
>>> area_triangle_three_sides(-1, -2, -1)
Traceback (most recent call last):
...
ValueError: area_triangle_three_sides() only accepts non-negative values
>>> area_triangle_three_sides(1, -2, 1)
Traceback (most recent call last):
...
ValueError: area_triangle_three_sides() only accepts non-negative values
>>> area_triangle_three_sides(2, 4, 7)
Traceback (most recent call last):
...
ValueError: Given three sides do not form a triangle
>>> area_triangle_three_sides(2, 7, 4)
Traceback (most recent call last):
...
ValueError: Given three sides do not form a triangle
>>> area_triangle_three_sides(7, 2, 4)
Traceback (most recent call last):
...
ValueError: Given three sides do not form a triangle
"""
if side1 < 0 or side2 < 0 or side3 < 0:
raise ValueError("area_triangle_three_sides() only accepts non-negative values")
elif side1 + side2 < side3 or side1 + side3 < side2 or side2 + side3 < side1:
raise ValueError("Given three sides do not form a triangle")
semi_perimeter = (side1 + side2 + side3) / 2
area = sqrt(
semi_perimeter
* (semi_perimeter - side1)
* (semi_perimeter - side2)
* (semi_perimeter - side3)
)
return area
def area_parallelogram(base: float, height: float) -> float:
"""
Calculate the area of a parallelogram.
>>> area_parallelogram(10, 20)
200
>>> area_parallelogram(-1, -2)
Traceback (most recent call last):
...
ValueError: area_parallelogram() only accepts non-negative values
>>> area_parallelogram(1, -2)
Traceback (most recent call last):
...
ValueError: area_parallelogram() only accepts non-negative values
>>> area_parallelogram(-1, 2)
Traceback (most recent call last):
...
ValueError: area_parallelogram() only accepts non-negative values
"""
if base < 0 or height < 0:
raise ValueError("area_parallelogram() only accepts non-negative values")
return base * height
def area_trapezium(base1: float, base2: float, height: float) -> float:
"""
Calculate the area of a trapezium.
>>> area_trapezium(10, 20, 30)
450.0
>>> area_trapezium(-1, -2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(-1, 2, 3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(1, -2, 3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(1, 2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(-1, -2, 3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(1, -2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(-1, 2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
"""
if base1 < 0 or base2 < 0 or height < 0:
raise ValueError("area_trapezium() only accepts non-negative values")
return 1 / 2 * (base1 + base2) * height
def area_circle(radius: float) -> float:
"""
Calculate the area of a circle.
>>> area_circle(20)
1256.6370614359173
>>> area_circle(-1)
Traceback (most recent call last):
...
ValueError: area_circle() only accepts non-negative values
"""
if radius < 0:
raise ValueError("area_circle() only accepts non-negative values")
return pi * radius**2
def area_ellipse(radius_x: float, radius_y: float) -> float:
"""
Calculate the area of a ellipse.
>>> area_ellipse(10, 10)
314.1592653589793
>>> area_ellipse(10, 20)
628.3185307179587
>>> area_ellipse(-10, 20)
Traceback (most recent call last):
...
ValueError: area_ellipse() only accepts non-negative values
>>> area_ellipse(10, -20)
Traceback (most recent call last):
...
ValueError: area_ellipse() only accepts non-negative values
>>> area_ellipse(-10, -20)
Traceback (most recent call last):
...
ValueError: area_ellipse() only accepts non-negative values
"""
if radius_x < 0 or radius_y < 0:
raise ValueError("area_ellipse() only accepts non-negative values")
return pi * radius_x * radius_y
def area_rhombus(diagonal_1: float, diagonal_2: float) -> float:
"""
Calculate the area of a rhombus.
>>> area_rhombus(10, 20)
100.0
>>> area_rhombus(-1, -2)
Traceback (most recent call last):
...
ValueError: area_rhombus() only accepts non-negative values
>>> area_rhombus(1, -2)
Traceback (most recent call last):
...
ValueError: area_rhombus() only accepts non-negative values
>>> area_rhombus(-1, 2)
Traceback (most recent call last):
...
ValueError: area_rhombus() only accepts non-negative values
"""
if diagonal_1 < 0 or diagonal_2 < 0:
raise ValueError("area_rhombus() only accepts non-negative values")
return 1 / 2 * diagonal_1 * diagonal_2
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True) # verbose so we can see methods missing tests
print("[DEMO] Areas of various geometric shapes: \n")
print(f"Rectangle: {area_rectangle(10, 20) = }")
print(f"Square: {area_square(10) = }")
print(f"Triangle: {area_triangle(10, 10) = }")
print(f"Triangle: {area_triangle_three_sides(5, 12, 13) = }")
print(f"Parallelogram: {area_parallelogram(10, 20) = }")
print(f"Rhombus: {area_rhombus(10, 20) = }")
print(f"Trapezium: {area_trapezium(10, 20, 30) = }")
print(f"Circle: {area_circle(20) = }")
print("\nSurface Areas of various geometric shapes: \n")
print(f"Cube: {surface_area_cube(20) = }")
print(f"Sphere: {surface_area_sphere(20) = }")
print(f"Hemisphere: {surface_area_hemisphere(20) = }")
print(f"Cone: {surface_area_cone(10, 20) = }")
print(f"Cylinder: {surface_area_cylinder(10, 20) = }")
| """
Find the area of various geometric shapes
"""
from math import pi, sqrt
def surface_area_cube(side_length: float) -> float:
"""
Calculate the Surface Area of a Cube.
>>> surface_area_cube(1)
6
>>> surface_area_cube(3)
54
>>> surface_area_cube(-1)
Traceback (most recent call last):
...
ValueError: surface_area_cube() only accepts non-negative values
"""
if side_length < 0:
raise ValueError("surface_area_cube() only accepts non-negative values")
return 6 * side_length**2
def surface_area_sphere(radius: float) -> float:
"""
Calculate the Surface Area of a Sphere.
Wikipedia reference: https://en.wikipedia.org/wiki/Sphere
Formula: 4 * pi * r^2
>>> surface_area_sphere(5)
314.1592653589793
>>> surface_area_sphere(1)
12.566370614359172
>>> surface_area_sphere(-1)
Traceback (most recent call last):
...
ValueError: surface_area_sphere() only accepts non-negative values
"""
if radius < 0:
raise ValueError("surface_area_sphere() only accepts non-negative values")
return 4 * pi * radius**2
def surface_area_hemisphere(radius: float) -> float:
"""
Calculate the Surface Area of a Hemisphere.
Formula: 3 * pi * r^2
>>> surface_area_hemisphere(5)
235.61944901923448
>>> surface_area_hemisphere(1)
9.42477796076938
>>> surface_area_hemisphere(0)
0.0
>>> surface_area_hemisphere(1.1)
11.40398133253095
>>> surface_area_hemisphere(-1)
Traceback (most recent call last):
...
ValueError: surface_area_hemisphere() only accepts non-negative values
"""
if radius < 0:
raise ValueError("surface_area_hemisphere() only accepts non-negative values")
return 3 * pi * radius**2
def surface_area_cone(radius: float, height: float) -> float:
"""
Calculate the Surface Area of a Cone.
Wikipedia reference: https://en.wikipedia.org/wiki/Cone
Formula: pi * r * (r + (h ** 2 + r ** 2) ** 0.5)
>>> surface_area_cone(10, 24)
1130.9733552923256
>>> surface_area_cone(6, 8)
301.59289474462014
>>> surface_area_cone(-1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
>>> surface_area_cone(1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
>>> surface_area_cone(-1, 2)
Traceback (most recent call last):
...
ValueError: surface_area_cone() only accepts non-negative values
"""
if radius < 0 or height < 0:
raise ValueError("surface_area_cone() only accepts non-negative values")
return pi * radius * (radius + (height**2 + radius**2) ** 0.5)
def surface_area_cylinder(radius: float, height: float) -> float:
"""
Calculate the Surface Area of a Cylinder.
Wikipedia reference: https://en.wikipedia.org/wiki/Cylinder
Formula: 2 * pi * r * (h + r)
>>> surface_area_cylinder(7, 10)
747.6990515543707
>>> surface_area_cylinder(6, 8)
527.7875658030853
>>> surface_area_cylinder(-1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cylinder() only accepts non-negative values
>>> surface_area_cylinder(1, -2)
Traceback (most recent call last):
...
ValueError: surface_area_cylinder() only accepts non-negative values
>>> surface_area_cylinder(-1, 2)
Traceback (most recent call last):
...
ValueError: surface_area_cylinder() only accepts non-negative values
"""
if radius < 0 or height < 0:
raise ValueError("surface_area_cylinder() only accepts non-negative values")
return 2 * pi * radius * (height + radius)
def area_rectangle(length: float, width: float) -> float:
"""
Calculate the area of a rectangle.
>>> area_rectangle(10, 20)
200
>>> area_rectangle(-1, -2)
Traceback (most recent call last):
...
ValueError: area_rectangle() only accepts non-negative values
>>> area_rectangle(1, -2)
Traceback (most recent call last):
...
ValueError: area_rectangle() only accepts non-negative values
>>> area_rectangle(-1, 2)
Traceback (most recent call last):
...
ValueError: area_rectangle() only accepts non-negative values
"""
if length < 0 or width < 0:
raise ValueError("area_rectangle() only accepts non-negative values")
return length * width
def area_square(side_length: float) -> float:
"""
Calculate the area of a square.
>>> area_square(10)
100
>>> area_square(-1)
Traceback (most recent call last):
...
ValueError: area_square() only accepts non-negative values
"""
if side_length < 0:
raise ValueError("area_square() only accepts non-negative values")
return side_length**2
def area_triangle(base: float, height: float) -> float:
"""
Calculate the area of a triangle given the base and height.
>>> area_triangle(10, 10)
50.0
>>> area_triangle(-1, -2)
Traceback (most recent call last):
...
ValueError: area_triangle() only accepts non-negative values
>>> area_triangle(1, -2)
Traceback (most recent call last):
...
ValueError: area_triangle() only accepts non-negative values
>>> area_triangle(-1, 2)
Traceback (most recent call last):
...
ValueError: area_triangle() only accepts non-negative values
"""
if base < 0 or height < 0:
raise ValueError("area_triangle() only accepts non-negative values")
return (base * height) / 2
def area_triangle_three_sides(side1: float, side2: float, side3: float) -> float:
"""
Calculate area of triangle when the length of 3 sides are known.
This function uses Heron's formula: https://en.wikipedia.org/wiki/Heron%27s_formula
>>> area_triangle_three_sides(5, 12, 13)
30.0
>>> area_triangle_three_sides(10, 11, 12)
51.521233486786784
>>> area_triangle_three_sides(-1, -2, -1)
Traceback (most recent call last):
...
ValueError: area_triangle_three_sides() only accepts non-negative values
>>> area_triangle_three_sides(1, -2, 1)
Traceback (most recent call last):
...
ValueError: area_triangle_three_sides() only accepts non-negative values
>>> area_triangle_three_sides(2, 4, 7)
Traceback (most recent call last):
...
ValueError: Given three sides do not form a triangle
>>> area_triangle_three_sides(2, 7, 4)
Traceback (most recent call last):
...
ValueError: Given three sides do not form a triangle
>>> area_triangle_three_sides(7, 2, 4)
Traceback (most recent call last):
...
ValueError: Given three sides do not form a triangle
"""
if side1 < 0 or side2 < 0 or side3 < 0:
raise ValueError("area_triangle_three_sides() only accepts non-negative values")
elif side1 + side2 < side3 or side1 + side3 < side2 or side2 + side3 < side1:
raise ValueError("Given three sides do not form a triangle")
semi_perimeter = (side1 + side2 + side3) / 2
area = sqrt(
semi_perimeter
* (semi_perimeter - side1)
* (semi_perimeter - side2)
* (semi_perimeter - side3)
)
return area
def area_parallelogram(base: float, height: float) -> float:
"""
Calculate the area of a parallelogram.
>>> area_parallelogram(10, 20)
200
>>> area_parallelogram(-1, -2)
Traceback (most recent call last):
...
ValueError: area_parallelogram() only accepts non-negative values
>>> area_parallelogram(1, -2)
Traceback (most recent call last):
...
ValueError: area_parallelogram() only accepts non-negative values
>>> area_parallelogram(-1, 2)
Traceback (most recent call last):
...
ValueError: area_parallelogram() only accepts non-negative values
"""
if base < 0 or height < 0:
raise ValueError("area_parallelogram() only accepts non-negative values")
return base * height
def area_trapezium(base1: float, base2: float, height: float) -> float:
"""
Calculate the area of a trapezium.
>>> area_trapezium(10, 20, 30)
450.0
>>> area_trapezium(-1, -2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(-1, 2, 3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(1, -2, 3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(1, 2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(-1, -2, 3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(1, -2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
>>> area_trapezium(-1, 2, -3)
Traceback (most recent call last):
...
ValueError: area_trapezium() only accepts non-negative values
"""
if base1 < 0 or base2 < 0 or height < 0:
raise ValueError("area_trapezium() only accepts non-negative values")
return 1 / 2 * (base1 + base2) * height
def area_circle(radius: float) -> float:
"""
Calculate the area of a circle.
>>> area_circle(20)
1256.6370614359173
>>> area_circle(-1)
Traceback (most recent call last):
...
ValueError: area_circle() only accepts non-negative values
"""
if radius < 0:
raise ValueError("area_circle() only accepts non-negative values")
return pi * radius**2
def area_ellipse(radius_x: float, radius_y: float) -> float:
"""
Calculate the area of a ellipse.
>>> area_ellipse(10, 10)
314.1592653589793
>>> area_ellipse(10, 20)
628.3185307179587
>>> area_ellipse(-10, 20)
Traceback (most recent call last):
...
ValueError: area_ellipse() only accepts non-negative values
>>> area_ellipse(10, -20)
Traceback (most recent call last):
...
ValueError: area_ellipse() only accepts non-negative values
>>> area_ellipse(-10, -20)
Traceback (most recent call last):
...
ValueError: area_ellipse() only accepts non-negative values
"""
if radius_x < 0 or radius_y < 0:
raise ValueError("area_ellipse() only accepts non-negative values")
return pi * radius_x * radius_y
def area_rhombus(diagonal_1: float, diagonal_2: float) -> float:
"""
Calculate the area of a rhombus.
>>> area_rhombus(10, 20)
100.0
>>> area_rhombus(-1, -2)
Traceback (most recent call last):
...
ValueError: area_rhombus() only accepts non-negative values
>>> area_rhombus(1, -2)
Traceback (most recent call last):
...
ValueError: area_rhombus() only accepts non-negative values
>>> area_rhombus(-1, 2)
Traceback (most recent call last):
...
ValueError: area_rhombus() only accepts non-negative values
"""
if diagonal_1 < 0 or diagonal_2 < 0:
raise ValueError("area_rhombus() only accepts non-negative values")
return 1 / 2 * diagonal_1 * diagonal_2
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True) # verbose so we can see methods missing tests
print("[DEMO] Areas of various geometric shapes: \n")
print(f"Rectangle: {area_rectangle(10, 20) = }")
print(f"Square: {area_square(10) = }")
print(f"Triangle: {area_triangle(10, 10) = }")
print(f"Triangle: {area_triangle_three_sides(5, 12, 13) = }")
print(f"Parallelogram: {area_parallelogram(10, 20) = }")
print(f"Rhombus: {area_rhombus(10, 20) = }")
print(f"Trapezium: {area_trapezium(10, 20, 30) = }")
print(f"Circle: {area_circle(20) = }")
print("\nSurface Areas of various geometric shapes: \n")
print(f"Cube: {surface_area_cube(20) = }")
print(f"Sphere: {surface_area_sphere(20) = }")
print(f"Hemisphere: {surface_area_hemisphere(20) = }")
print(f"Cone: {surface_area_cone(10, 20) = }")
print(f"Cylinder: {surface_area_cylinder(10, 20) = }")
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Prime permutations
Problem 49
The arithmetic sequence, 1487, 4817, 8147, in which each of
the terms increases by 3330, is unusual in two ways:
(i) each of the three terms are prime,
(ii) each of the 4-digit numbers are permutations of one another.
There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes,
exhibiting this property, but there is one other 4-digit increasing sequence.
What 12-digit number do you form by concatenating the three terms in this sequence?
Solution:
First, we need to generate all 4 digits prime numbers. Then greedy
all of them and use permutation to form new numbers. Use binary search
to check if the permutated numbers is in our prime list and include
them in a candidate list.
After that, bruteforce all passed candidates sequences using
3 nested loops since we know the answer will be 12 digits.
The bruteforce of this solution will be about 1 sec.
"""
from itertools import permutations
from math import floor, sqrt
def is_prime(number: int) -> bool:
"""
function to check whether the number is prime or not.
>>> is_prime(2)
True
>>> is_prime(6)
False
>>> is_prime(1)
False
>>> is_prime(-800)
False
>>> is_prime(104729)
True
"""
if number < 2:
return False
for i in range(2, floor(sqrt(number)) + 1):
if number % i == 0:
return False
return True
def search(target: int, prime_list: list) -> bool:
"""
function to search a number in a list using Binary Search.
>>> search(3, [1, 2, 3])
True
>>> search(4, [1, 2, 3])
False
>>> search(101, list(range(-100, 100)))
False
"""
left, right = 0, len(prime_list) - 1
while left <= right:
middle = (left + right) // 2
if prime_list[middle] == target:
return True
elif prime_list[middle] < target:
left = middle + 1
else:
right = middle - 1
return False
def solution():
"""
Return the solution of the problem.
>>> solution()
296962999629
"""
prime_list = [n for n in range(1001, 10000, 2) if is_prime(n)]
candidates = []
for number in prime_list:
tmp_numbers = []
for prime_member in permutations(list(str(number))):
prime = int("".join(prime_member))
if prime % 2 == 0:
continue
if search(prime, prime_list):
tmp_numbers.append(prime)
tmp_numbers.sort()
if len(tmp_numbers) >= 3:
candidates.append(tmp_numbers)
passed = []
for candidate in candidates:
length = len(candidate)
found = False
for i in range(length):
for j in range(i + 1, length):
for k in range(j + 1, length):
if (
abs(candidate[i] - candidate[j])
== abs(candidate[j] - candidate[k])
and len({candidate[i], candidate[j], candidate[k]}) == 3
):
passed.append(
sorted([candidate[i], candidate[j], candidate[k]])
)
found = True
if found:
break
if found:
break
if found:
break
answer = set()
for seq in passed:
answer.add("".join([str(i) for i in seq]))
return max(int(x) for x in answer)
if __name__ == "__main__":
print(solution())
| """
Prime permutations
Problem 49
The arithmetic sequence, 1487, 4817, 8147, in which each of
the terms increases by 3330, is unusual in two ways:
(i) each of the three terms are prime,
(ii) each of the 4-digit numbers are permutations of one another.
There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes,
exhibiting this property, but there is one other 4-digit increasing sequence.
What 12-digit number do you form by concatenating the three terms in this sequence?
Solution:
First, we need to generate all 4 digits prime numbers. Then greedy
all of them and use permutation to form new numbers. Use binary search
to check if the permutated numbers is in our prime list and include
them in a candidate list.
After that, bruteforce all passed candidates sequences using
3 nested loops since we know the answer will be 12 digits.
The bruteforce of this solution will be about 1 sec.
"""
from itertools import permutations
from math import floor, sqrt
def is_prime(number: int) -> bool:
"""
function to check whether the number is prime or not.
>>> is_prime(2)
True
>>> is_prime(6)
False
>>> is_prime(1)
False
>>> is_prime(-800)
False
>>> is_prime(104729)
True
"""
if number < 2:
return False
for i in range(2, floor(sqrt(number)) + 1):
if number % i == 0:
return False
return True
def search(target: int, prime_list: list) -> bool:
"""
function to search a number in a list using Binary Search.
>>> search(3, [1, 2, 3])
True
>>> search(4, [1, 2, 3])
False
>>> search(101, list(range(-100, 100)))
False
"""
left, right = 0, len(prime_list) - 1
while left <= right:
middle = (left + right) // 2
if prime_list[middle] == target:
return True
elif prime_list[middle] < target:
left = middle + 1
else:
right = middle - 1
return False
def solution():
"""
Return the solution of the problem.
>>> solution()
296962999629
"""
prime_list = [n for n in range(1001, 10000, 2) if is_prime(n)]
candidates = []
for number in prime_list:
tmp_numbers = []
for prime_member in permutations(list(str(number))):
prime = int("".join(prime_member))
if prime % 2 == 0:
continue
if search(prime, prime_list):
tmp_numbers.append(prime)
tmp_numbers.sort()
if len(tmp_numbers) >= 3:
candidates.append(tmp_numbers)
passed = []
for candidate in candidates:
length = len(candidate)
found = False
for i in range(length):
for j in range(i + 1, length):
for k in range(j + 1, length):
if (
abs(candidate[i] - candidate[j])
== abs(candidate[j] - candidate[k])
and len({candidate[i], candidate[j], candidate[k]}) == 3
):
passed.append(
sorted([candidate[i], candidate[j], candidate[k]])
)
found = True
if found:
break
if found:
break
if found:
break
answer = set()
for seq in passed:
answer.add("".join([str(i) for i in seq]))
return max(int(x) for x in answer)
if __name__ == "__main__":
print(solution())
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Functions for testing the validity of credit card numbers.
https://en.wikipedia.org/wiki/Luhn_algorithm
"""
def validate_initial_digits(credit_card_number: str) -> bool:
"""
Function to validate initial digits of a given credit card number.
>>> valid = "4111111111111111 41111111111111 34 35 37 412345 523456 634567"
>>> all(validate_initial_digits(cc) for cc in valid.split())
True
>>> invalid = "14 25 76 32323 36111111111111"
>>> all(validate_initial_digits(cc) is False for cc in invalid.split())
True
"""
return credit_card_number.startswith(("34", "35", "37", "4", "5", "6"))
def luhn_validation(credit_card_number: str) -> bool:
"""
Function to luhn algorithm validation for a given credit card number.
>>> luhn_validation('4111111111111111')
True
>>> luhn_validation('36111111111111')
True
>>> luhn_validation('41111111111111')
False
"""
cc_number = credit_card_number
total = 0
half_len = len(cc_number) - 2
for i in range(half_len, -1, -2):
# double the value of every second digit
digit = int(cc_number[i])
digit *= 2
# If doubling of a number results in a two digit number
# i.e greater than 9(e.g., 6 × 2 = 12),
# then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6),
# to get a single digit number.
if digit > 9:
digit %= 10
digit += 1
cc_number = cc_number[:i] + str(digit) + cc_number[i + 1 :]
total += digit
# Sum up the remaining digits
for i in range(len(cc_number) - 1, -1, -2):
total += int(cc_number[i])
return total % 10 == 0
def validate_credit_card_number(credit_card_number: str) -> bool:
"""
Function to validate the given credit card number.
>>> validate_credit_card_number('4111111111111111')
4111111111111111 is a valid credit card number.
True
>>> validate_credit_card_number('helloworld$')
helloworld$ is an invalid credit card number because it has nonnumerical characters.
False
>>> validate_credit_card_number('32323')
32323 is an invalid credit card number because of its length.
False
>>> validate_credit_card_number('32323323233232332323')
32323323233232332323 is an invalid credit card number because of its length.
False
>>> validate_credit_card_number('36111111111111')
36111111111111 is an invalid credit card number because of its first two digits.
False
>>> validate_credit_card_number('41111111111111')
41111111111111 is an invalid credit card number because it fails the Luhn check.
False
"""
error_message = f"{credit_card_number} is an invalid credit card number because"
if not credit_card_number.isdigit():
print(f"{error_message} it has nonnumerical characters.")
return False
if not 13 <= len(credit_card_number) <= 16:
print(f"{error_message} of its length.")
return False
if not validate_initial_digits(credit_card_number):
print(f"{error_message} of its first two digits.")
return False
if not luhn_validation(credit_card_number):
print(f"{error_message} it fails the Luhn check.")
return False
print(f"{credit_card_number} is a valid credit card number.")
return True
if __name__ == "__main__":
import doctest
doctest.testmod()
validate_credit_card_number("4111111111111111")
validate_credit_card_number("32323")
| """
Functions for testing the validity of credit card numbers.
https://en.wikipedia.org/wiki/Luhn_algorithm
"""
def validate_initial_digits(credit_card_number: str) -> bool:
"""
Function to validate initial digits of a given credit card number.
>>> valid = "4111111111111111 41111111111111 34 35 37 412345 523456 634567"
>>> all(validate_initial_digits(cc) for cc in valid.split())
True
>>> invalid = "14 25 76 32323 36111111111111"
>>> all(validate_initial_digits(cc) is False for cc in invalid.split())
True
"""
return credit_card_number.startswith(("34", "35", "37", "4", "5", "6"))
def luhn_validation(credit_card_number: str) -> bool:
"""
Function to luhn algorithm validation for a given credit card number.
>>> luhn_validation('4111111111111111')
True
>>> luhn_validation('36111111111111')
True
>>> luhn_validation('41111111111111')
False
"""
cc_number = credit_card_number
total = 0
half_len = len(cc_number) - 2
for i in range(half_len, -1, -2):
# double the value of every second digit
digit = int(cc_number[i])
digit *= 2
# If doubling of a number results in a two digit number
# i.e greater than 9(e.g., 6 × 2 = 12),
# then add the digits of the product (e.g., 12: 1 + 2 = 3, 15: 1 + 5 = 6),
# to get a single digit number.
if digit > 9:
digit %= 10
digit += 1
cc_number = cc_number[:i] + str(digit) + cc_number[i + 1 :]
total += digit
# Sum up the remaining digits
for i in range(len(cc_number) - 1, -1, -2):
total += int(cc_number[i])
return total % 10 == 0
def validate_credit_card_number(credit_card_number: str) -> bool:
"""
Function to validate the given credit card number.
>>> validate_credit_card_number('4111111111111111')
4111111111111111 is a valid credit card number.
True
>>> validate_credit_card_number('helloworld$')
helloworld$ is an invalid credit card number because it has nonnumerical characters.
False
>>> validate_credit_card_number('32323')
32323 is an invalid credit card number because of its length.
False
>>> validate_credit_card_number('32323323233232332323')
32323323233232332323 is an invalid credit card number because of its length.
False
>>> validate_credit_card_number('36111111111111')
36111111111111 is an invalid credit card number because of its first two digits.
False
>>> validate_credit_card_number('41111111111111')
41111111111111 is an invalid credit card number because it fails the Luhn check.
False
"""
error_message = f"{credit_card_number} is an invalid credit card number because"
if not credit_card_number.isdigit():
print(f"{error_message} it has nonnumerical characters.")
return False
if not 13 <= len(credit_card_number) <= 16:
print(f"{error_message} of its length.")
return False
if not validate_initial_digits(credit_card_number):
print(f"{error_message} of its first two digits.")
return False
if not luhn_validation(credit_card_number):
print(f"{error_message} it fails the Luhn check.")
return False
print(f"{credit_card_number} is a valid credit card number.")
return True
if __name__ == "__main__":
import doctest
doctest.testmod()
validate_credit_card_number("4111111111111111")
validate_credit_card_number("32323")
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| import math
def fx(x: float, a: float) -> float:
return math.pow(x, 2) - a
def fx_derivative(x: float) -> float:
return 2 * x
def get_initial_point(a: float) -> float:
start = 2.0
while start <= a:
start = math.pow(start, 2)
return start
def square_root_iterative(
a: float, max_iter: int = 9999, tolerance: float = 0.00000000000001
) -> float:
"""
Square root is aproximated using Newtons method.
https://en.wikipedia.org/wiki/Newton%27s_method
>>> all(abs(square_root_iterative(i)-math.sqrt(i)) <= .00000000000001
... for i in range(500))
True
>>> square_root_iterative(-1)
Traceback (most recent call last):
...
ValueError: math domain error
>>> square_root_iterative(4)
2.0
>>> square_root_iterative(3.2)
1.788854381999832
>>> square_root_iterative(140)
11.832159566199232
"""
if a < 0:
raise ValueError("math domain error")
value = get_initial_point(a)
for i in range(max_iter):
prev_value = value
value = value - fx(value, a) / fx_derivative(value)
if abs(prev_value - value) < tolerance:
return value
return value
if __name__ == "__main__":
from doctest import testmod
testmod()
| import math
def fx(x: float, a: float) -> float:
return math.pow(x, 2) - a
def fx_derivative(x: float) -> float:
return 2 * x
def get_initial_point(a: float) -> float:
start = 2.0
while start <= a:
start = math.pow(start, 2)
return start
def square_root_iterative(
a: float, max_iter: int = 9999, tolerance: float = 0.00000000000001
) -> float:
"""
Square root is aproximated using Newtons method.
https://en.wikipedia.org/wiki/Newton%27s_method
>>> all(abs(square_root_iterative(i)-math.sqrt(i)) <= .00000000000001
... for i in range(500))
True
>>> square_root_iterative(-1)
Traceback (most recent call last):
...
ValueError: math domain error
>>> square_root_iterative(4)
2.0
>>> square_root_iterative(3.2)
1.788854381999832
>>> square_root_iterative(140)
11.832159566199232
"""
if a < 0:
raise ValueError("math domain error")
value = get_initial_point(a)
for i in range(max_iter):
prev_value = value
value = value - fx(value, a) / fx_derivative(value)
if abs(prev_value - value) < tolerance:
return value
return value
if __name__ == "__main__":
from doctest import testmod
testmod()
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| -1 |
||
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Simple multithreaded algorithm to show how the 4 phases of a genetic algorithm works
(Evaluation, Selection, Crossover and Mutation)
https://en.wikipedia.org/wiki/Genetic_algorithm
Author: D4rkia
"""
from __future__ import annotations
import random
# Maximum size of the population. bigger could be faster but is more memory expensive
N_POPULATION = 200
# Number of elements selected in every generation for evolution the selection takes
# place from the best to the worst of that generation must be smaller than N_POPULATION
N_SELECTED = 50
# Probability that an element of a generation can mutate changing one of its genes this
# guarantees that all genes will be used during evolution
MUTATION_PROBABILITY = 0.4
# just a seed to improve randomness required by the algorithm
random.seed(random.randint(0, 1000))
def basic(target: str, genes: list[str], debug: bool = True) -> tuple[int, int, str]:
"""
Verify that the target contains no genes besides the ones inside genes variable.
>>> from string import ascii_lowercase
>>> basic("doctest", ascii_lowercase, debug=False)[2]
'doctest'
>>> genes = list(ascii_lowercase)
>>> genes.remove("e")
>>> basic("test", genes)
Traceback (most recent call last):
...
ValueError: ['e'] is not in genes list, evolution cannot converge
>>> genes.remove("s")
>>> basic("test", genes)
Traceback (most recent call last):
...
ValueError: ['e', 's'] is not in genes list, evolution cannot converge
>>> genes.remove("t")
>>> basic("test", genes)
Traceback (most recent call last):
...
ValueError: ['e', 's', 't'] is not in genes list, evolution cannot converge
"""
# Verify if N_POPULATION is bigger than N_SELECTED
if N_POPULATION < N_SELECTED:
raise ValueError(f"{N_POPULATION} must be bigger than {N_SELECTED}")
# Verify that the target contains no genes besides the ones inside genes variable.
not_in_genes_list = sorted({c for c in target if c not in genes})
if not_in_genes_list:
raise ValueError(
f"{not_in_genes_list} is not in genes list, evolution cannot converge"
)
# Generate random starting population
population = []
for _ in range(N_POPULATION):
population.append("".join([random.choice(genes) for i in range(len(target))]))
# Just some logs to know what the algorithms is doing
generation, total_population = 0, 0
# This loop will end when we will find a perfect match for our target
while True:
generation += 1
total_population += len(population)
# Random population created now it's time to evaluate
def evaluate(item: str, main_target: str = target) -> tuple[str, float]:
"""
Evaluate how similar the item is with the target by just
counting each char in the right position
>>> evaluate("Helxo Worlx", Hello World)
["Helxo Worlx", 9]
"""
score = len(
[g for position, g in enumerate(item) if g == main_target[position]]
)
return (item, float(score))
# Adding a bit of concurrency can make everything faster,
#
# import concurrent.futures
# population_score: list[tuple[str, float]] = []
# with concurrent.futures.ThreadPoolExecutor(
# max_workers=NUM_WORKERS) as executor:
# futures = {executor.submit(evaluate, item) for item in population}
# concurrent.futures.wait(futures)
# population_score = [item.result() for item in futures]
#
# but with a simple algorithm like this will probably be slower
# we just need to call evaluate for every item inside population
population_score = [evaluate(item) for item in population]
# Check if there is a matching evolution
population_score = sorted(population_score, key=lambda x: x[1], reverse=True)
if population_score[0][0] == target:
return (generation, total_population, population_score[0][0])
# Print the Best result every 10 generation
# just to know that the algorithm is working
if debug and generation % 10 == 0:
print(
f"\nGeneration: {generation}"
f"\nTotal Population:{total_population}"
f"\nBest score: {population_score[0][1]}"
f"\nBest string: {population_score[0][0]}"
)
# Flush the old population keeping some of the best evolutions
# Keeping this avoid regression of evolution
population_best = population[: int(N_POPULATION / 3)]
population.clear()
population.extend(population_best)
# Normalize population score from 0 to 1
population_score = [
(item, score / len(target)) for item, score in population_score
]
# Select, Crossover and Mutate a new population
def select(parent_1: tuple[str, float]) -> list[str]:
"""Select the second parent and generate new population"""
pop = []
# Generate more child proportionally to the fitness score
child_n = int(parent_1[1] * 100) + 1
child_n = 10 if child_n >= 10 else child_n
for _ in range(child_n):
parent_2 = population_score[random.randint(0, N_SELECTED)][0]
child_1, child_2 = crossover(parent_1[0], parent_2)
# Append new string to the population list
pop.append(mutate(child_1))
pop.append(mutate(child_2))
return pop
def crossover(parent_1: str, parent_2: str) -> tuple[str, str]:
"""Slice and combine two string in a random point"""
random_slice = random.randint(0, len(parent_1) - 1)
child_1 = parent_1[:random_slice] + parent_2[random_slice:]
child_2 = parent_2[:random_slice] + parent_1[random_slice:]
return (child_1, child_2)
def mutate(child: str) -> str:
"""Mutate a random gene of a child with another one from the list"""
child_list = list(child)
if random.uniform(0, 1) < MUTATION_PROBABILITY:
child_list[random.randint(0, len(child)) - 1] = random.choice(genes)
return "".join(child_list)
# This is Selection
for i in range(N_SELECTED):
population.extend(select(population_score[int(i)]))
# Check if the population has already reached the maximum value and if so,
# break the cycle. if this check is disabled the algorithm will take
# forever to compute large strings but will also calculate small string in
# a lot fewer generations
if len(population) > N_POPULATION:
break
if __name__ == "__main__":
target_str = (
"This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!"
)
genes_list = list(
" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm"
"nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\"
)
print(
"\nGeneration: %s\nTotal Population: %s\nTarget: %s"
% basic(target_str, genes_list)
)
| """
Simple multithreaded algorithm to show how the 4 phases of a genetic algorithm works
(Evaluation, Selection, Crossover and Mutation)
https://en.wikipedia.org/wiki/Genetic_algorithm
Author: D4rkia
"""
from __future__ import annotations
import random
# Maximum size of the population. bigger could be faster but is more memory expensive
N_POPULATION = 200
# Number of elements selected in every generation for evolution the selection takes
# place from the best to the worst of that generation must be smaller than N_POPULATION
N_SELECTED = 50
# Probability that an element of a generation can mutate changing one of its genes this
# guarantees that all genes will be used during evolution
MUTATION_PROBABILITY = 0.4
# just a seed to improve randomness required by the algorithm
random.seed(random.randint(0, 1000))
def basic(target: str, genes: list[str], debug: bool = True) -> tuple[int, int, str]:
"""
Verify that the target contains no genes besides the ones inside genes variable.
>>> from string import ascii_lowercase
>>> basic("doctest", ascii_lowercase, debug=False)[2]
'doctest'
>>> genes = list(ascii_lowercase)
>>> genes.remove("e")
>>> basic("test", genes)
Traceback (most recent call last):
...
ValueError: ['e'] is not in genes list, evolution cannot converge
>>> genes.remove("s")
>>> basic("test", genes)
Traceback (most recent call last):
...
ValueError: ['e', 's'] is not in genes list, evolution cannot converge
>>> genes.remove("t")
>>> basic("test", genes)
Traceback (most recent call last):
...
ValueError: ['e', 's', 't'] is not in genes list, evolution cannot converge
"""
# Verify if N_POPULATION is bigger than N_SELECTED
if N_POPULATION < N_SELECTED:
raise ValueError(f"{N_POPULATION} must be bigger than {N_SELECTED}")
# Verify that the target contains no genes besides the ones inside genes variable.
not_in_genes_list = sorted({c for c in target if c not in genes})
if not_in_genes_list:
raise ValueError(
f"{not_in_genes_list} is not in genes list, evolution cannot converge"
)
# Generate random starting population
population = []
for _ in range(N_POPULATION):
population.append("".join([random.choice(genes) for i in range(len(target))]))
# Just some logs to know what the algorithms is doing
generation, total_population = 0, 0
# This loop will end when we will find a perfect match for our target
while True:
generation += 1
total_population += len(population)
# Random population created now it's time to evaluate
def evaluate(item: str, main_target: str = target) -> tuple[str, float]:
"""
Evaluate how similar the item is with the target by just
counting each char in the right position
>>> evaluate("Helxo Worlx", Hello World)
["Helxo Worlx", 9]
"""
score = len(
[g for position, g in enumerate(item) if g == main_target[position]]
)
return (item, float(score))
# Adding a bit of concurrency can make everything faster,
#
# import concurrent.futures
# population_score: list[tuple[str, float]] = []
# with concurrent.futures.ThreadPoolExecutor(
# max_workers=NUM_WORKERS) as executor:
# futures = {executor.submit(evaluate, item) for item in population}
# concurrent.futures.wait(futures)
# population_score = [item.result() for item in futures]
#
# but with a simple algorithm like this will probably be slower
# we just need to call evaluate for every item inside population
population_score = [evaluate(item) for item in population]
# Check if there is a matching evolution
population_score = sorted(population_score, key=lambda x: x[1], reverse=True)
if population_score[0][0] == target:
return (generation, total_population, population_score[0][0])
# Print the Best result every 10 generation
# just to know that the algorithm is working
if debug and generation % 10 == 0:
print(
f"\nGeneration: {generation}"
f"\nTotal Population:{total_population}"
f"\nBest score: {population_score[0][1]}"
f"\nBest string: {population_score[0][0]}"
)
# Flush the old population keeping some of the best evolutions
# Keeping this avoid regression of evolution
population_best = population[: int(N_POPULATION / 3)]
population.clear()
population.extend(population_best)
# Normalize population score from 0 to 1
population_score = [
(item, score / len(target)) for item, score in population_score
]
# Select, Crossover and Mutate a new population
def select(parent_1: tuple[str, float]) -> list[str]:
"""Select the second parent and generate new population"""
pop = []
# Generate more child proportionally to the fitness score
child_n = int(parent_1[1] * 100) + 1
child_n = 10 if child_n >= 10 else child_n
for _ in range(child_n):
parent_2 = population_score[random.randint(0, N_SELECTED)][0]
child_1, child_2 = crossover(parent_1[0], parent_2)
# Append new string to the population list
pop.append(mutate(child_1))
pop.append(mutate(child_2))
return pop
def crossover(parent_1: str, parent_2: str) -> tuple[str, str]:
"""Slice and combine two string in a random point"""
random_slice = random.randint(0, len(parent_1) - 1)
child_1 = parent_1[:random_slice] + parent_2[random_slice:]
child_2 = parent_2[:random_slice] + parent_1[random_slice:]
return (child_1, child_2)
def mutate(child: str) -> str:
"""Mutate a random gene of a child with another one from the list"""
child_list = list(child)
if random.uniform(0, 1) < MUTATION_PROBABILITY:
child_list[random.randint(0, len(child)) - 1] = random.choice(genes)
return "".join(child_list)
# This is Selection
for i in range(N_SELECTED):
population.extend(select(population_score[int(i)]))
# Check if the population has already reached the maximum value and if so,
# break the cycle. if this check is disabled the algorithm will take
# forever to compute large strings but will also calculate small string in
# a lot fewer generations
if len(population) > N_POPULATION:
break
if __name__ == "__main__":
target_str = (
"This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!"
)
genes_list = list(
" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm"
"nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\"
)
print(
"\nGeneration: %s\nTotal Population: %s\nTarget: %s"
% basic(target_str, genes_list)
)
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #
| #
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| from collections import defaultdict
from graphs.minimum_spanning_tree_prims import PrimsAlgorithm as mst
def test_prim_successful_result():
num_nodes, num_edges = 9, 14 # noqa: F841
edges = [
[0, 1, 4],
[0, 7, 8],
[1, 2, 8],
[7, 8, 7],
[7, 6, 1],
[2, 8, 2],
[8, 6, 6],
[2, 3, 7],
[2, 5, 4],
[6, 5, 2],
[3, 5, 14],
[3, 4, 9],
[5, 4, 10],
[1, 7, 11],
]
adjancency = defaultdict(list)
for node1, node2, cost in edges:
adjancency[node1].append([node2, cost])
adjancency[node2].append([node1, cost])
result = mst(adjancency)
expected = [
[7, 6, 1],
[2, 8, 2],
[6, 5, 2],
[0, 1, 4],
[2, 5, 4],
[2, 3, 7],
[0, 7, 8],
[3, 4, 9],
]
for answer in expected:
edge = tuple(answer[:2])
reverse = tuple(edge[::-1])
assert edge in result or reverse in result
| from collections import defaultdict
from graphs.minimum_spanning_tree_prims import PrimsAlgorithm as mst
def test_prim_successful_result():
num_nodes, num_edges = 9, 14 # noqa: F841
edges = [
[0, 1, 4],
[0, 7, 8],
[1, 2, 8],
[7, 8, 7],
[7, 6, 1],
[2, 8, 2],
[8, 6, 6],
[2, 3, 7],
[2, 5, 4],
[6, 5, 2],
[3, 5, 14],
[3, 4, 9],
[5, 4, 10],
[1, 7, 11],
]
adjancency = defaultdict(list)
for node1, node2, cost in edges:
adjancency[node1].append([node2, cost])
adjancency[node2].append([node1, cost])
result = mst(adjancency)
expected = [
[7, 6, 1],
[2, 8, 2],
[6, 5, 2],
[0, 1, 4],
[2, 5, 4],
[2, 3, 7],
[0, 7, 8],
[3, 4, 9],
]
for answer in expected:
edge = tuple(answer[:2])
reverse = tuple(edge[::-1])
assert edge in result or reverse in result
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 64: https://projecteuler.net/problem=64
All square roots are periodic when written as continued fractions.
For example, let us consider sqrt(23).
It can be seen that the sequence is repeating.
For conciseness, we use the notation sqrt(23)=[4;(1,3,1,8)],
to indicate that the block (1,3,1,8) repeats indefinitely.
Exactly four continued fractions, for N<=13, have an odd period.
How many continued fractions for N<=10000 have an odd period?
References:
- https://en.wikipedia.org/wiki/Continued_fraction
"""
from math import floor, sqrt
def continuous_fraction_period(n: int) -> int:
"""
Returns the continued fraction period of a number n.
>>> continuous_fraction_period(2)
1
>>> continuous_fraction_period(5)
1
>>> continuous_fraction_period(7)
4
>>> continuous_fraction_period(11)
2
>>> continuous_fraction_period(13)
5
"""
numerator = 0.0
denominator = 1.0
ROOT = int(sqrt(n))
integer_part = ROOT
period = 0
while integer_part != 2 * ROOT:
numerator = denominator * integer_part - numerator
denominator = (n - numerator**2) / denominator
integer_part = int((ROOT + numerator) / denominator)
period += 1
return period
def solution(n: int = 10000) -> int:
"""
Returns the count of numbers <= 10000 with odd periods.
This function calls continuous_fraction_period for numbers which are
not perfect squares.
This is checked in if sr - floor(sr) != 0 statement.
If an odd period is returned by continuous_fraction_period,
count_odd_periods is increased by 1.
>>> solution(2)
1
>>> solution(5)
2
>>> solution(7)
2
>>> solution(11)
3
>>> solution(13)
4
"""
count_odd_periods = 0
for i in range(2, n + 1):
sr = sqrt(i)
if sr - floor(sr) != 0:
if continuous_fraction_period(i) % 2 == 1:
count_odd_periods += 1
return count_odd_periods
if __name__ == "__main__":
print(f"{solution(int(input().strip()))}")
| """
Project Euler Problem 64: https://projecteuler.net/problem=64
All square roots are periodic when written as continued fractions.
For example, let us consider sqrt(23).
It can be seen that the sequence is repeating.
For conciseness, we use the notation sqrt(23)=[4;(1,3,1,8)],
to indicate that the block (1,3,1,8) repeats indefinitely.
Exactly four continued fractions, for N<=13, have an odd period.
How many continued fractions for N<=10000 have an odd period?
References:
- https://en.wikipedia.org/wiki/Continued_fraction
"""
from math import floor, sqrt
def continuous_fraction_period(n: int) -> int:
"""
Returns the continued fraction period of a number n.
>>> continuous_fraction_period(2)
1
>>> continuous_fraction_period(5)
1
>>> continuous_fraction_period(7)
4
>>> continuous_fraction_period(11)
2
>>> continuous_fraction_period(13)
5
"""
numerator = 0.0
denominator = 1.0
ROOT = int(sqrt(n))
integer_part = ROOT
period = 0
while integer_part != 2 * ROOT:
numerator = denominator * integer_part - numerator
denominator = (n - numerator**2) / denominator
integer_part = int((ROOT + numerator) / denominator)
period += 1
return period
def solution(n: int = 10000) -> int:
"""
Returns the count of numbers <= 10000 with odd periods.
This function calls continuous_fraction_period for numbers which are
not perfect squares.
This is checked in if sr - floor(sr) != 0 statement.
If an odd period is returned by continuous_fraction_period,
count_odd_periods is increased by 1.
>>> solution(2)
1
>>> solution(5)
2
>>> solution(7)
2
>>> solution(11)
3
>>> solution(13)
4
"""
count_odd_periods = 0
for i in range(2, n + 1):
sr = sqrt(i)
if sr - floor(sr) != 0:
if continuous_fraction_period(i) % 2 == 1:
count_odd_periods += 1
return count_odd_periods
if __name__ == "__main__":
print(f"{solution(int(input().strip()))}")
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
https://en.wikipedia.org/wiki/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 | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
Project Euler Problem 6: https://projecteuler.net/problem=6
Sum square difference
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one
hundred natural numbers and the square of the sum.
"""
def solution(n: int = 100) -> int:
"""
Returns the difference between the sum of the squares of the first n
natural numbers and the square of the sum.
>>> solution(10)
2640
>>> solution(15)
13160
>>> solution(20)
41230
>>> solution(50)
1582700
"""
sum_cubes = (n * (n + 1) // 2) ** 2
sum_squares = n * (n + 1) * (2 * n + 1) // 6
return sum_cubes - sum_squares
if __name__ == "__main__":
print(f"{solution() = }")
| """
Project Euler Problem 6: https://projecteuler.net/problem=6
Sum square difference
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten
natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one
hundred natural numbers and the square of the sum.
"""
def solution(n: int = 100) -> int:
"""
Returns the difference between the sum of the squares of the first n
natural numbers and the square of the sum.
>>> solution(10)
2640
>>> solution(15)
13160
>>> solution(20)
41230
>>> solution(50)
1582700
"""
sum_cubes = (n * (n + 1) // 2) ** 2
sum_squares = n * (n + 1) * (2 * n + 1) // 6
return sum_cubes - sum_squares
if __name__ == "__main__":
print(f"{solution() = }")
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| # Information on 2's complement: https://en.wikipedia.org/wiki/Two%27s_complement
def twos_complement(number: int) -> str:
"""
Take in a negative integer 'number'.
Return the two's complement representation of 'number'.
>>> twos_complement(0)
'0b0'
>>> twos_complement(-1)
'0b11'
>>> twos_complement(-5)
'0b1011'
>>> twos_complement(-17)
'0b101111'
>>> twos_complement(-207)
'0b100110001'
>>> twos_complement(1)
Traceback (most recent call last):
...
ValueError: input must be a negative integer
"""
if number > 0:
raise ValueError("input must be a negative integer")
binary_number_length = len(bin(number)[3:])
twos_complement_number = bin(abs(number) - (1 << binary_number_length))[3:]
twos_complement_number = (
(
"1"
+ "0" * (binary_number_length - len(twos_complement_number))
+ twos_complement_number
)
if number < 0
else "0"
)
return "0b" + twos_complement_number
if __name__ == "__main__":
import doctest
doctest.testmod()
| # Information on 2's complement: https://en.wikipedia.org/wiki/Two%27s_complement
def twos_complement(number: int) -> str:
"""
Take in a negative integer 'number'.
Return the two's complement representation of 'number'.
>>> twos_complement(0)
'0b0'
>>> twos_complement(-1)
'0b11'
>>> twos_complement(-5)
'0b1011'
>>> twos_complement(-17)
'0b101111'
>>> twos_complement(-207)
'0b100110001'
>>> twos_complement(1)
Traceback (most recent call last):
...
ValueError: input must be a negative integer
"""
if number > 0:
raise ValueError("input must be a negative integer")
binary_number_length = len(bin(number)[3:])
twos_complement_number = bin(abs(number) - (1 << binary_number_length))[3:]
twos_complement_number = (
(
"1"
+ "0" * (binary_number_length - len(twos_complement_number))
+ twos_complement_number
)
if number < 0
else "0"
)
return "0b" + twos_complement_number
if __name__ == "__main__":
import doctest
doctest.testmod()
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| #!/usr/bin/env python3
from __future__ import annotations
import json
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
headers = {"UserAgent": UserAgent().random}
def extract_user_profile(script) -> dict:
"""
May raise json.decoder.JSONDecodeError
"""
data = script.contents[0]
info = json.loads(data[data.find('{"config"') : -1])
return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]
class InstagramUser:
"""
Class Instagram crawl instagram user information
Usage: (doctest failing on GitHub Actions)
# >>> instagram_user = InstagramUser("github")
# >>> instagram_user.is_verified
True
# >>> instagram_user.biography
'Built for developers.'
"""
def __init__(self, username):
self.url = f"https://www.instagram.com/{username}/"
self.user_data = self.get_json()
def get_json(self) -> dict:
"""
Return a dict of user information
"""
html = requests.get(self.url, headers=headers).text
scripts = BeautifulSoup(html, "html.parser").find_all("script")
try:
return extract_user_profile(scripts[4])
except (json.decoder.JSONDecodeError, KeyError):
return extract_user_profile(scripts[3])
def __repr__(self) -> str:
return f"{self.__class__.__name__}('{self.username}')"
def __str__(self) -> str:
return f"{self.fullname} ({self.username}) is {self.biography}"
@property
def username(self) -> str:
return self.user_data["username"]
@property
def fullname(self) -> str:
return self.user_data["full_name"]
@property
def biography(self) -> str:
return self.user_data["biography"]
@property
def email(self) -> str:
return self.user_data["business_email"]
@property
def website(self) -> str:
return self.user_data["external_url"]
@property
def number_of_followers(self) -> int:
return self.user_data["edge_followed_by"]["count"]
@property
def number_of_followings(self) -> int:
return self.user_data["edge_follow"]["count"]
@property
def number_of_posts(self) -> int:
return self.user_data["edge_owner_to_timeline_media"]["count"]
@property
def profile_picture_url(self) -> str:
return self.user_data["profile_pic_url_hd"]
@property
def is_verified(self) -> bool:
return self.user_data["is_verified"]
@property
def is_private(self) -> bool:
return self.user_data["is_private"]
def test_instagram_user(username: str = "github") -> None:
"""
A self running doctest
>>> test_instagram_user()
"""
import os
if os.environ.get("CI"):
return None # test failing on GitHub Actions
instagram_user = InstagramUser(username)
assert instagram_user.user_data
assert isinstance(instagram_user.user_data, dict)
assert instagram_user.username == username
if username != "github":
return
assert instagram_user.fullname == "GitHub"
assert instagram_user.biography == "Built for developers."
assert instagram_user.number_of_posts > 150
assert instagram_user.number_of_followers > 120000
assert instagram_user.number_of_followings > 15
assert instagram_user.email == "[email protected]"
assert instagram_user.website == "https://github.com/readme"
assert instagram_user.profile_picture_url.startswith("https://instagram.")
assert instagram_user.is_verified is True
assert instagram_user.is_private is False
if __name__ == "__main__":
import doctest
doctest.testmod()
instagram_user = InstagramUser("github")
print(instagram_user)
print(f"{instagram_user.number_of_posts = }")
print(f"{instagram_user.number_of_followers = }")
print(f"{instagram_user.number_of_followings = }")
print(f"{instagram_user.email = }")
print(f"{instagram_user.website = }")
print(f"{instagram_user.profile_picture_url = }")
print(f"{instagram_user.is_verified = }")
print(f"{instagram_user.is_private = }")
| #!/usr/bin/env python3
from __future__ import annotations
import json
import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
headers = {"UserAgent": UserAgent().random}
def extract_user_profile(script) -> dict:
"""
May raise json.decoder.JSONDecodeError
"""
data = script.contents[0]
info = json.loads(data[data.find('{"config"') : -1])
return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]
class InstagramUser:
"""
Class Instagram crawl instagram user information
Usage: (doctest failing on GitHub Actions)
# >>> instagram_user = InstagramUser("github")
# >>> instagram_user.is_verified
True
# >>> instagram_user.biography
'Built for developers.'
"""
def __init__(self, username):
self.url = f"https://www.instagram.com/{username}/"
self.user_data = self.get_json()
def get_json(self) -> dict:
"""
Return a dict of user information
"""
html = requests.get(self.url, headers=headers).text
scripts = BeautifulSoup(html, "html.parser").find_all("script")
try:
return extract_user_profile(scripts[4])
except (json.decoder.JSONDecodeError, KeyError):
return extract_user_profile(scripts[3])
def __repr__(self) -> str:
return f"{self.__class__.__name__}('{self.username}')"
def __str__(self) -> str:
return f"{self.fullname} ({self.username}) is {self.biography}"
@property
def username(self) -> str:
return self.user_data["username"]
@property
def fullname(self) -> str:
return self.user_data["full_name"]
@property
def biography(self) -> str:
return self.user_data["biography"]
@property
def email(self) -> str:
return self.user_data["business_email"]
@property
def website(self) -> str:
return self.user_data["external_url"]
@property
def number_of_followers(self) -> int:
return self.user_data["edge_followed_by"]["count"]
@property
def number_of_followings(self) -> int:
return self.user_data["edge_follow"]["count"]
@property
def number_of_posts(self) -> int:
return self.user_data["edge_owner_to_timeline_media"]["count"]
@property
def profile_picture_url(self) -> str:
return self.user_data["profile_pic_url_hd"]
@property
def is_verified(self) -> bool:
return self.user_data["is_verified"]
@property
def is_private(self) -> bool:
return self.user_data["is_private"]
def test_instagram_user(username: str = "github") -> None:
"""
A self running doctest
>>> test_instagram_user()
"""
import os
if os.environ.get("CI"):
return None # test failing on GitHub Actions
instagram_user = InstagramUser(username)
assert instagram_user.user_data
assert isinstance(instagram_user.user_data, dict)
assert instagram_user.username == username
if username != "github":
return
assert instagram_user.fullname == "GitHub"
assert instagram_user.biography == "Built for developers."
assert instagram_user.number_of_posts > 150
assert instagram_user.number_of_followers > 120000
assert instagram_user.number_of_followings > 15
assert instagram_user.email == "[email protected]"
assert instagram_user.website == "https://github.com/readme"
assert instagram_user.profile_picture_url.startswith("https://instagram.")
assert instagram_user.is_verified is True
assert instagram_user.is_private is False
if __name__ == "__main__":
import doctest
doctest.testmod()
instagram_user = InstagramUser("github")
print(instagram_user)
print(f"{instagram_user.number_of_posts = }")
print(f"{instagram_user.number_of_followers = }")
print(f"{instagram_user.number_of_followings = }")
print(f"{instagram_user.email = }")
print(f"{instagram_user.website = }")
print(f"{instagram_user.profile_picture_url = }")
print(f"{instagram_user.is_verified = }")
print(f"{instagram_user.is_private = }")
| -1 |
TheAlgorithms/Python | 6,228 | Unify primality checking | ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| ngiachou | "2022-07-04T00:02:14Z" | "2022-07-11T14:36:58Z" | dad789d9034ea6fb183bddb1a34b6b89d379e422 | f7c58e4c4b66750cbb3afd9ad29e9c246b2480ab | Unify primality checking. ### Describe your change:
I refactored some functions in order to fix #5434. More specifically,
1. I changed the name of some function in order to agree with naming conventions.
2. I changed the implementation of a primality checking function in order to have a `O(sqrt(n))` time complexity algorithm.
There are some more functions that are related to primality checking namely the [lucas_lehmer_primality_test.py](https://github.com/TheAlgorithms/Python/blob/master/maths/lucas_lehmer_primality_test.py) and [miller_rabin.py](https://github.com/TheAlgorithms/Python/blob/master/maths/miller_rabin.py) but I did not change these since they are specific algorithms.
I have searched for every mention of the word `prime` in all of the files and except from the [project_euler](https://github.com/TheAlgorithms/Python/tree/master/project_euler) I think that there are no other mentions on the primality testing subject.
* [ ] Add an algorithm?
* [x] Fix a bug or typo in an existing algorithm?
* [ ] Documentation change?
### Checklist:
* [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md).
* [x] This pull request is all my own work -- I have not plagiarized.
* [x] I know that pull requests will not be merged if they fail the automated tests.
* [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
* [ ] All new Python files are placed inside an existing directory.
* [ ] All filenames are in all lowercase characters with no spaces or dashes.
* [ ] All functions and variable names follow Python naming conventions.
* [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html).
* [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing.
* [ ] All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
* [ ] If this pull request resolves one or more open issues then the commit message contains `Fixes: #{$ISSUE_NO}`.
| """
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000
digits?
"""
def fibonacci(n: int) -> int:
"""
Computes the Fibonacci number for input n by iterating through n numbers
and creating an array of ints using the Fibonacci formula.
Returns the nth element of the array.
>>> fibonacci(2)
1
>>> fibonacci(3)
2
>>> fibonacci(5)
5
>>> fibonacci(10)
55
>>> fibonacci(12)
144
"""
if n == 1 or type(n) is not int:
return 0
elif n == 2:
return 1
else:
sequence = [0, 1]
for i in range(2, n + 1):
sequence.append(sequence[i - 1] + sequence[i - 2])
return sequence[n]
def fibonacci_digits_index(n: int) -> int:
"""
Computes incrementing Fibonacci numbers starting from 3 until the length
of the resulting Fibonacci result is the input value n. Returns the term
of the Fibonacci sequence where this occurs.
>>> fibonacci_digits_index(1000)
4782
>>> fibonacci_digits_index(100)
476
>>> fibonacci_digits_index(50)
237
>>> fibonacci_digits_index(3)
12
"""
digits = 0
index = 2
while digits < n:
index += 1
digits = len(str(fibonacci(index)))
return index
def solution(n: int = 1000) -> int:
"""
Returns the index of the first term in the Fibonacci sequence to contain
n digits.
>>> solution(1000)
4782
>>> solution(100)
476
>>> solution(50)
237
>>> solution(3)
12
"""
return fibonacci_digits_index(n)
if __name__ == "__main__":
print(solution(int(str(input()).strip())))
| """
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000
digits?
"""
def fibonacci(n: int) -> int:
"""
Computes the Fibonacci number for input n by iterating through n numbers
and creating an array of ints using the Fibonacci formula.
Returns the nth element of the array.
>>> fibonacci(2)
1
>>> fibonacci(3)
2
>>> fibonacci(5)
5
>>> fibonacci(10)
55
>>> fibonacci(12)
144
"""
if n == 1 or type(n) is not int:
return 0
elif n == 2:
return 1
else:
sequence = [0, 1]
for i in range(2, n + 1):
sequence.append(sequence[i - 1] + sequence[i - 2])
return sequence[n]
def fibonacci_digits_index(n: int) -> int:
"""
Computes incrementing Fibonacci numbers starting from 3 until the length
of the resulting Fibonacci result is the input value n. Returns the term
of the Fibonacci sequence where this occurs.
>>> fibonacci_digits_index(1000)
4782
>>> fibonacci_digits_index(100)
476
>>> fibonacci_digits_index(50)
237
>>> fibonacci_digits_index(3)
12
"""
digits = 0
index = 2
while digits < n:
index += 1
digits = len(str(fibonacci(index)))
return index
def solution(n: int = 1000) -> int:
"""
Returns the index of the first term in the Fibonacci sequence to contain
n digits.
>>> solution(1000)
4782
>>> solution(100)
476
>>> solution(50)
237
>>> solution(3)
12
"""
return fibonacci_digits_index(n)
if __name__ == "__main__":
print(solution(int(str(input()).strip())))
| -1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.