repo_name
stringclasses
1 value
pr_number
int64
4.12k
11.2k
pr_title
stringlengths
9
107
pr_description
stringlengths
107
5.48k
author
stringlengths
4
18
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
118
5.52k
before_content
stringlengths
0
7.93M
after_content
stringlengths
0
7.93M
label
int64
-1
1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" python/black : True """ from __future__ import annotations def prime_factors(n: int) -> list[int]: """ Returns prime factors of n as a list. >>> prime_factors(0) [] >>> prime_factors(100) [2, 2, 5, 5] >>> prime_factors(2560) [2, 2, 2, 2, 2, 2, 2, 2, 2, 5] >>> prime_factors(10**-2) [] >>> prime_factors(0.02) [] >>> x = prime_factors(10**241) # doctest: +NORMALIZE_WHITESPACE >>> x == [2]*241 + [5]*241 True >>> prime_factors(10**-354) [] >>> prime_factors('hello') Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'str' >>> prime_factors([1,2,'hello']) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'list' """ i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors if __name__ == "__main__": import doctest doctest.testmod()
""" python/black : True """ from __future__ import annotations def prime_factors(n: int) -> list[int]: """ Returns prime factors of n as a list. >>> prime_factors(0) [] >>> prime_factors(100) [2, 2, 5, 5] >>> prime_factors(2560) [2, 2, 2, 2, 2, 2, 2, 2, 2, 5] >>> prime_factors(10**-2) [] >>> prime_factors(0.02) [] >>> x = prime_factors(10**241) # doctest: +NORMALIZE_WHITESPACE >>> x == [2]*241 + [5]*241 True >>> prime_factors(10**-354) [] >>> prime_factors('hello') Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'str' >>> prime_factors([1,2,'hello']) Traceback (most recent call last): ... TypeError: '<=' not supported between instances of 'int' and 'list' """ i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# Python program to show the usage of Fermat's little theorem in a division # According to Fermat's little theorem, (a / b) mod p always equals # a * (b ^ (p - 2)) mod p # Here we assume that p is a prime number, b divides a, and p doesn't divide b # Wikipedia reference: https://en.wikipedia.org/wiki/Fermat%27s_little_theorem def binary_exponentiation(a, n, mod): if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(a, n - 1, mod) * a) % mod else: b = binary_exponentiation(a, n / 2, mod) return (b * b) % mod # a prime number p = 701 a = 1000000000 b = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) # using Python operators: print((a / b) % p == (a * b ** (p - 2)) % p)
# Python program to show the usage of Fermat's little theorem in a division # According to Fermat's little theorem, (a / b) mod p always equals # a * (b ^ (p - 2)) mod p # Here we assume that p is a prime number, b divides a, and p doesn't divide b # Wikipedia reference: https://en.wikipedia.org/wiki/Fermat%27s_little_theorem def binary_exponentiation(a, n, mod): if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(a, n - 1, mod) * a) % mod else: b = binary_exponentiation(a, n / 2, mod) return (b * b) % mod # a prime number p = 701 a = 1000000000 b = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) # using Python operators: print((a / b) % p == (a * b ** (p - 2)) % p)
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" 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 """ a = 3 result = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 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 """ a = 3 result = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from collections import deque from .hash_table import HashTable class HashTableWithLinkedList(HashTable): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _set_value(self, key, data): self.values[key] = deque([]) if self.values[key] is None else self.values[key] self.values[key].appendleft(data) self._keys[key] = self.values[key] def balanced_factor(self): return ( sum(self.charge_factor - len(slot) for slot in self.values) / self.size_table * self.charge_factor ) def _collision_resolution(self, key, data=None): if not ( len(self.values[key]) == self.charge_factor and self.values.count(None) == 0 ): return key return super()._collision_resolution(key, data)
from collections import deque from .hash_table import HashTable class HashTableWithLinkedList(HashTable): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def _set_value(self, key, data): self.values[key] = deque([]) if self.values[key] is None else self.values[key] self.values[key].appendleft(data) self._keys[key] = self.values[key] def balanced_factor(self): return ( sum(self.charge_factor - len(slot) for slot in self.values) / self.size_table * self.charge_factor ) def _collision_resolution(self, key, data=None): if not ( len(self.values[key]) == self.charge_factor and self.values.count(None) == 0 ): return key return super()._collision_resolution(key, data)
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# dodecahedron.py """ A regular dodecahedron is a three-dimensional figure made up of 12 pentagon faces having the same equal size. """ def dodecahedron_surface_area(edge: float) -> float: """ Calculates the surface area of a regular dodecahedron a = 3 * ((25 + 10 * (5** (1 / 2))) ** (1 / 2 )) * (e**2) where: a --> is the area of the dodecahedron e --> is the length of the edge reference-->"Dodecahedron" Study.com <https://study.com/academy/lesson/dodecahedron-volume-surface-area-formulas.html> :param edge: length of the edge of the dodecahedron :type edge: float :return: the surface area of the dodecahedron as a float Tests: >>> dodecahedron_surface_area(5) 516.1432201766901 >>> dodecahedron_surface_area(10) 2064.5728807067603 >>> dodecahedron_surface_area(-1) Traceback (most recent call last): ... ValueError: Length must be a positive. """ if edge <= 0 or not isinstance(edge, int): raise ValueError("Length must be a positive.") return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def dodecahedron_volume(edge: float) -> float: """ Calculates the volume of a regular dodecahedron v = ((15 + (7 * (5** (1 / 2)))) / 4) * (e**3) where: v --> is the volume of the dodecahedron e --> is the length of the edge reference-->"Dodecahedron" Study.com <https://study.com/academy/lesson/dodecahedron-volume-surface-area-formulas.html> :param edge: length of the edge of the dodecahedron :type edge: float :return: the volume of the dodecahedron as a float Tests: >>> dodecahedron_volume(5) 957.8898700780791 >>> dodecahedron_volume(10) 7663.118960624633 >>> dodecahedron_volume(-1) Traceback (most recent call last): ... ValueError: Length must be a positive. """ if edge <= 0 or not isinstance(edge, int): raise ValueError("Length must be a positive.") return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
# dodecahedron.py """ A regular dodecahedron is a three-dimensional figure made up of 12 pentagon faces having the same equal size. """ def dodecahedron_surface_area(edge: float) -> float: """ Calculates the surface area of a regular dodecahedron a = 3 * ((25 + 10 * (5** (1 / 2))) ** (1 / 2 )) * (e**2) where: a --> is the area of the dodecahedron e --> is the length of the edge reference-->"Dodecahedron" Study.com <https://study.com/academy/lesson/dodecahedron-volume-surface-area-formulas.html> :param edge: length of the edge of the dodecahedron :type edge: float :return: the surface area of the dodecahedron as a float Tests: >>> dodecahedron_surface_area(5) 516.1432201766901 >>> dodecahedron_surface_area(10) 2064.5728807067603 >>> dodecahedron_surface_area(-1) Traceback (most recent call last): ... ValueError: Length must be a positive. """ if edge <= 0 or not isinstance(edge, int): raise ValueError("Length must be a positive.") return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def dodecahedron_volume(edge: float) -> float: """ Calculates the volume of a regular dodecahedron v = ((15 + (7 * (5** (1 / 2)))) / 4) * (e**3) where: v --> is the volume of the dodecahedron e --> is the length of the edge reference-->"Dodecahedron" Study.com <https://study.com/academy/lesson/dodecahedron-volume-surface-area-formulas.html> :param edge: length of the edge of the dodecahedron :type edge: float :return: the volume of the dodecahedron as a float Tests: >>> dodecahedron_volume(5) 957.8898700780791 >>> dodecahedron_volume(10) 7663.118960624633 >>> dodecahedron_volume(-1) Traceback (most recent call last): ... ValueError: Length must be a positive. """ if edge <= 0 or not isinstance(edge, int): raise ValueError("Length must be a positive.") return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
def gray_code(bit_count: int) -> list: """ Takes in an integer n and returns a n-bit gray code sequence An n-bit gray code sequence is a sequence of 2^n integers where: a) Every integer is between [0,2^n -1] inclusive b) The sequence begins with 0 c) An integer appears at most one times in the sequence d)The binary representation of every pair of integers differ by exactly one bit e) The binary representation of first and last bit also differ by exactly one bit >>> gray_code(2) [0, 1, 3, 2] >>> gray_code(1) [0, 1] >>> gray_code(3) [0, 1, 3, 2, 6, 7, 5, 4] >>> gray_code(-1) Traceback (most recent call last): ... ValueError: The given input must be positive >>> gray_code(10.6) Traceback (most recent call last): ... TypeError: unsupported operand type(s) for <<: 'int' and 'float' """ # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("The given input must be positive") # get the generated string sequence sequence = gray_code_sequence_string(bit_count) # # convert them to integers for i in range(len(sequence)): sequence[i] = int(sequence[i], 2) return sequence def gray_code_sequence_string(bit_count: int) -> list: """ Will output the n-bit grey sequence as a string of bits >>> gray_code_sequence_string(2) ['00', '01', '11', '10'] >>> gray_code_sequence_string(1) ['0', '1'] """ # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] seq_len = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits smaller_sequence = gray_code_sequence_string(bit_count - 1) sequence = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2): generated_no = "0" + smaller_sequence[i] sequence.append(generated_no) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2)): generated_no = "1" + smaller_sequence[i] sequence.append(generated_no) return sequence if __name__ == "__main__": import doctest doctest.testmod()
def gray_code(bit_count: int) -> list: """ Takes in an integer n and returns a n-bit gray code sequence An n-bit gray code sequence is a sequence of 2^n integers where: a) Every integer is between [0,2^n -1] inclusive b) The sequence begins with 0 c) An integer appears at most one times in the sequence d)The binary representation of every pair of integers differ by exactly one bit e) The binary representation of first and last bit also differ by exactly one bit >>> gray_code(2) [0, 1, 3, 2] >>> gray_code(1) [0, 1] >>> gray_code(3) [0, 1, 3, 2, 6, 7, 5, 4] >>> gray_code(-1) Traceback (most recent call last): ... ValueError: The given input must be positive >>> gray_code(10.6) Traceback (most recent call last): ... TypeError: unsupported operand type(s) for <<: 'int' and 'float' """ # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError("The given input must be positive") # get the generated string sequence sequence = gray_code_sequence_string(bit_count) # # convert them to integers for i in range(len(sequence)): sequence[i] = int(sequence[i], 2) return sequence def gray_code_sequence_string(bit_count: int) -> list: """ Will output the n-bit grey sequence as a string of bits >>> gray_code_sequence_string(2) ['00', '01', '11', '10'] >>> gray_code_sequence_string(1) ['0', '1'] """ # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] seq_len = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits smaller_sequence = gray_code_sequence_string(bit_count - 1) sequence = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2): generated_no = "0" + smaller_sequence[i] sequence.append(generated_no) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2)): generated_no = "1" + smaller_sequence[i] sequence.append(generated_no) return sequence if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that only the integer weights 0-1 knapsack problem is solvable using dynamic programming. """ def mf_knapsack(i, wt, val, j): """ This code involves the concept of memory functions. Here we solve the subproblems which are needed unlike the below example F is a 2D array with -1s filled up """ global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: val = mf_knapsack(i - 1, wt, val, j) else: val = max( mf_knapsack(i - 1, wt, val, j), mf_knapsack(i - 1, wt, val, j - wt[i - 1]) + val[i - 1], ) f[i][j] = val return f[i][j] def knapsack(w, wt, val, n): dp = [[0] * (w + 1) for _ in range(n + 1)] for i in range(1, n + 1): for w_ in range(1, w + 1): if wt[i - 1] <= w_: dp[i][w_] = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]], dp[i - 1][w_]) else: dp[i][w_] = dp[i - 1][w_] return dp[n][w_], dp def knapsack_with_example_solution(w: int, wt: list, val: list): """ Solves the integer weights knapsack problem returns one of the several possible optimal subsets. Parameters --------- W: int, the total maximum weight for the given knapsack problem. wt: list, the vector of weights for all items where wt[i] is the weight of the i-th item. val: list, the vector of values for all items where val[i] is the value of the i-th item Returns ------- optimal_val: float, the optimal value for the given knapsack problem example_optional_set: set, the indices of one of the optimal subsets which gave rise to the optimal value. Examples ------- >>> knapsack_with_example_solution(10, [1, 3, 5, 2], [10, 20, 100, 22]) (142, {2, 3, 4}) >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4, 4]) (8, {3, 4}) >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4]) Traceback (most recent call last): ... ValueError: The number of weights must be the same as the number of values. But got 4 weights and 3 values """ if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))): raise ValueError( "Both the weights and values vectors must be either lists or tuples" ) num_items = len(wt) if num_items != len(val): msg = ( "The number of weights must be the same as the number of values.\n" f"But got {num_items} weights and {len(val)} values" ) raise ValueError(msg) for i in range(num_items): if not isinstance(wt[i], int): msg = ( "All weights must be integers but got weight of " f"type {type(wt[i])} at index {i}" ) raise TypeError(msg) optimal_val, dp_table = knapsack(w, wt, val, num_items) example_optional_set: set = set() _construct_solution(dp_table, wt, num_items, w, example_optional_set) return optimal_val, example_optional_set def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set): """ Recursively reconstructs one of the optimal subsets given a filled DP table and the vector of weights Parameters --------- dp: list of list, the table of a solved integer weight dynamic programming problem wt: list or tuple, the vector of weights of the items i: int, the index of the item under consideration j: int, the current possible maximum weight optimal_set: set, the optimal subset so far. This gets modified by the function. Returns ------- None """ # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(dp, wt, i - 1, j, optimal_set) else: optimal_set.add(i) _construct_solution(dp, wt, i - 1, j - wt[i - 1], optimal_set) if __name__ == "__main__": """ Adding test case for knapsack """ val = [3, 2, 4, 4] wt = [4, 3, 2, 3] n = 4 w = 6 f = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] optimal_solution, _ = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 optimal_solution, optimal_subset = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print("optimal_value = ", optimal_solution) print("An optimal subset corresponding to the optimal value", optimal_subset)
""" Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. Note that only the integer weights 0-1 knapsack problem is solvable using dynamic programming. """ def mf_knapsack(i, wt, val, j): """ This code involves the concept of memory functions. Here we solve the subproblems which are needed unlike the below example F is a 2D array with -1s filled up """ global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: val = mf_knapsack(i - 1, wt, val, j) else: val = max( mf_knapsack(i - 1, wt, val, j), mf_knapsack(i - 1, wt, val, j - wt[i - 1]) + val[i - 1], ) f[i][j] = val return f[i][j] def knapsack(w, wt, val, n): dp = [[0] * (w + 1) for _ in range(n + 1)] for i in range(1, n + 1): for w_ in range(1, w + 1): if wt[i - 1] <= w_: dp[i][w_] = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]], dp[i - 1][w_]) else: dp[i][w_] = dp[i - 1][w_] return dp[n][w_], dp def knapsack_with_example_solution(w: int, wt: list, val: list): """ Solves the integer weights knapsack problem returns one of the several possible optimal subsets. Parameters --------- W: int, the total maximum weight for the given knapsack problem. wt: list, the vector of weights for all items where wt[i] is the weight of the i-th item. val: list, the vector of values for all items where val[i] is the value of the i-th item Returns ------- optimal_val: float, the optimal value for the given knapsack problem example_optional_set: set, the indices of one of the optimal subsets which gave rise to the optimal value. Examples ------- >>> knapsack_with_example_solution(10, [1, 3, 5, 2], [10, 20, 100, 22]) (142, {2, 3, 4}) >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4, 4]) (8, {3, 4}) >>> knapsack_with_example_solution(6, [4, 3, 2, 3], [3, 2, 4]) Traceback (most recent call last): ... ValueError: The number of weights must be the same as the number of values. But got 4 weights and 3 values """ if not (isinstance(wt, (list, tuple)) and isinstance(val, (list, tuple))): raise ValueError( "Both the weights and values vectors must be either lists or tuples" ) num_items = len(wt) if num_items != len(val): msg = ( "The number of weights must be the same as the number of values.\n" f"But got {num_items} weights and {len(val)} values" ) raise ValueError(msg) for i in range(num_items): if not isinstance(wt[i], int): msg = ( "All weights must be integers but got weight of " f"type {type(wt[i])} at index {i}" ) raise TypeError(msg) optimal_val, dp_table = knapsack(w, wt, val, num_items) example_optional_set: set = set() _construct_solution(dp_table, wt, num_items, w, example_optional_set) return optimal_val, example_optional_set def _construct_solution(dp: list, wt: list, i: int, j: int, optimal_set: set): """ Recursively reconstructs one of the optimal subsets given a filled DP table and the vector of weights Parameters --------- dp: list of list, the table of a solved integer weight dynamic programming problem wt: list or tuple, the vector of weights of the items i: int, the index of the item under consideration j: int, the current possible maximum weight optimal_set: set, the optimal subset so far. This gets modified by the function. Returns ------- None """ # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(dp, wt, i - 1, j, optimal_set) else: optimal_set.add(i) _construct_solution(dp, wt, i - 1, j - wt[i - 1], optimal_set) if __name__ == "__main__": """ Adding test case for knapsack """ val = [3, 2, 4, 4] wt = [4, 3, 2, 3] n = 4 w = 6 f = [[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] optimal_solution, _ = knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 optimal_solution, optimal_subset = knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print("optimal_value = ", optimal_solution) print("An optimal subset corresponding to the optimal value", optimal_subset)
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# Created by sarathkaul on 12/11/19 import requests def send_slack_message(message_body: str, slack_url: str) -> None: headers = {"Content-Type": "application/json"} response = requests.post(slack_url, json={"text": message_body}, headers=headers) if response.status_code != 200: msg = ( "Request to slack returned an error " f"{response.status_code}, the response is:\n{response.text}" ) raise ValueError(msg) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
# Created by sarathkaul on 12/11/19 import requests def send_slack_message(message_body: str, slack_url: str) -> None: headers = {"Content-Type": "application/json"} response = requests.post(slack_url, json={"text": message_body}, headers=headers) if response.status_code != 200: msg = ( "Request to slack returned an error " f"{response.status_code}, the response is:\n{response.text}" ) raise ValueError(msg) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 201 210 What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? """ from itertools import permutations def solution(): """Returns the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. >>> solution() '2783915460' """ result = list(map("".join, permutations("0123456789"))) return result[999999] if __name__ == "__main__": print(solution())
""" A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are: 012 021 102 120 201 210 What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9? """ from itertools import permutations def solution(): """Returns the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. >>> solution() '2783915460' """ result = list(map("".join, permutations("0123456789"))) return result[999999] if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Segment_tree creates a segment tree with a given array and function, allowing queries to be done later in log(N) time function takes 2 values and returns a same type value """ from collections.abc import Sequence from queue import Queue class SegmentTreeNode: def __init__(self, start, end, val, left=None, right=None): self.start = start self.end = end self.val = val self.mid = (start + end) // 2 self.left = left self.right = right def __repr__(self): return f"SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})" class SegmentTree: """ >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> tuple(num_arr.traverse()) # doctest: +NORMALIZE_WHITESPACE (SegmentTreeNode(start=0, end=4, val=15), SegmentTreeNode(start=0, end=2, val=8), SegmentTreeNode(start=3, end=4, val=7), SegmentTreeNode(start=0, end=1, val=3), SegmentTreeNode(start=2, end=2, val=5), SegmentTreeNode(start=3, end=3, val=3), SegmentTreeNode(start=4, end=4, val=4), SegmentTreeNode(start=0, end=0, val=2), SegmentTreeNode(start=1, end=1, val=1)) >>> >>> num_arr.update(1, 5) >>> tuple(num_arr.traverse()) # doctest: +NORMALIZE_WHITESPACE (SegmentTreeNode(start=0, end=4, val=19), SegmentTreeNode(start=0, end=2, val=12), SegmentTreeNode(start=3, end=4, val=7), SegmentTreeNode(start=0, end=1, val=7), SegmentTreeNode(start=2, end=2, val=5), SegmentTreeNode(start=3, end=3, val=3), SegmentTreeNode(start=4, end=4, val=4), SegmentTreeNode(start=0, end=0, val=2), SegmentTreeNode(start=1, end=1, val=5)) >>> >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> >>> max_arr = SegmentTree([2, 1, 5, 3, 4], max) >>> for node in max_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=5) SegmentTreeNode(start=0, end=2, val=5) SegmentTreeNode(start=3, end=4, val=4) SegmentTreeNode(start=0, end=1, val=2) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=1) >>> >>> max_arr.update(1, 5) >>> for node in max_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=5) SegmentTreeNode(start=0, end=2, val=5) SegmentTreeNode(start=3, end=4, val=4) SegmentTreeNode(start=0, end=1, val=5) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=5) >>> >>> max_arr.query_range(3, 4) 4 >>> max_arr.query_range(2, 2) 5 >>> max_arr.query_range(1, 3) 5 >>> >>> min_arr = SegmentTree([2, 1, 5, 3, 4], min) >>> for node in min_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=1) SegmentTreeNode(start=0, end=2, val=1) SegmentTreeNode(start=3, end=4, val=3) SegmentTreeNode(start=0, end=1, val=1) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=1) >>> >>> min_arr.update(1, 5) >>> for node in min_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=2) SegmentTreeNode(start=0, end=2, val=2) SegmentTreeNode(start=3, end=4, val=3) SegmentTreeNode(start=0, end=1, val=2) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=5) >>> >>> min_arr.query_range(3, 4) 3 >>> min_arr.query_range(2, 2) 5 >>> min_arr.query_range(1, 3) 3 >>> """ def __init__(self, collection: Sequence, function): self.collection = collection self.fn = function if self.collection: self.root = self._build_tree(0, len(collection) - 1) def update(self, i, val): """ Update an element in log(N) time :param i: position to be update :param val: new value >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(1, 3) 13 """ self._update_tree(self.root, i, val) def query_range(self, i, j): """ Get range query value in log(N) time :param i: left element index :param j: right element index :return: element combined in the range [i, j] >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> """ return self._query_range(self.root, i, j) def _build_tree(self, start, end): if start == end: return SegmentTreeNode(start, end, self.collection[start]) mid = (start + end) // 2 left = self._build_tree(start, mid) right = self._build_tree(mid + 1, end) return SegmentTreeNode(start, end, self.fn(left.val, right.val), left, right) def _update_tree(self, node, i, val): if node.start == i and node.end == i: node.val = val return if i <= node.mid: self._update_tree(node.left, i, val) else: self._update_tree(node.right, i, val) node.val = self.fn(node.left.val, node.right.val) def _query_range(self, node, i, j): if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left, i, j) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left, i, node.mid), self._query_range(node.right, node.mid + 1, j), ) else: # range in right child tree return self._query_range(node.right, i, j) def traverse(self): if self.root is not None: queue = Queue() queue.put(self.root) while not queue.empty(): node = queue.get() yield node if node.left is not None: queue.put(node.left) if node.right is not None: queue.put(node.right) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print("*" * 50) arr = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
""" Segment_tree creates a segment tree with a given array and function, allowing queries to be done later in log(N) time function takes 2 values and returns a same type value """ from collections.abc import Sequence from queue import Queue class SegmentTreeNode: def __init__(self, start, end, val, left=None, right=None): self.start = start self.end = end self.val = val self.mid = (start + end) // 2 self.left = left self.right = right def __repr__(self): return f"SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})" class SegmentTree: """ >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> tuple(num_arr.traverse()) # doctest: +NORMALIZE_WHITESPACE (SegmentTreeNode(start=0, end=4, val=15), SegmentTreeNode(start=0, end=2, val=8), SegmentTreeNode(start=3, end=4, val=7), SegmentTreeNode(start=0, end=1, val=3), SegmentTreeNode(start=2, end=2, val=5), SegmentTreeNode(start=3, end=3, val=3), SegmentTreeNode(start=4, end=4, val=4), SegmentTreeNode(start=0, end=0, val=2), SegmentTreeNode(start=1, end=1, val=1)) >>> >>> num_arr.update(1, 5) >>> tuple(num_arr.traverse()) # doctest: +NORMALIZE_WHITESPACE (SegmentTreeNode(start=0, end=4, val=19), SegmentTreeNode(start=0, end=2, val=12), SegmentTreeNode(start=3, end=4, val=7), SegmentTreeNode(start=0, end=1, val=7), SegmentTreeNode(start=2, end=2, val=5), SegmentTreeNode(start=3, end=3, val=3), SegmentTreeNode(start=4, end=4, val=4), SegmentTreeNode(start=0, end=0, val=2), SegmentTreeNode(start=1, end=1, val=5)) >>> >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> >>> max_arr = SegmentTree([2, 1, 5, 3, 4], max) >>> for node in max_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=5) SegmentTreeNode(start=0, end=2, val=5) SegmentTreeNode(start=3, end=4, val=4) SegmentTreeNode(start=0, end=1, val=2) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=1) >>> >>> max_arr.update(1, 5) >>> for node in max_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=5) SegmentTreeNode(start=0, end=2, val=5) SegmentTreeNode(start=3, end=4, val=4) SegmentTreeNode(start=0, end=1, val=5) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=5) >>> >>> max_arr.query_range(3, 4) 4 >>> max_arr.query_range(2, 2) 5 >>> max_arr.query_range(1, 3) 5 >>> >>> min_arr = SegmentTree([2, 1, 5, 3, 4], min) >>> for node in min_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=1) SegmentTreeNode(start=0, end=2, val=1) SegmentTreeNode(start=3, end=4, val=3) SegmentTreeNode(start=0, end=1, val=1) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=1) >>> >>> min_arr.update(1, 5) >>> for node in min_arr.traverse(): ... print(node) ... SegmentTreeNode(start=0, end=4, val=2) SegmentTreeNode(start=0, end=2, val=2) SegmentTreeNode(start=3, end=4, val=3) SegmentTreeNode(start=0, end=1, val=2) SegmentTreeNode(start=2, end=2, val=5) SegmentTreeNode(start=3, end=3, val=3) SegmentTreeNode(start=4, end=4, val=4) SegmentTreeNode(start=0, end=0, val=2) SegmentTreeNode(start=1, end=1, val=5) >>> >>> min_arr.query_range(3, 4) 3 >>> min_arr.query_range(2, 2) 5 >>> min_arr.query_range(1, 3) 3 >>> """ def __init__(self, collection: Sequence, function): self.collection = collection self.fn = function if self.collection: self.root = self._build_tree(0, len(collection) - 1) def update(self, i, val): """ Update an element in log(N) time :param i: position to be update :param val: new value >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(1, 3) 13 """ self._update_tree(self.root, i, val) def query_range(self, i, j): """ Get range query value in log(N) time :param i: left element index :param j: right element index :return: element combined in the range [i, j] >>> import operator >>> num_arr = SegmentTree([2, 1, 5, 3, 4], operator.add) >>> num_arr.update(1, 5) >>> num_arr.query_range(3, 4) 7 >>> num_arr.query_range(2, 2) 5 >>> num_arr.query_range(1, 3) 13 >>> """ return self._query_range(self.root, i, j) def _build_tree(self, start, end): if start == end: return SegmentTreeNode(start, end, self.collection[start]) mid = (start + end) // 2 left = self._build_tree(start, mid) right = self._build_tree(mid + 1, end) return SegmentTreeNode(start, end, self.fn(left.val, right.val), left, right) def _update_tree(self, node, i, val): if node.start == i and node.end == i: node.val = val return if i <= node.mid: self._update_tree(node.left, i, val) else: self._update_tree(node.right, i, val) node.val = self.fn(node.left.val, node.right.val) def _query_range(self, node, i, j): if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left, i, j) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left, i, node.mid), self._query_range(node.right, node.mid + 1, j), ) else: # range in right child tree return self._query_range(node.right, i, j) def traverse(self): if self.root is not None: queue = Queue() queue.put(self.root) while not queue.empty(): node = queue.get() yield node if node.left is not None: queue.put(node.left) if node.right is not None: queue.put(node.right) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print("*" * 50) arr = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
#!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git commit" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message if # it wants to stop the commit. # # To enable this hook, rename this file to "pre-commit". if git rev-parse --verify HEAD >/dev/null 2>&1 then against=HEAD else # Initial commit: diff against an empty tree object against=$(git hash-object -t tree /dev/null) fi # If you want to allow non-ASCII filenames set this variable to true. allownonascii=$(git config --bool hooks.allownonascii) # Redirect output to stderr. exec 1>&2 # Cross platform projects tend to avoid non-ASCII filenames; prevent # them from being added to the repository. We exploit the fact that the # printable range starts at the space character and ends with tilde. if [ "$allownonascii" != "true" ] && # Note that the use of brackets around a tr range is ok here, (it's # even required, for portability to Solaris 10's /usr/bin/tr), since # the square bracket bytes happen to fall in the designated range. test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 then cat <<\EOF Error: Attempt to add a non-ASCII file name. This can cause problems if you want to work with people on other platforms. To be portable it is advisable to rename the file. If you know what you are doing you can disable this check using: git config hooks.allownonascii true EOF exit 1 fi # If there are whitespace errors, print the offending file names and fail. exec git diff-index --check --cached $against --
#!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git commit" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message if # it wants to stop the commit. # # To enable this hook, rename this file to "pre-commit". if git rev-parse --verify HEAD >/dev/null 2>&1 then against=HEAD else # Initial commit: diff against an empty tree object against=$(git hash-object -t tree /dev/null) fi # If you want to allow non-ASCII filenames set this variable to true. allownonascii=$(git config --bool hooks.allownonascii) # Redirect output to stderr. exec 1>&2 # Cross platform projects tend to avoid non-ASCII filenames; prevent # them from being added to the repository. We exploit the fact that the # printable range starts at the space character and ends with tilde. if [ "$allownonascii" != "true" ] && # Note that the use of brackets around a tr range is ok here, (it's # even required, for portability to Solaris 10's /usr/bin/tr), since # the square bracket bytes happen to fall in the designated range. test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 then cat <<\EOF Error: Attempt to add a non-ASCII file name. This can cause problems if you want to work with people on other platforms. To be portable it is advisable to rename the file. If you know what you are doing you can disable this check using: git config hooks.allownonascii true EOF exit 1 fi # If there are whitespace errors, print the offending file names and fail. exec git diff-index --check --cached $against --
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" 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. """ import math from itertools import permutations def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True 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. """ import math from itertools import permutations def is_prime(number: int) -> bool: """Checks to see if a number is a prime in O(sqrt(n)). A number is prime if it has exactly two factors: 1 and itself. >>> is_prime(0) False >>> is_prime(1) False >>> is_prime(2) True >>> is_prime(3) True >>> is_prime(27) False >>> is_prime(87) False >>> is_prime(563) True >>> is_prime(2999) True >>> is_prime(67483) False """ if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True 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
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Heap's (iterative) algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(n: int, arr: list): c = [0] * n res.append(tuple(arr)) i = 0 while i < n: if c[i] < i: if i % 2 == 0: arr[0], arr[i] = arr[i], arr[0] else: arr[c[i]], arr[i] = arr[i], arr[c[i]] res.append(tuple(arr)) c[i] += 1 i = 0 else: c[i] = 0 i += 1 generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
""" Heap's (iterative) algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implementation of the iterative Heap's algorithm, returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(n: int, arr: list): c = [0] * n res.append(tuple(arr)) i = 0 while i < n: if c[i] < i: if i % 2 == 0: arr[0], arr[i] = arr[i], arr[0] else: arr[c[i]], arr[i] = arr[i], arr[c[i]] res.append(tuple(arr)) c[i] += 1 i = 0 else: c[i] = 0 i += 1 generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
#!/bin/sh # # An example hook script to check the commit log message. # Called by "git commit" with one argument, the name of the file # that has the commit message. The hook should exit with non-zero # status after issuing an appropriate message if it wants to stop the # commit. The hook is allowed to edit the commit message file. # # To enable this hook, rename this file to "commit-msg". # Uncomment the below to add a Signed-off-by line to the message. # Doing this in a hook is a bad idea in general, but the prepare-commit-msg # hook is more suited to it. # # SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') # grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" # This example catches duplicate Signed-off-by lines. test "" = "$(grep '^Signed-off-by: ' "$1" | sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || { echo >&2 Duplicate Signed-off-by lines. exit 1 }
#!/bin/sh # # An example hook script to check the commit log message. # Called by "git commit" with one argument, the name of the file # that has the commit message. The hook should exit with non-zero # status after issuing an appropriate message if it wants to stop the # commit. The hook is allowed to edit the commit message file. # # To enable this hook, rename this file to "commit-msg". # Uncomment the below to add a Signed-off-by line to the message. # Doing this in a hook is a bad idea in general, but the prepare-commit-msg # hook is more suited to it. # # SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') # grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" # This example catches duplicate Signed-off-by lines. test "" = "$(grep '^Signed-off-by: ' "$1" | sort | uniq -c | sed -e '/^[ ]*1[ ]/d')" || { echo >&2 Duplicate Signed-off-by lines. exit 1 }
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Calculates the nth number in Sylvester's sequence Source: https://en.wikipedia.org/wiki/Sylvester%27s_sequence """ def sylvester(number: int) -> int: """ :param number: nth number to calculate in the sequence :return: the nth number in Sylvester's sequence >>> sylvester(8) 113423713055421844361000443 >>> sylvester(-1) Traceback (most recent call last): ... ValueError: The input value of [n=-1] has to be > 0 >>> sylvester(8.0) Traceback (most recent call last): ... AssertionError: The input value of [n=8.0] is not an integer """ assert isinstance(number, int), f"The input value of [n={number}] is not an integer" if number == 1: return 2 elif number < 1: msg = f"The input value of [n={number}] has to be > 0" raise ValueError(msg) else: num = sylvester(number - 1) lower = num - 1 upper = num return lower * upper + 1 if __name__ == "__main__": print(f"The 8th number in Sylvester's sequence: {sylvester(8)}")
""" Calculates the nth number in Sylvester's sequence Source: https://en.wikipedia.org/wiki/Sylvester%27s_sequence """ def sylvester(number: int) -> int: """ :param number: nth number to calculate in the sequence :return: the nth number in Sylvester's sequence >>> sylvester(8) 113423713055421844361000443 >>> sylvester(-1) Traceback (most recent call last): ... ValueError: The input value of [n=-1] has to be > 0 >>> sylvester(8.0) Traceback (most recent call last): ... AssertionError: The input value of [n=8.0] is not an integer """ assert isinstance(number, int), f"The input value of [n={number}] is not an integer" if number == 1: return 2 elif number < 1: msg = f"The input value of [n={number}] has to be > 0" raise ValueError(msg) else: num = sylvester(number - 1) lower = num - 1 upper = num return lower * upper + 1 if __name__ == "__main__": print(f"The 8th number in Sylvester's sequence: {sylvester(8)}")
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 36 https://projecteuler.net/problem=36 Problem Statement: Double-base palindromes Problem 36 The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. (Please note that the palindromic number, in either base, may not include leading zeros.) """ from __future__ import annotations def is_palindrome(n: int | str) -> bool: """ Return true if the input n is a palindrome. Otherwise return false. n can be an integer or a string. >>> is_palindrome(909) True >>> is_palindrome(908) False >>> is_palindrome('10101') True >>> is_palindrome('10111') False """ n = str(n) return n == n[::-1] def solution(n: int = 1000000): """Return the sum of all numbers, less than n , which are palindromic in base 10 and base 2. >>> solution(1000000) 872187 >>> solution(500000) 286602 >>> solution(100000) 286602 >>> solution(1000) 1772 >>> solution(100) 157 >>> solution(10) 25 >>> solution(2) 1 >>> solution(1) 0 """ total = 0 for i in range(1, n): if is_palindrome(i) and is_palindrome(bin(i).split("b")[1]): total += i return total if __name__ == "__main__": print(solution(int(str(input().strip()))))
""" Project Euler Problem 36 https://projecteuler.net/problem=36 Problem Statement: Double-base palindromes Problem 36 The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. (Please note that the palindromic number, in either base, may not include leading zeros.) """ from __future__ import annotations def is_palindrome(n: int | str) -> bool: """ Return true if the input n is a palindrome. Otherwise return false. n can be an integer or a string. >>> is_palindrome(909) True >>> is_palindrome(908) False >>> is_palindrome('10101') True >>> is_palindrome('10111') False """ n = str(n) return n == n[::-1] def solution(n: int = 1000000): """Return the sum of all numbers, less than n , which are palindromic in base 10 and base 2. >>> solution(1000000) 872187 >>> solution(500000) 286602 >>> solution(100000) 286602 >>> solution(1000) 1772 >>> solution(100) 157 >>> solution(10) 25 >>> solution(2) 1 >>> solution(1) 0 """ total = 0 for i in range(1, n): if is_palindrome(i) and is_palindrome(bin(i).split("b")[1]): total += i return total if __name__ == "__main__": print(solution(int(str(input().strip()))))
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
name: Other description: Use this for any other issues. PLEASE do not create blank issues labels: ["awaiting triage"] body: - type: textarea id: issuedescription attributes: label: What would you like to share? description: Provide a clear and concise explanation of your issue. validations: required: true - type: textarea id: extrainfo attributes: label: Additional information description: Is there anything else we should know about this issue? validations: required: false
name: Other description: Use this for any other issues. PLEASE do not create blank issues labels: ["awaiting triage"] body: - type: textarea id: issuedescription attributes: label: What would you like to share? description: Provide a clear and concise explanation of your issue. validations: required: true - type: textarea id: extrainfo attributes: label: Additional information description: Is there anything else we should know about this issue? validations: required: false
-1
TheAlgorithms/Python
8,913
Ruff fixes
### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
tianyizheng02
"2023-07-31T19:13:04Z"
"2023-07-31T20:53:26Z"
90a8e6e0d210a5c526c8f485fa825e1649d217e2
5cf34d901e32b65425103309bbad0068b1851238
Ruff fixes. ### Describe your change: Fix graphs/eulerian_path_and_circuit_for_undirected_graph.py and physics/newtons_second_law_of_motion.py, which are causing ruff to fail * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
def remove_digit(num: int) -> int: """ returns the biggest possible result that can be achieved by removing one digit from the given number >>> remove_digit(152) 52 >>> remove_digit(6385) 685 >>> remove_digit(-11) 1 >>> remove_digit(2222222) 222222 >>> remove_digit("2222222") Traceback (most recent call last): TypeError: only integers accepted as input >>> remove_digit("string input") Traceback (most recent call last): TypeError: only integers accepted as input """ if not isinstance(num, int): raise TypeError("only integers accepted as input") else: num_str = str(abs(num)) num_transpositions = [list(num_str) for char in range(len(num_str))] for index in range(len(num_str)): num_transpositions[index].pop(index) return max( int("".join(list(transposition))) for transposition in num_transpositions ) if __name__ == "__main__": __import__("doctest").testmod()
def remove_digit(num: int) -> int: """ returns the biggest possible result that can be achieved by removing one digit from the given number >>> remove_digit(152) 52 >>> remove_digit(6385) 685 >>> remove_digit(-11) 1 >>> remove_digit(2222222) 222222 >>> remove_digit("2222222") Traceback (most recent call last): TypeError: only integers accepted as input >>> remove_digit("string input") Traceback (most recent call last): TypeError: only integers accepted as input """ if not isinstance(num, int): raise TypeError("only integers accepted as input") else: num_str = str(abs(num)) num_transpositions = [list(num_str) for char in range(len(num_str))] for index in range(len(num_str)): num_transpositions[index].pop(index) return max( int("".join(list(transposition))) for transposition in num_transpositions ) if __name__ == "__main__": __import__("doctest").testmod()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from binascii import hexlify from hashlib import sha256 from os import urandom # RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for # Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526 primes = { # 1536-bit 5: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, # 2048-bit 14: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AACAA68FFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, # 3072-bit 15: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" + "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, # 4096-bit 16: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" + "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" + "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" + "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" + "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" + "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" + "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" + "FFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, # 6144-bit 17: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" + "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" + "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" + "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" + "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" + "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" + "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" + "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" + "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" + "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" + "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" + "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" + "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" + "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" + "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" + "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" + "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" + "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" + "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" + "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" + "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" + "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" + "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" + "6DCC4024FFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, # 8192-bit 18: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" + "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" + "83655D23DCA3AD961C62F356208552BB9ED529077096966D" + "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" + "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" + "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" + "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" + "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" + "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" + "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" + "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" + "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" + "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" + "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" + "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" + "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" + "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" + "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD" + "F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831" + "179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B" + "DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF" + "5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6" + "D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3" + "23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" + "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328" + "06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C" + "DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE" + "12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4" + "38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300" + "741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568" + "3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" + "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B" + "4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A" + "062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36" + "4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1" + "B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92" + "4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47" + "9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" + "60C980DD98EDD3DFFFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, } class DiffieHellman: """ Class to represent the Diffie-Hellman key exchange protocol >>> alice = DiffieHellman() >>> bob = DiffieHellman() >>> alice_private = alice.get_private_key() >>> alice_public = alice.generate_public_key() >>> bob_private = bob.get_private_key() >>> bob_public = bob.generate_public_key() >>> # generating shared key using the DH object >>> alice_shared = alice.generate_shared_key(bob_public) >>> bob_shared = bob.generate_shared_key(alice_public) >>> assert alice_shared == bob_shared >>> # generating shared key using static methods >>> alice_shared = DiffieHellman.generate_shared_key_static( ... alice_private, bob_public ... ) >>> bob_shared = DiffieHellman.generate_shared_key_static( ... bob_private, alice_public ... ) >>> assert alice_shared == bob_shared """ # Current minimum recommendation is 2048 bit (group 14) def __init__(self, group: int = 14) -> None: if group not in primes: raise ValueError("Unsupported Group") self.prime = primes[group]["prime"] self.generator = primes[group]["generator"] self.__private_key = int(hexlify(urandom(32)), base=16) def get_private_key(self) -> str: return hex(self.__private_key)[2:] def generate_public_key(self) -> str: public_key = pow(self.generator, self.__private_key, self.prime) return hex(public_key)[2:] def is_valid_public_key(self, key: int) -> bool: # check if the other public key is valid based on NIST SP800-56 return ( 2 <= key <= self.prime - 2 and pow(key, (self.prime - 1) // 2, self.prime) == 1 ) def generate_shared_key(self, other_key_str: str) -> str: other_key = int(other_key_str, base=16) if not self.is_valid_public_key(other_key): raise ValueError("Invalid public key") shared_key = pow(other_key, self.__private_key, self.prime) return sha256(str(shared_key).encode()).hexdigest() @staticmethod def is_valid_public_key_static(remote_public_key_str: int, prime: int) -> bool: # check if the other public key is valid based on NIST SP800-56 return ( 2 <= remote_public_key_str <= prime - 2 and pow(remote_public_key_str, (prime - 1) // 2, prime) == 1 ) @staticmethod def generate_shared_key_static( local_private_key_str: str, remote_public_key_str: str, group: int = 14 ) -> str: local_private_key = int(local_private_key_str, base=16) remote_public_key = int(remote_public_key_str, base=16) prime = primes[group]["prime"] if not DiffieHellman.is_valid_public_key_static(remote_public_key, prime): raise ValueError("Invalid public key") shared_key = pow(remote_public_key, local_private_key, prime) return sha256(str(shared_key).encode()).hexdigest() if __name__ == "__main__": import doctest doctest.testmod()
from binascii import hexlify from hashlib import sha256 from os import urandom # RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for # Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526 primes = { # 1536-bit 5: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" "83655D23DCA3AD961C62F356208552BB9ED529077096966D" "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, # 2048-bit 14: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" "83655D23DCA3AD961C62F356208552BB9ED529077096966D" "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" "15728E5A8AACAA68FFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, # 3072-bit 15: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" "83655D23DCA3AD961C62F356208552BB9ED529077096966D" "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, # 4096-bit 16: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" "83655D23DCA3AD961C62F356208552BB9ED529077096966D" "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" "FFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, # 6144-bit 17: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08" "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B" "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9" "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6" "49286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8" "FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D" "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C" "180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718" "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D" "04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7D" "B3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D226" "1AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200C" "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFC" "E0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B26" "99C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB" "04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2" "233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127" "D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406" "AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918" "DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B33205151" "2BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03" "F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97F" "BEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58B" "B7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632" "387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E" "6DCC4024FFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, # 8192-bit 18: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" "83655D23DCA3AD961C62F356208552BB9ED529077096966D" "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934028492" "36C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BD" "F8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831" "179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1B" "DB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF" "5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6" "D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F3" "23A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AA" "CC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE328" "06A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55C" "DA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE" "12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E4" "38777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300" "741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F568" "3423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD9" "22222E04A4037C0713EB57A81A23F0C73473FC646CEA306B" "4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A" "062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A36" "4597E899A0255DC164F31CC50846851DF9AB48195DED7EA1" "B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F92" "4009438B481C6CD7889A002ED5EE382BC9190DA6FC026E47" "9558E4475677E9AA9E3050E2765694DFC81F56E880B96E71" "60C980DD98EDD3DFFFFFFFFFFFFFFFFF", base=16, ), "generator": 2, }, } class DiffieHellman: """ Class to represent the Diffie-Hellman key exchange protocol >>> alice = DiffieHellman() >>> bob = DiffieHellman() >>> alice_private = alice.get_private_key() >>> alice_public = alice.generate_public_key() >>> bob_private = bob.get_private_key() >>> bob_public = bob.generate_public_key() >>> # generating shared key using the DH object >>> alice_shared = alice.generate_shared_key(bob_public) >>> bob_shared = bob.generate_shared_key(alice_public) >>> assert alice_shared == bob_shared >>> # generating shared key using static methods >>> alice_shared = DiffieHellman.generate_shared_key_static( ... alice_private, bob_public ... ) >>> bob_shared = DiffieHellman.generate_shared_key_static( ... bob_private, alice_public ... ) >>> assert alice_shared == bob_shared """ # Current minimum recommendation is 2048 bit (group 14) def __init__(self, group: int = 14) -> None: if group not in primes: raise ValueError("Unsupported Group") self.prime = primes[group]["prime"] self.generator = primes[group]["generator"] self.__private_key = int(hexlify(urandom(32)), base=16) def get_private_key(self) -> str: return hex(self.__private_key)[2:] def generate_public_key(self) -> str: public_key = pow(self.generator, self.__private_key, self.prime) return hex(public_key)[2:] def is_valid_public_key(self, key: int) -> bool: # check if the other public key is valid based on NIST SP800-56 return ( 2 <= key <= self.prime - 2 and pow(key, (self.prime - 1) // 2, self.prime) == 1 ) def generate_shared_key(self, other_key_str: str) -> str: other_key = int(other_key_str, base=16) if not self.is_valid_public_key(other_key): raise ValueError("Invalid public key") shared_key = pow(other_key, self.__private_key, self.prime) return sha256(str(shared_key).encode()).hexdigest() @staticmethod def is_valid_public_key_static(remote_public_key_str: int, prime: int) -> bool: # check if the other public key is valid based on NIST SP800-56 return ( 2 <= remote_public_key_str <= prime - 2 and pow(remote_public_key_str, (prime - 1) // 2, prime) == 1 ) @staticmethod def generate_shared_key_static( local_private_key_str: str, remote_public_key_str: str, group: int = 14 ) -> str: local_private_key = int(local_private_key_str, base=16) remote_public_key = int(remote_public_key_str, base=16) prime = primes[group]["prime"] if not DiffieHellman.is_valid_public_key_static(remote_public_key, prime): raise ValueError("Invalid public key") shared_key = pow(remote_public_key, local_private_key, prime) return sha256(str(shared_key).encode()).hexdigest() if __name__ == "__main__": import doctest doctest.testmod()
1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. More importantly, the transformation is reversible, without needing to store any additional data except the position of the first original character. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. """ from __future__ import annotations from typing import TypedDict class BWTTransformDict(TypedDict): bwt_string: str idx_original_string: int def all_rotations(s: str) -> list[str]: """ :param s: The string that will be rotated len(s) times. :return: A list with the rotations. :raises TypeError: If s is not an instance of str. Examples: >>> all_rotations("^BANANA|") # doctest: +NORMALIZE_WHITESPACE ['^BANANA|', 'BANANA|^', 'ANANA|^B', 'NANA|^BA', 'ANA|^BAN', 'NA|^BANA', 'A|^BANAN', '|^BANANA'] >>> all_rotations("a_asa_da_casa") # doctest: +NORMALIZE_WHITESPACE ['a_asa_da_casa', '_asa_da_casaa', 'asa_da_casaa_', 'sa_da_casaa_a', 'a_da_casaa_as', '_da_casaa_asa', 'da_casaa_asa_', 'a_casaa_asa_d', '_casaa_asa_da', 'casaa_asa_da_', 'asaa_asa_da_c', 'saa_asa_da_ca', 'aa_asa_da_cas'] >>> all_rotations("panamabanana") # doctest: +NORMALIZE_WHITESPACE ['panamabanana', 'anamabananap', 'namabananapa', 'amabananapan', 'mabananapana', 'abananapanam', 'bananapanama', 'ananapanamab', 'nanapanamaba', 'anapanamaban', 'napanamabana', 'apanamabanan'] >>> all_rotations(5) Traceback (most recent call last): ... TypeError: The parameter s type must be str. """ if not isinstance(s, str): raise TypeError("The parameter s type must be str.") return [s[i:] + s[:i] for i in range(len(s))] def bwt_transform(s: str) -> BWTTransformDict: """ :param s: The string that will be used at bwt algorithm :return: the string composed of the last char of each row of the ordered rotations and the index of the original string at ordered rotations list :raises TypeError: If the s parameter type is not str :raises ValueError: If the s parameter is empty Examples: >>> bwt_transform("^BANANA") {'bwt_string': 'BNN^AAA', 'idx_original_string': 6} >>> bwt_transform("a_asa_da_casa") {'bwt_string': 'aaaadss_c__aa', 'idx_original_string': 3} >>> bwt_transform("panamabanana") {'bwt_string': 'mnpbnnaaaaaa', 'idx_original_string': 11} >>> bwt_transform(4) Traceback (most recent call last): ... TypeError: The parameter s type must be str. >>> bwt_transform('') Traceback (most recent call last): ... ValueError: The parameter s must not be empty. """ if not isinstance(s, str): raise TypeError("The parameter s type must be str.") if not s: raise ValueError("The parameter s must not be empty.") rotations = all_rotations(s) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation response: BWTTransformDict = { "bwt_string": "".join([word[-1] for word in rotations]), "idx_original_string": rotations.index(s), } return response def reverse_bwt(bwt_string: str, idx_original_string: int) -> str: """ :param bwt_string: The string returned from bwt algorithm execution :param idx_original_string: A 0-based index of the string that was used to generate bwt_string at ordered rotations list :return: The string used to generate bwt_string when bwt was executed :raises TypeError: If the bwt_string parameter type is not str :raises ValueError: If the bwt_string parameter is empty :raises TypeError: If the idx_original_string type is not int or if not possible to cast it to int :raises ValueError: If the idx_original_string value is lower than 0 or greater than len(bwt_string) - 1 >>> reverse_bwt("BNN^AAA", 6) '^BANANA' >>> reverse_bwt("aaaadss_c__aa", 3) 'a_asa_da_casa' >>> reverse_bwt("mnpbnnaaaaaa", 11) 'panamabanana' >>> reverse_bwt(4, 11) Traceback (most recent call last): ... TypeError: The parameter bwt_string type must be str. >>> reverse_bwt("", 11) Traceback (most recent call last): ... ValueError: The parameter bwt_string must not be empty. >>> reverse_bwt("mnpbnnaaaaaa", "asd") # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TypeError: The parameter idx_original_string type must be int or passive of cast to int. >>> reverse_bwt("mnpbnnaaaaaa", -1) Traceback (most recent call last): ... ValueError: The parameter idx_original_string must not be lower than 0. >>> reverse_bwt("mnpbnnaaaaaa", 12) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: The parameter idx_original_string must be lower than len(bwt_string). >>> reverse_bwt("mnpbnnaaaaaa", 11.0) 'panamabanana' >>> reverse_bwt("mnpbnnaaaaaa", 11.4) 'panamabanana' """ if not isinstance(bwt_string, str): raise TypeError("The parameter bwt_string type must be str.") if not bwt_string: raise ValueError("The parameter bwt_string must not be empty.") try: idx_original_string = int(idx_original_string) except ValueError: raise TypeError( "The parameter idx_original_string type must be int or passive" " of cast to int." ) if idx_original_string < 0: raise ValueError("The parameter idx_original_string must not be lower than 0.") if idx_original_string >= len(bwt_string): raise ValueError( "The parameter idx_original_string must be lower than" " len(bwt_string)." ) ordered_rotations = [""] * len(bwt_string) for _ in range(len(bwt_string)): for i in range(len(bwt_string)): ordered_rotations[i] = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": entry_msg = "Provide a string that I will generate its BWT transform: " s = input(entry_msg).strip() result = bwt_transform(s) print( f"Burrows Wheeler transform for string '{s}' results " f"in '{result['bwt_string']}'" ) original_string = reverse_bwt(result["bwt_string"], result["idx_original_string"]) print( f"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " f"we get original string '{original_string}'" )
""" https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. More importantly, the transformation is reversible, without needing to store any additional data except the position of the first original character. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. """ from __future__ import annotations from typing import TypedDict class BWTTransformDict(TypedDict): bwt_string: str idx_original_string: int def all_rotations(s: str) -> list[str]: """ :param s: The string that will be rotated len(s) times. :return: A list with the rotations. :raises TypeError: If s is not an instance of str. Examples: >>> all_rotations("^BANANA|") # doctest: +NORMALIZE_WHITESPACE ['^BANANA|', 'BANANA|^', 'ANANA|^B', 'NANA|^BA', 'ANA|^BAN', 'NA|^BANA', 'A|^BANAN', '|^BANANA'] >>> all_rotations("a_asa_da_casa") # doctest: +NORMALIZE_WHITESPACE ['a_asa_da_casa', '_asa_da_casaa', 'asa_da_casaa_', 'sa_da_casaa_a', 'a_da_casaa_as', '_da_casaa_asa', 'da_casaa_asa_', 'a_casaa_asa_d', '_casaa_asa_da', 'casaa_asa_da_', 'asaa_asa_da_c', 'saa_asa_da_ca', 'aa_asa_da_cas'] >>> all_rotations("panamabanana") # doctest: +NORMALIZE_WHITESPACE ['panamabanana', 'anamabananap', 'namabananapa', 'amabananapan', 'mabananapana', 'abananapanam', 'bananapanama', 'ananapanamab', 'nanapanamaba', 'anapanamaban', 'napanamabana', 'apanamabanan'] >>> all_rotations(5) Traceback (most recent call last): ... TypeError: The parameter s type must be str. """ if not isinstance(s, str): raise TypeError("The parameter s type must be str.") return [s[i:] + s[:i] for i in range(len(s))] def bwt_transform(s: str) -> BWTTransformDict: """ :param s: The string that will be used at bwt algorithm :return: the string composed of the last char of each row of the ordered rotations and the index of the original string at ordered rotations list :raises TypeError: If the s parameter type is not str :raises ValueError: If the s parameter is empty Examples: >>> bwt_transform("^BANANA") {'bwt_string': 'BNN^AAA', 'idx_original_string': 6} >>> bwt_transform("a_asa_da_casa") {'bwt_string': 'aaaadss_c__aa', 'idx_original_string': 3} >>> bwt_transform("panamabanana") {'bwt_string': 'mnpbnnaaaaaa', 'idx_original_string': 11} >>> bwt_transform(4) Traceback (most recent call last): ... TypeError: The parameter s type must be str. >>> bwt_transform('') Traceback (most recent call last): ... ValueError: The parameter s must not be empty. """ if not isinstance(s, str): raise TypeError("The parameter s type must be str.") if not s: raise ValueError("The parameter s must not be empty.") rotations = all_rotations(s) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation response: BWTTransformDict = { "bwt_string": "".join([word[-1] for word in rotations]), "idx_original_string": rotations.index(s), } return response def reverse_bwt(bwt_string: str, idx_original_string: int) -> str: """ :param bwt_string: The string returned from bwt algorithm execution :param idx_original_string: A 0-based index of the string that was used to generate bwt_string at ordered rotations list :return: The string used to generate bwt_string when bwt was executed :raises TypeError: If the bwt_string parameter type is not str :raises ValueError: If the bwt_string parameter is empty :raises TypeError: If the idx_original_string type is not int or if not possible to cast it to int :raises ValueError: If the idx_original_string value is lower than 0 or greater than len(bwt_string) - 1 >>> reverse_bwt("BNN^AAA", 6) '^BANANA' >>> reverse_bwt("aaaadss_c__aa", 3) 'a_asa_da_casa' >>> reverse_bwt("mnpbnnaaaaaa", 11) 'panamabanana' >>> reverse_bwt(4, 11) Traceback (most recent call last): ... TypeError: The parameter bwt_string type must be str. >>> reverse_bwt("", 11) Traceback (most recent call last): ... ValueError: The parameter bwt_string must not be empty. >>> reverse_bwt("mnpbnnaaaaaa", "asd") # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... TypeError: The parameter idx_original_string type must be int or passive of cast to int. >>> reverse_bwt("mnpbnnaaaaaa", -1) Traceback (most recent call last): ... ValueError: The parameter idx_original_string must not be lower than 0. >>> reverse_bwt("mnpbnnaaaaaa", 12) # doctest: +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: The parameter idx_original_string must be lower than len(bwt_string). >>> reverse_bwt("mnpbnnaaaaaa", 11.0) 'panamabanana' >>> reverse_bwt("mnpbnnaaaaaa", 11.4) 'panamabanana' """ if not isinstance(bwt_string, str): raise TypeError("The parameter bwt_string type must be str.") if not bwt_string: raise ValueError("The parameter bwt_string must not be empty.") try: idx_original_string = int(idx_original_string) except ValueError: raise TypeError( "The parameter idx_original_string type must be int or passive" " of cast to int." ) if idx_original_string < 0: raise ValueError("The parameter idx_original_string must not be lower than 0.") if idx_original_string >= len(bwt_string): raise ValueError( "The parameter idx_original_string must be lower than len(bwt_string)." ) ordered_rotations = [""] * len(bwt_string) for _ in range(len(bwt_string)): for i in range(len(bwt_string)): ordered_rotations[i] = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string] if __name__ == "__main__": entry_msg = "Provide a string that I will generate its BWT transform: " s = input(entry_msg).strip() result = bwt_transform(s) print( f"Burrows Wheeler transform for string '{s}' results " f"in '{result['bwt_string']}'" ) original_string = reverse_bwt(result["bwt_string"], result["idx_original_string"]) print( f"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " f"we get original string '{original_string}'" )
1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functions for downloading and reading MNIST data (deprecated). This module and all its submodules are deprecated. """ import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _Datasets = collections.namedtuple("_Datasets", ["train", "validation", "test"]) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ DEFAULT_SOURCE_URL = "https://storage.googleapis.com/cvdf-datasets/mnist/" def _read32(bytestream): dt = numpy.dtype(numpy.uint32).newbyteorder(">") return numpy.frombuffer(bytestream.read(4), dtype=dt)[0] @deprecated(None, "Please use tf.data to implement this functionality.") def _extract_images(f): """Extract the images into a 4D uint8 numpy array [index, y, x, depth]. Args: f: A file object that can be passed into a gzip reader. Returns: data: A 4D uint8 numpy array [index, y, x, depth]. Raises: ValueError: If the bytestream does not start with 2051. """ print("Extracting", f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) if magic != 2051: raise ValueError( "Invalid magic number %d in MNIST image file: %s" % (magic, f.name) ) num_images = _read32(bytestream) rows = _read32(bytestream) cols = _read32(bytestream) buf = bytestream.read(rows * cols * num_images) data = numpy.frombuffer(buf, dtype=numpy.uint8) data = data.reshape(num_images, rows, cols, 1) return data @deprecated(None, "Please use tf.one_hot on tensors.") def _dense_to_one_hot(labels_dense, num_classes): """Convert class labels from scalars to one-hot vectors.""" num_labels = labels_dense.shape[0] index_offset = numpy.arange(num_labels) * num_classes labels_one_hot = numpy.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot @deprecated(None, "Please use tf.data to implement this functionality.") def _extract_labels(f, one_hot=False, num_classes=10): """Extract the labels into a 1D uint8 numpy array [index]. Args: f: A file object that can be passed into a gzip reader. one_hot: Does one hot encoding for the result. num_classes: Number of classes for the one hot encoding. Returns: labels: a 1D uint8 numpy array. Raises: ValueError: If the bystream doesn't start with 2049. """ print("Extracting", f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) if magic != 2049: raise ValueError( "Invalid magic number %d in MNIST label file: %s" % (magic, f.name) ) num_items = _read32(bytestream) buf = bytestream.read(num_items) labels = numpy.frombuffer(buf, dtype=numpy.uint8) if one_hot: return _dense_to_one_hot(labels, num_classes) return labels class _DataSet: """Container class for a _DataSet (deprecated). THIS CLASS IS DEPRECATED. """ @deprecated( None, "Please use alternatives such as official/mnist/_DataSet.py" " from tensorflow/models.", ) def __init__( self, images, labels, fake_data=False, one_hot=False, dtype=dtypes.float32, reshape=True, seed=None, ): """Construct a _DataSet. one_hot arg is used only if fake_data is true. `dtype` can be either `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into `[0, 1]`. Seed arg provides for convenient deterministic testing. Args: images: The images labels: The labels fake_data: Ignore inages and labels, use fake data. one_hot: Bool, return the labels as one hot vectors (if True) or ints (if False). dtype: Output image dtype. One of [uint8, float32]. `uint8` output has range [0,255]. float32 output has range [0,1]. reshape: Bool. If True returned images are returned flattened to vectors. seed: The random seed to use. """ seed1, seed2 = random_seed.get_seed(seed) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seed1 if seed is None else seed2) dtype = dtypes.as_dtype(dtype).base_dtype if dtype not in (dtypes.uint8, dtypes.float32): raise TypeError("Invalid image dtype %r, expected uint8 or float32" % dtype) if fake_data: self._num_examples = 10000 self.one_hot = one_hot else: assert ( images.shape[0] == labels.shape[0] ), f"images.shape: {images.shape} labels.shape: {labels.shape}" self._num_examples = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 images = images.reshape( images.shape[0], images.shape[1] * images.shape[2] ) if dtype == dtypes.float32: # Convert from [0, 255] -> [0.0, 1.0]. images = images.astype(numpy.float32) images = numpy.multiply(images, 1.0 / 255.0) self._images = images self._labels = labels self._epochs_completed = 0 self._index_in_epoch = 0 @property def images(self): return self._images @property def labels(self): return self._labels @property def num_examples(self): return self._num_examples @property def epochs_completed(self): return self._epochs_completed def next_batch(self, batch_size, fake_data=False, shuffle=True): """Return the next `batch_size` examples from this data set.""" if fake_data: fake_image = [1] * 784 fake_label = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(batch_size)], [fake_label for _ in range(batch_size)], ) start = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: perm0 = numpy.arange(self._num_examples) numpy.random.shuffle(perm0) self._images = self.images[perm0] self._labels = self.labels[perm0] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch rest_num_examples = self._num_examples - start images_rest_part = self._images[start : self._num_examples] labels_rest_part = self._labels[start : self._num_examples] # Shuffle the data if shuffle: perm = numpy.arange(self._num_examples) numpy.random.shuffle(perm) self._images = self.images[perm] self._labels = self.labels[perm] # Start next epoch start = 0 self._index_in_epoch = batch_size - rest_num_examples end = self._index_in_epoch images_new_part = self._images[start:end] labels_new_part = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part), axis=0), numpy.concatenate((labels_rest_part, labels_new_part), axis=0), ) else: self._index_in_epoch += batch_size end = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(None, "Please write your own downloading logic.") def _maybe_download(filename, work_directory, source_url): """Download the data from source url, unless it's already here. Args: filename: string, name of the file in the directory. work_directory: string, path to working directory. source_url: url to download from if file doesn't exist. Returns: Path to resulting file. """ if not gfile.Exists(work_directory): gfile.MakeDirs(work_directory) filepath = os.path.join(work_directory, filename) if not gfile.Exists(filepath): urllib.request.urlretrieve(source_url, filepath) # noqa: S310 with gfile.GFile(filepath) as f: size = f.size() print("Successfully downloaded", filename, size, "bytes.") return filepath @deprecated( None, "Please use alternatives such as:" " tensorflow_datasets.load('mnist')" ) def read_data_sets( train_dir, fake_data=False, one_hot=False, dtype=dtypes.float32, reshape=True, validation_size=5000, seed=None, source_url=DEFAULT_SOURCE_URL, ): if fake_data: def fake(): return _DataSet( [], [], fake_data=True, one_hot=one_hot, dtype=dtype, seed=seed ) train = fake() validation = fake() test = fake() return _Datasets(train=train, validation=validation, test=test) if not source_url: # empty string check source_url = DEFAULT_SOURCE_URL train_images_file = "train-images-idx3-ubyte.gz" train_labels_file = "train-labels-idx1-ubyte.gz" test_images_file = "t10k-images-idx3-ubyte.gz" test_labels_file = "t10k-labels-idx1-ubyte.gz" local_file = _maybe_download( train_images_file, train_dir, source_url + train_images_file ) with gfile.Open(local_file, "rb") as f: train_images = _extract_images(f) local_file = _maybe_download( train_labels_file, train_dir, source_url + train_labels_file ) with gfile.Open(local_file, "rb") as f: train_labels = _extract_labels(f, one_hot=one_hot) local_file = _maybe_download( test_images_file, train_dir, source_url + test_images_file ) with gfile.Open(local_file, "rb") as f: test_images = _extract_images(f) local_file = _maybe_download( test_labels_file, train_dir, source_url + test_labels_file ) with gfile.Open(local_file, "rb") as f: test_labels = _extract_labels(f, one_hot=one_hot) if not 0 <= validation_size <= len(train_images): msg = ( "Validation size should be between 0 and " f"{len(train_images)}. Received: {validation_size}." ) raise ValueError(msg) validation_images = train_images[:validation_size] validation_labels = train_labels[:validation_size] train_images = train_images[validation_size:] train_labels = train_labels[validation_size:] options = {"dtype": dtype, "reshape": reshape, "seed": seed} train = _DataSet(train_images, train_labels, **options) validation = _DataSet(validation_images, validation_labels, **options) test = _DataSet(test_images, test_labels, **options) return _Datasets(train=train, validation=validation, test=test)
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functions for downloading and reading MNIST data (deprecated). This module and all its submodules are deprecated. """ import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _Datasets = collections.namedtuple("_Datasets", ["train", "validation", "test"]) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ DEFAULT_SOURCE_URL = "https://storage.googleapis.com/cvdf-datasets/mnist/" def _read32(bytestream): dt = numpy.dtype(numpy.uint32).newbyteorder(">") return numpy.frombuffer(bytestream.read(4), dtype=dt)[0] @deprecated(None, "Please use tf.data to implement this functionality.") def _extract_images(f): """Extract the images into a 4D uint8 numpy array [index, y, x, depth]. Args: f: A file object that can be passed into a gzip reader. Returns: data: A 4D uint8 numpy array [index, y, x, depth]. Raises: ValueError: If the bytestream does not start with 2051. """ print("Extracting", f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) if magic != 2051: raise ValueError( "Invalid magic number %d in MNIST image file: %s" % (magic, f.name) ) num_images = _read32(bytestream) rows = _read32(bytestream) cols = _read32(bytestream) buf = bytestream.read(rows * cols * num_images) data = numpy.frombuffer(buf, dtype=numpy.uint8) data = data.reshape(num_images, rows, cols, 1) return data @deprecated(None, "Please use tf.one_hot on tensors.") def _dense_to_one_hot(labels_dense, num_classes): """Convert class labels from scalars to one-hot vectors.""" num_labels = labels_dense.shape[0] index_offset = numpy.arange(num_labels) * num_classes labels_one_hot = numpy.zeros((num_labels, num_classes)) labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 return labels_one_hot @deprecated(None, "Please use tf.data to implement this functionality.") def _extract_labels(f, one_hot=False, num_classes=10): """Extract the labels into a 1D uint8 numpy array [index]. Args: f: A file object that can be passed into a gzip reader. one_hot: Does one hot encoding for the result. num_classes: Number of classes for the one hot encoding. Returns: labels: a 1D uint8 numpy array. Raises: ValueError: If the bystream doesn't start with 2049. """ print("Extracting", f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) if magic != 2049: raise ValueError( "Invalid magic number %d in MNIST label file: %s" % (magic, f.name) ) num_items = _read32(bytestream) buf = bytestream.read(num_items) labels = numpy.frombuffer(buf, dtype=numpy.uint8) if one_hot: return _dense_to_one_hot(labels, num_classes) return labels class _DataSet: """Container class for a _DataSet (deprecated). THIS CLASS IS DEPRECATED. """ @deprecated( None, "Please use alternatives such as official/mnist/_DataSet.py" " from tensorflow/models.", ) def __init__( self, images, labels, fake_data=False, one_hot=False, dtype=dtypes.float32, reshape=True, seed=None, ): """Construct a _DataSet. one_hot arg is used only if fake_data is true. `dtype` can be either `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into `[0, 1]`. Seed arg provides for convenient deterministic testing. Args: images: The images labels: The labels fake_data: Ignore inages and labels, use fake data. one_hot: Bool, return the labels as one hot vectors (if True) or ints (if False). dtype: Output image dtype. One of [uint8, float32]. `uint8` output has range [0,255]. float32 output has range [0,1]. reshape: Bool. If True returned images are returned flattened to vectors. seed: The random seed to use. """ seed1, seed2 = random_seed.get_seed(seed) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seed1 if seed is None else seed2) dtype = dtypes.as_dtype(dtype).base_dtype if dtype not in (dtypes.uint8, dtypes.float32): raise TypeError("Invalid image dtype %r, expected uint8 or float32" % dtype) if fake_data: self._num_examples = 10000 self.one_hot = one_hot else: assert ( images.shape[0] == labels.shape[0] ), f"images.shape: {images.shape} labels.shape: {labels.shape}" self._num_examples = images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 images = images.reshape( images.shape[0], images.shape[1] * images.shape[2] ) if dtype == dtypes.float32: # Convert from [0, 255] -> [0.0, 1.0]. images = images.astype(numpy.float32) images = numpy.multiply(images, 1.0 / 255.0) self._images = images self._labels = labels self._epochs_completed = 0 self._index_in_epoch = 0 @property def images(self): return self._images @property def labels(self): return self._labels @property def num_examples(self): return self._num_examples @property def epochs_completed(self): return self._epochs_completed def next_batch(self, batch_size, fake_data=False, shuffle=True): """Return the next `batch_size` examples from this data set.""" if fake_data: fake_image = [1] * 784 fake_label = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(batch_size)], [fake_label for _ in range(batch_size)], ) start = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: perm0 = numpy.arange(self._num_examples) numpy.random.shuffle(perm0) self._images = self.images[perm0] self._labels = self.labels[perm0] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch rest_num_examples = self._num_examples - start images_rest_part = self._images[start : self._num_examples] labels_rest_part = self._labels[start : self._num_examples] # Shuffle the data if shuffle: perm = numpy.arange(self._num_examples) numpy.random.shuffle(perm) self._images = self.images[perm] self._labels = self.labels[perm] # Start next epoch start = 0 self._index_in_epoch = batch_size - rest_num_examples end = self._index_in_epoch images_new_part = self._images[start:end] labels_new_part = self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part), axis=0), numpy.concatenate((labels_rest_part, labels_new_part), axis=0), ) else: self._index_in_epoch += batch_size end = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(None, "Please write your own downloading logic.") def _maybe_download(filename, work_directory, source_url): """Download the data from source url, unless it's already here. Args: filename: string, name of the file in the directory. work_directory: string, path to working directory. source_url: url to download from if file doesn't exist. Returns: Path to resulting file. """ if not gfile.Exists(work_directory): gfile.MakeDirs(work_directory) filepath = os.path.join(work_directory, filename) if not gfile.Exists(filepath): urllib.request.urlretrieve(source_url, filepath) # noqa: S310 with gfile.GFile(filepath) as f: size = f.size() print("Successfully downloaded", filename, size, "bytes.") return filepath @deprecated(None, "Please use alternatives such as: tensorflow_datasets.load('mnist')") def read_data_sets( train_dir, fake_data=False, one_hot=False, dtype=dtypes.float32, reshape=True, validation_size=5000, seed=None, source_url=DEFAULT_SOURCE_URL, ): if fake_data: def fake(): return _DataSet( [], [], fake_data=True, one_hot=one_hot, dtype=dtype, seed=seed ) train = fake() validation = fake() test = fake() return _Datasets(train=train, validation=validation, test=test) if not source_url: # empty string check source_url = DEFAULT_SOURCE_URL train_images_file = "train-images-idx3-ubyte.gz" train_labels_file = "train-labels-idx1-ubyte.gz" test_images_file = "t10k-images-idx3-ubyte.gz" test_labels_file = "t10k-labels-idx1-ubyte.gz" local_file = _maybe_download( train_images_file, train_dir, source_url + train_images_file ) with gfile.Open(local_file, "rb") as f: train_images = _extract_images(f) local_file = _maybe_download( train_labels_file, train_dir, source_url + train_labels_file ) with gfile.Open(local_file, "rb") as f: train_labels = _extract_labels(f, one_hot=one_hot) local_file = _maybe_download( test_images_file, train_dir, source_url + test_images_file ) with gfile.Open(local_file, "rb") as f: test_images = _extract_images(f) local_file = _maybe_download( test_labels_file, train_dir, source_url + test_labels_file ) with gfile.Open(local_file, "rb") as f: test_labels = _extract_labels(f, one_hot=one_hot) if not 0 <= validation_size <= len(train_images): msg = ( "Validation size should be between 0 and " f"{len(train_images)}. Received: {validation_size}." ) raise ValueError(msg) validation_images = train_images[:validation_size] validation_labels = train_labels[:validation_size] train_images = train_images[validation_size:] train_labels = train_labels[validation_size:] options = {"dtype": dtype, "reshape": reshape, "seed": seed} train = _DataSet(train_images, train_labels, **options) validation = _DataSet(validation_images, validation_labels, **options) test = _DataSet(test_images, test_labels, **options) return _Datasets(train=train, validation=validation, test=test)
1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
[tool.ruff] ignore = [ # `ruff rule S101` for a description of that rule "ARG001", # Unused function argument `amount` -- FIX ME? "B904", # Within an `except` clause, raise exceptions with `raise ... from err` -- FIX ME "B905", # `zip()` without an explicit `strict=` parameter -- FIX ME "DTZ001", # The use of `datetime.datetime()` without `tzinfo` argument is not allowed -- FIX ME "DTZ005", # The use of `datetime.datetime.now()` without `tzinfo` argument is not allowed -- FIX ME "E741", # Ambiguous variable name 'l' -- FIX ME "EM101", # Exception must not use a string literal, assign to variable first "EXE001", # Shebang is present but file is not executable" -- FIX ME "G004", # Logging statement uses f-string "ICN001", # `matplotlib.pyplot` should be imported as `plt` -- FIX ME "INP001", # File `x/y/z.py` is part of an implicit namespace package. Add an `__init__.py`. -- FIX ME "N999", # Invalid module name -- FIX ME "NPY002", # Replace legacy `np.random.choice` call with `np.random.Generator` -- FIX ME "PGH003", # Use specific rule codes when ignoring type issues -- FIX ME "PLC1901", # `{}` can be simplified to `{}` as an empty string is falsey "PLR5501", # Consider using `elif` instead of `else` -- FIX ME "PLW0120", # `else` clause on loop without a `break` statement -- FIX ME "PLW060", # Using global for `{name}` but no assignment is done -- DO NOT FIX "PLW2901", # PLW2901: Redefined loop variable -- FIX ME "RUF00", # Ambiguous unicode character and other rules "RUF100", # Unused `noqa` directive -- FIX ME "S101", # Use of `assert` detected -- DO NOT FIX "S105", # Possible hardcoded password: 'password' "S113", # Probable use of requests call without timeout -- FIX ME "S311", # Standard pseudo-random generators are not suitable for cryptographic purposes -- FIX ME "SIM102", # Use a single `if` statement instead of nested `if` statements -- FIX ME "SLF001", # Private member accessed: `_Iterator` -- FIX ME "UP038", # Use `X | Y` in `{}` call instead of `(X, Y)` -- DO NOT FIX ] select = [ # https://beta.ruff.rs/docs/rules "A", # flake8-builtins "ARG", # flake8-unused-arguments "ASYNC", # flake8-async "B", # flake8-bugbear "BLE", # flake8-blind-except "C4", # flake8-comprehensions "C90", # McCabe cyclomatic complexity "DTZ", # flake8-datetimez "E", # pycodestyle "EM", # flake8-errmsg "EXE", # flake8-executable "F", # Pyflakes "FA", # flake8-future-annotations "FLY", # flynt "G", # flake8-logging-format "I", # isort "ICN", # flake8-import-conventions "INP", # flake8-no-pep420 "INT", # flake8-gettext "N", # pep8-naming "NPY", # NumPy-specific rules "PGH", # pygrep-hooks "PIE", # flake8-pie "PL", # Pylint "PYI", # flake8-pyi "RSE", # flake8-raise "RUF", # Ruff-specific rules "S", # flake8-bandit "SIM", # flake8-simplify "SLF", # flake8-self "T10", # flake8-debugger "TD", # flake8-todos "TID", # flake8-tidy-imports "UP", # pyupgrade "W", # pycodestyle "YTT", # flake8-2020 # "ANN", # flake8-annotations # FIX ME? # "COM", # flake8-commas # "D", # pydocstyle -- FIX ME? # "DJ", # flake8-django # "ERA", # eradicate -- DO NOT FIX # "FBT", # flake8-boolean-trap # FIX ME # "ISC", # flake8-implicit-str-concat # FIX ME # "PD", # pandas-vet # "PT", # flake8-pytest-style # "PTH", # flake8-use-pathlib # FIX ME # "Q", # flake8-quotes # "RET", # flake8-return # FIX ME? # "T20", # flake8-print # "TCH", # flake8-type-checking # "TRY", # tryceratops ] show-source = true target-version = "py311" [tool.ruff.mccabe] # DO NOT INCREASE THIS VALUE max-complexity = 17 # default: 10 [tool.ruff.per-file-ignores] "arithmetic_analysis/newton_raphson.py" = ["PGH001"] "audio_filters/show_response.py" = ["ARG002"] "data_structures/binary_tree/binary_search_tree_recursive.py" = ["BLE001"] "data_structures/binary_tree/treap.py" = ["SIM114"] "data_structures/hashing/hash_table.py" = ["ARG002"] "data_structures/hashing/quadratic_probing.py" = ["ARG002"] "data_structures/hashing/tests/test_hash_map.py" = ["BLE001"] "data_structures/heap/max_heap.py" = ["SIM114"] "graphs/minimum_spanning_tree_prims.py" = ["SIM114"] "hashes/enigma_machine.py" = ["BLE001"] "machine_learning/decision_tree.py" = ["SIM114"] "machine_learning/linear_discriminant_analysis.py" = ["ARG005"] "machine_learning/sequential_minimum_optimization.py" = ["SIM115"] "matrix/sherman_morrison.py" = ["SIM103", "SIM114"] "other/l*u_cache.py" = ["RUF012"] "physics/newtons_second_law_of_motion.py" = ["BLE001"] "project_euler/problem_099/sol1.py" = ["SIM115"] "sorts/external_sort.py" = ["SIM115"] [tool.ruff.pylint] # DO NOT INCREASE THESE VALUES allow-magic-value-types = ["float", "int", "str"] max-args = 10 # default: 5 max-branches = 20 # default: 12 max-returns = 8 # default: 6 max-statements = 88 # default: 50 [tool.pytest.ini_options] markers = [ "mat_ops: mark a test as utilizing matrix operations.", ] addopts = [ "--durations=10", "--doctest-modules", "--showlocals", ] [tool.coverage.report] omit = [".env/*"] sort = "Cover" [tool.codespell] ignore-words-list = "3rt,ans,crate,damon,fo,followings,hist,iff,kwanza,mater,secant,som,sur,tim,zar" skip = "./.*,*.json,ciphers/prehistoric_men.txt,project_euler/problem_022/p022_names.txt,pyproject.toml,strings/dictionary.txt,strings/words.txt"
[tool.ruff] ignore = [ # `ruff rule S101` for a description of that rule "ARG001", # Unused function argument `amount` -- FIX ME? "B904", # Within an `except` clause, raise exceptions with `raise ... from err` -- FIX ME "B905", # `zip()` without an explicit `strict=` parameter -- FIX ME "DTZ001", # The use of `datetime.datetime()` without `tzinfo` argument is not allowed -- FIX ME "DTZ005", # The use of `datetime.datetime.now()` without `tzinfo` argument is not allowed -- FIX ME "E741", # Ambiguous variable name 'l' -- FIX ME "EM101", # Exception must not use a string literal, assign to variable first "EXE001", # Shebang is present but file is not executable" -- FIX ME "G004", # Logging statement uses f-string "ICN001", # `matplotlib.pyplot` should be imported as `plt` -- FIX ME "INP001", # File `x/y/z.py` is part of an implicit namespace package. Add an `__init__.py`. -- FIX ME "N999", # Invalid module name -- FIX ME "NPY002", # Replace legacy `np.random.choice` call with `np.random.Generator` -- FIX ME "PGH003", # Use specific rule codes when ignoring type issues -- FIX ME "PLC1901", # `{}` can be simplified to `{}` as an empty string is falsey "PLR5501", # Consider using `elif` instead of `else` -- FIX ME "PLW0120", # `else` clause on loop without a `break` statement -- FIX ME "PLW060", # Using global for `{name}` but no assignment is done -- DO NOT FIX "PLW2901", # PLW2901: Redefined loop variable -- FIX ME "RUF00", # Ambiguous unicode character and other rules "RUF100", # Unused `noqa` directive -- FIX ME "S101", # Use of `assert` detected -- DO NOT FIX "S105", # Possible hardcoded password: 'password' "S113", # Probable use of requests call without timeout -- FIX ME "S311", # Standard pseudo-random generators are not suitable for cryptographic purposes -- FIX ME "SIM102", # Use a single `if` statement instead of nested `if` statements -- FIX ME "SLF001", # Private member accessed: `_Iterator` -- FIX ME "UP038", # Use `X | Y` in `{}` call instead of `(X, Y)` -- DO NOT FIX ] select = [ # https://beta.ruff.rs/docs/rules "A", # flake8-builtins "ARG", # flake8-unused-arguments "ASYNC", # flake8-async "B", # flake8-bugbear "BLE", # flake8-blind-except "C4", # flake8-comprehensions "C90", # McCabe cyclomatic complexity "DTZ", # flake8-datetimez "E", # pycodestyle "EM", # flake8-errmsg "EXE", # flake8-executable "F", # Pyflakes "FA", # flake8-future-annotations "FLY", # flynt "G", # flake8-logging-format "I", # isort "ICN", # flake8-import-conventions "INP", # flake8-no-pep420 "INT", # flake8-gettext "ISC", # flake8-implicit-str-concat "N", # pep8-naming "NPY", # NumPy-specific rules "PGH", # pygrep-hooks "PIE", # flake8-pie "PL", # Pylint "PYI", # flake8-pyi "RSE", # flake8-raise "RUF", # Ruff-specific rules "S", # flake8-bandit "SIM", # flake8-simplify "SLF", # flake8-self "T10", # flake8-debugger "TD", # flake8-todos "TID", # flake8-tidy-imports "UP", # pyupgrade "W", # pycodestyle "YTT", # flake8-2020 # "ANN", # flake8-annotations # FIX ME? # "COM", # flake8-commas # "D", # pydocstyle -- FIX ME? # "DJ", # flake8-django # "ERA", # eradicate -- DO NOT FIX # "FBT", # flake8-boolean-trap # FIX ME # "PD", # pandas-vet # "PT", # flake8-pytest-style # "PTH", # flake8-use-pathlib # FIX ME # "Q", # flake8-quotes # "RET", # flake8-return # FIX ME? # "T20", # flake8-print # "TCH", # flake8-type-checking # "TRY", # tryceratops ] show-source = true target-version = "py311" [tool.ruff.mccabe] # DO NOT INCREASE THIS VALUE max-complexity = 17 # default: 10 [tool.ruff.per-file-ignores] "arithmetic_analysis/newton_raphson.py" = ["PGH001"] "audio_filters/show_response.py" = ["ARG002"] "data_structures/binary_tree/binary_search_tree_recursive.py" = ["BLE001"] "data_structures/binary_tree/treap.py" = ["SIM114"] "data_structures/hashing/hash_table.py" = ["ARG002"] "data_structures/hashing/quadratic_probing.py" = ["ARG002"] "data_structures/hashing/tests/test_hash_map.py" = ["BLE001"] "data_structures/heap/max_heap.py" = ["SIM114"] "graphs/minimum_spanning_tree_prims.py" = ["SIM114"] "hashes/enigma_machine.py" = ["BLE001"] "machine_learning/decision_tree.py" = ["SIM114"] "machine_learning/linear_discriminant_analysis.py" = ["ARG005"] "machine_learning/sequential_minimum_optimization.py" = ["SIM115"] "matrix/sherman_morrison.py" = ["SIM103", "SIM114"] "other/l*u_cache.py" = ["RUF012"] "physics/newtons_second_law_of_motion.py" = ["BLE001"] "project_euler/problem_099/sol1.py" = ["SIM115"] "sorts/external_sort.py" = ["SIM115"] [tool.ruff.pylint] # DO NOT INCREASE THESE VALUES allow-magic-value-types = ["float", "int", "str"] max-args = 10 # default: 5 max-branches = 20 # default: 12 max-returns = 8 # default: 6 max-statements = 88 # default: 50 [tool.pytest.ini_options] markers = [ "mat_ops: mark a test as utilizing matrix operations.", ] addopts = [ "--durations=10", "--doctest-modules", "--showlocals", ] [tool.coverage.report] omit = [".env/*"] sort = "Cover" [tool.codespell] ignore-words-list = "3rt,ans,crate,damon,fo,followings,hist,iff,kwanza,mater,secant,som,sur,tim,zar" skip = "./.*,*.json,ciphers/prehistoric_men.txt,project_euler/problem_022/p022_names.txt,pyproject.toml,strings/dictionary.txt,strings/words.txt"
1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
import re def is_sri_lankan_phone_number(phone: str) -> bool: """ Determine whether the string is a valid sri lankan mobile phone number or not References: https://aye.sh/blog/sri-lankan-phone-number-regex >>> is_sri_lankan_phone_number("+94773283048") True >>> is_sri_lankan_phone_number("+9477-3283048") True >>> is_sri_lankan_phone_number("0718382399") True >>> is_sri_lankan_phone_number("0094702343221") True >>> is_sri_lankan_phone_number("075 3201568") True >>> is_sri_lankan_phone_number("07779209245") False >>> is_sri_lankan_phone_number("0957651234") False """ pattern = re.compile( r"^(?:0|94|\+94|0{2}94)" r"7(0|1|2|4|5|6|7|8)" r"(-| |)" r"\d{7}$" ) return bool(re.search(pattern, phone)) if __name__ == "__main__": phone = "0094702343221" print(is_sri_lankan_phone_number(phone))
import re def is_sri_lankan_phone_number(phone: str) -> bool: """ Determine whether the string is a valid sri lankan mobile phone number or not References: https://aye.sh/blog/sri-lankan-phone-number-regex >>> is_sri_lankan_phone_number("+94773283048") True >>> is_sri_lankan_phone_number("+9477-3283048") True >>> is_sri_lankan_phone_number("0718382399") True >>> is_sri_lankan_phone_number("0094702343221") True >>> is_sri_lankan_phone_number("075 3201568") True >>> is_sri_lankan_phone_number("07779209245") False >>> is_sri_lankan_phone_number("0957651234") False """ pattern = re.compile(r"^(?:0|94|\+94|0{2}94)7(0|1|2|4|5|6|7|8)(-| |)\d{7}$") return bool(re.search(pattern, phone)) if __name__ == "__main__": phone = "0094702343221" print(is_sri_lankan_phone_number(phone))
1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
#!/usr/bin/env python3 """ Provide the current worldwide COVID-19 statistics. This data is being scrapped from 'https://www.worldometers.info/coronavirus/'. """ import requests from bs4 import BeautifulSoup def world_covid19_stats(url: str = "https://www.worldometers.info/coronavirus") -> dict: """ Return a dict of current worldwide COVID-19 statistics """ soup = BeautifulSoup(requests.get(url).text, "html.parser") keys = soup.findAll("h1") values = soup.findAll("div", {"class": "maincounter-number"}) keys += soup.findAll("span", {"class": "panel-title"}) values += soup.findAll("div", {"class": "number-table-main"}) return {key.text.strip(): value.text.strip() for key, value in zip(keys, values)} if __name__ == "__main__": print("\033[1m" + "COVID-19 Status of the World" + "\033[0m\n") for key, value in world_covid19_stats().items(): print(f"{key}\n{value}\n")
#!/usr/bin/env python3 """ Provide the current worldwide COVID-19 statistics. This data is being scrapped from 'https://www.worldometers.info/coronavirus/'. """ import requests from bs4 import BeautifulSoup def world_covid19_stats(url: str = "https://www.worldometers.info/coronavirus") -> dict: """ Return a dict of current worldwide COVID-19 statistics """ soup = BeautifulSoup(requests.get(url).text, "html.parser") keys = soup.findAll("h1") values = soup.findAll("div", {"class": "maincounter-number"}) keys += soup.findAll("span", {"class": "panel-title"}) values += soup.findAll("div", {"class": "number-table-main"}) return {key.text.strip(): value.text.strip() for key, value in zip(keys, values)} if __name__ == "__main__": print("\033[1m COVID-19 Status of the World \033[0m\n") print("\n".join(f"{key}\n{value}" for key, value in world_covid19_stats().items()))
1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# Check whether Graph is Bipartite or Not using DFS # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def check_bipartite_dfs(graph): visited = [False] * len(graph) color = [-1] * len(graph) def dfs(v, c): visited[v] = True color[v] = c for u in graph[v]: if not visited[u]: dfs(u, 1 - c) for i in range(len(graph)): if not visited[i]: dfs(i, 0) for i in range(len(graph)): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph graph = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
# Check whether Graph is Bipartite or Not using DFS # A Bipartite Graph is a graph whose vertices can be divided into two independent sets, # U and V such that every edge (u, v) either connects a vertex from U to V or a vertex # from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, # or u belongs to V and v to U. We can also say that there is no edge that connects # vertices of same set. def check_bipartite_dfs(graph): visited = [False] * len(graph) color = [-1] * len(graph) def dfs(v, c): visited[v] = True color[v] = c for u in graph[v]: if not visited[u]: dfs(u, 1 - c) for i in range(len(graph)): if not visited[i]: dfs(i, 0) for i in range(len(graph)): for j in graph[i]: if color[i] == color[j]: return False return True # Adjacency list of graph graph = {0: [1, 3], 1: [0, 2], 2: [1, 3], 3: [0, 2], 4: []} print(check_bipartite_dfs(graph))
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# 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 visited[t] def ford_fulkerson(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(ford_fulkerson(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 visited[t] def ford_fulkerson(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(ford_fulkerson(graph, source, sink))
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
def get_highest_set_bit_position(number: int) -> int: """ Returns position of the highest set bit of a number. Ref - https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious >>> get_highest_set_bit_position(25) 5 >>> get_highest_set_bit_position(37) 6 >>> get_highest_set_bit_position(1) 1 >>> get_highest_set_bit_position(4) 3 >>> get_highest_set_bit_position(0) 0 >>> get_highest_set_bit_position(0.8) Traceback (most recent call last): ... TypeError: Input value must be an 'int' type """ if not isinstance(number, int): raise TypeError("Input value must be an 'int' type") position = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
def get_highest_set_bit_position(number: int) -> int: """ Returns position of the highest set bit of a number. Ref - https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious >>> get_highest_set_bit_position(25) 5 >>> get_highest_set_bit_position(37) 6 >>> get_highest_set_bit_position(1) 1 >>> get_highest_set_bit_position(4) 3 >>> get_highest_set_bit_position(0) 0 >>> get_highest_set_bit_position(0.8) Traceback (most recent call last): ... TypeError: Input value must be an 'int' type """ if not isinstance(number, int): raise TypeError("Input value must be an 'int' type") position = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Problem Statement (Digit Fifth Powers): https://projecteuler.net/problem=30 Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 1^4 + 6^4 + 3^4 + 4^4 8208 = 8^4 + 2^4 + 0^4 + 8^4 9474 = 9^4 + 4^4 + 7^4 + 4^4 As 1 = 1^4 is not a sum it is not included. The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. 9^5 = 59049 59049 * 7 = 413343 (which is only 6 digit number) So, numbers greater than 999999 are rejected and also 59049 * 3 = 177147 (which exceeds the criteria of number being 3 digit) So, number > 999 and hence a number between 1000 and 1000000 """ DIGITS_FIFTH_POWER = {str(digit): digit**5 for digit in range(10)} def digits_fifth_powers_sum(number: int) -> int: """ >>> digits_fifth_powers_sum(1234) 1300 """ return sum(DIGITS_FIFTH_POWER[digit] for digit in str(number)) def solution() -> int: return sum( number for number in range(1000, 1000000) if number == digits_fifth_powers_sum(number) ) if __name__ == "__main__": print(solution())
""" Problem Statement (Digit Fifth Powers): https://projecteuler.net/problem=30 Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 1^4 + 6^4 + 3^4 + 4^4 8208 = 8^4 + 2^4 + 0^4 + 8^4 9474 = 9^4 + 4^4 + 7^4 + 4^4 As 1 = 1^4 is not a sum it is not included. The sum of these numbers is 1634 + 8208 + 9474 = 19316. Find the sum of all the numbers that can be written as the sum of fifth powers of their digits. 9^5 = 59049 59049 * 7 = 413343 (which is only 6 digit number) So, numbers greater than 999999 are rejected and also 59049 * 3 = 177147 (which exceeds the criteria of number being 3 digit) So, number > 999 and hence a number between 1000 and 1000000 """ DIGITS_FIFTH_POWER = {str(digit): digit**5 for digit in range(10)} def digits_fifth_powers_sum(number: int) -> int: """ >>> digits_fifth_powers_sum(1234) 1300 """ return sum(DIGITS_FIFTH_POWER[digit] for digit in str(number)) def solution() -> int: return sum( number for number in range(1000, 1000000) if number == digits_fifth_powers_sum(number) ) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word. Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words? """ import os # Precomputes a list of the 100 first triangular numbers TRIANGULAR_NUMBERS = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def solution(): """ Finds the amount of triangular words in the words file. >>> solution() 162 """ script_dir = os.path.dirname(os.path.realpath(__file__)) words_file_path = os.path.join(script_dir, "words.txt") words = "" with open(words_file_path) as f: words = f.readline() words = [word.strip('"') for word in words.strip("\r\n").split(",")] words = [ word for word in [sum(ord(x) - 64 for x in word) for word in words] if word in TRIANGULAR_NUMBERS ] return len(words) if __name__ == "__main__": print(solution())
""" The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word. Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words? """ import os # Precomputes a list of the 100 first triangular numbers TRIANGULAR_NUMBERS = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def solution(): """ Finds the amount of triangular words in the words file. >>> solution() 162 """ script_dir = os.path.dirname(os.path.realpath(__file__)) words_file_path = os.path.join(script_dir, "words.txt") words = "" with open(words_file_path) as f: words = f.readline() words = [word.strip('"') for word in words.strip("\r\n").split(",")] words = [ word for word in [sum(ord(x) - 64 for x in word) for word in words] if word in TRIANGULAR_NUMBERS ] return len(words) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from graphs.minimum_spanning_tree_kruskal import kruskal def test_kruskal_successful_result(): num_nodes = 9 edges = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] result = kruskal(num_nodes, edges) expected = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(expected) == sorted(result)
from graphs.minimum_spanning_tree_kruskal import kruskal def test_kruskal_successful_result(): num_nodes = 9 edges = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] result = kruskal(num_nodes, edges) expected = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] assert sorted(expected) == sorted(result)
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Numerical integration or quadrature for a smooth function f with known values at x_i This method is the classical approach of suming 'Equally Spaced Abscissas' method 2: "Simpson Rule" """ def method_2(boundary, steps): # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a, b, h) y = 0.0 y += (h / 3.0) * f(a) cnt = 2 for i in x_i: y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i) cnt += 1 y += (h / 3.0) * f(b) return y def make_points(a, b, h): x = a + h while x < (b - h): yield x x = x + h def f(x): # enter your function here y = (x - 0) * (x - 0) return y def main(): a = 0.0 # Lower bound of integration b = 1.0 # Upper bound of integration steps = 10.0 # define number of steps or resolution boundary = [a, b] # define boundary of integration y = method_2(boundary, steps) print(f"y = {y}") if __name__ == "__main__": main()
""" Numerical integration or quadrature for a smooth function f with known values at x_i This method is the classical approach of suming 'Equally Spaced Abscissas' method 2: "Simpson Rule" """ def method_2(boundary, steps): # "Simpson Rule" # int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn) h = (boundary[1] - boundary[0]) / steps a = boundary[0] b = boundary[1] x_i = make_points(a, b, h) y = 0.0 y += (h / 3.0) * f(a) cnt = 2 for i in x_i: y += (h / 3) * (4 - 2 * (cnt % 2)) * f(i) cnt += 1 y += (h / 3.0) * f(b) return y def make_points(a, b, h): x = a + h while x < (b - h): yield x x = x + h def f(x): # enter your function here y = (x - 0) * (x - 0) return y def main(): a = 0.0 # Lower bound of integration b = 1.0 # Upper bound of integration steps = 10.0 # define number of steps or resolution boundary = [a, b] # define boundary of integration y = method_2(boundary, steps) print(f"y = {y}") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller min_primitive_root = 3 # I have written my code naively same as definition of primitive root # however every time I run this program, memory exceeded... # so I used 4.80 Algorithm in # Handbook of Applied Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996) # and it seems to run nicely! def primitive_root(p_val: int) -> int: print("Generating primitive root of p") while True: g = random.randrange(3, p_val) if pow(g, 2, p_val) == 1: continue if pow(g, p_val, p_val) == 1: continue return g def generate_key(key_size: int) -> tuple[tuple[int, int, int, int], tuple[int, int]]: print("Generating prime p...") p = rabin_miller.generate_large_prime(key_size) # select large prime number. e_1 = primitive_root(p) # one primitive root on modulo p. d = random.randrange(3, p) # private_key -> have to be greater than 2 for safety. e_2 = cryptomath.find_mod_inverse(pow(e_1, d, p), p) public_key = (key_size, e_1, e_2, p) private_key = (key_size, d) return public_key, private_key def make_key_files(name: str, key_size: int) -> None: if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"): print("\nWARNING:") print( f'"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n' "Use a different name or delete these files and re-run this program." ) sys.exit() public_key, private_key = generate_key(key_size) print(f"\nWriting public key to file {name}_pubkey.txt...") with open(f"{name}_pubkey.txt", "w") as fo: fo.write(f"{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}") print(f"Writing private key to file {name}_privkey.txt...") with open(f"{name}_privkey.txt", "w") as fo: fo.write(f"{private_key[0]},{private_key[1]}") def main() -> None: print("Making key files...") make_key_files("elgamal", 2048) print("Key files generation successful") if __name__ == "__main__": main()
import os import random import sys from . import cryptomath_module as cryptomath from . import rabin_miller min_primitive_root = 3 # I have written my code naively same as definition of primitive root # however every time I run this program, memory exceeded... # so I used 4.80 Algorithm in # Handbook of Applied Cryptography(CRC Press, ISBN : 0-8493-8523-7, October 1996) # and it seems to run nicely! def primitive_root(p_val: int) -> int: print("Generating primitive root of p") while True: g = random.randrange(3, p_val) if pow(g, 2, p_val) == 1: continue if pow(g, p_val, p_val) == 1: continue return g def generate_key(key_size: int) -> tuple[tuple[int, int, int, int], tuple[int, int]]: print("Generating prime p...") p = rabin_miller.generate_large_prime(key_size) # select large prime number. e_1 = primitive_root(p) # one primitive root on modulo p. d = random.randrange(3, p) # private_key -> have to be greater than 2 for safety. e_2 = cryptomath.find_mod_inverse(pow(e_1, d, p), p) public_key = (key_size, e_1, e_2, p) private_key = (key_size, d) return public_key, private_key def make_key_files(name: str, key_size: int) -> None: if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"): print("\nWARNING:") print( f'"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n' "Use a different name or delete these files and re-run this program." ) sys.exit() public_key, private_key = generate_key(key_size) print(f"\nWriting public key to file {name}_pubkey.txt...") with open(f"{name}_pubkey.txt", "w") as fo: fo.write(f"{public_key[0]},{public_key[1]},{public_key[2]},{public_key[3]}") print(f"Writing private key to file {name}_privkey.txt...") with open(f"{name}_privkey.txt", "w") as fo: fo.write(f"{private_key[0]},{private_key[1]}") def main() -> None: print("Making key files...") make_key_files("elgamal", 2048) print("Key files generation successful") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 82: https://projecteuler.net/problem=82 The minimal path sum in the 5 by 5 matrix below, by starting in any cell in the left column and finishing in any cell in the right column, and only moving up, down, and right, is indicated in red and bold; the sum is equal to 994. 131 673 [234] [103] [18] [201] [96] [342] 965 150 630 803 746 422 111 537 699 497 121 956 805 732 524 37 331 Find the minimal path sum from the left column to the right column in matrix.txt (https://projecteuler.net/project/resources/p082_matrix.txt) (right click and "Save Link/Target As..."), a 31K text file containing an 80 by 80 matrix. """ import os def solution(filename: str = "input.txt") -> int: """ Returns the minimal path sum in the matrix from the file, by starting in any cell in the left column and finishing in any cell in the right column, and only moving up, down, and right >>> solution("test_matrix.txt") 994 """ with open(os.path.join(os.path.dirname(__file__), filename)) as input_file: matrix = [ [int(element) for element in line.split(",")] for line in input_file.readlines() ] rows = len(matrix) cols = len(matrix[0]) minimal_path_sums = [[-1 for _ in range(cols)] for _ in range(rows)] for i in range(rows): minimal_path_sums[i][0] = matrix[i][0] for j in range(1, cols): for i in range(rows): minimal_path_sums[i][j] = minimal_path_sums[i][j - 1] + matrix[i][j] for i in range(1, rows): minimal_path_sums[i][j] = min( minimal_path_sums[i][j], minimal_path_sums[i - 1][j] + matrix[i][j] ) for i in range(rows - 2, -1, -1): minimal_path_sums[i][j] = min( minimal_path_sums[i][j], minimal_path_sums[i + 1][j] + matrix[i][j] ) return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 82: https://projecteuler.net/problem=82 The minimal path sum in the 5 by 5 matrix below, by starting in any cell in the left column and finishing in any cell in the right column, and only moving up, down, and right, is indicated in red and bold; the sum is equal to 994. 131 673 [234] [103] [18] [201] [96] [342] 965 150 630 803 746 422 111 537 699 497 121 956 805 732 524 37 331 Find the minimal path sum from the left column to the right column in matrix.txt (https://projecteuler.net/project/resources/p082_matrix.txt) (right click and "Save Link/Target As..."), a 31K text file containing an 80 by 80 matrix. """ import os def solution(filename: str = "input.txt") -> int: """ Returns the minimal path sum in the matrix from the file, by starting in any cell in the left column and finishing in any cell in the right column, and only moving up, down, and right >>> solution("test_matrix.txt") 994 """ with open(os.path.join(os.path.dirname(__file__), filename)) as input_file: matrix = [ [int(element) for element in line.split(",")] for line in input_file.readlines() ] rows = len(matrix) cols = len(matrix[0]) minimal_path_sums = [[-1 for _ in range(cols)] for _ in range(rows)] for i in range(rows): minimal_path_sums[i][0] = matrix[i][0] for j in range(1, cols): for i in range(rows): minimal_path_sums[i][j] = minimal_path_sums[i][j - 1] + matrix[i][j] for i in range(1, rows): minimal_path_sums[i][j] = min( minimal_path_sums[i][j], minimal_path_sums[i - 1][j] + matrix[i][j] ) for i in range(rows - 2, -1, -1): minimal_path_sums[i][j] = min( minimal_path_sums[i][j], minimal_path_sums[i + 1][j] + matrix[i][j] ) return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Problem 45: https://projecteuler.net/problem=45 Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: Triangle T(n) = (n * (n + 1)) / 2 1, 3, 6, 10, 15, ... Pentagonal P(n) = (n * (3 * n − 1)) / 2 1, 5, 12, 22, 35, ... Hexagonal H(n) = n * (2 * n − 1) 1, 6, 15, 28, 45, ... It can be verified that T(285) = P(165) = H(143) = 40755. Find the next triangle number that is also pentagonal and hexagonal. All triangle numbers are hexagonal numbers. T(2n-1) = n * (2 * n - 1) = H(n) So we shall check only for hexagonal numbers which are also pentagonal. """ def hexagonal_num(n: int) -> int: """ Returns nth hexagonal number >>> hexagonal_num(143) 40755 >>> hexagonal_num(21) 861 >>> hexagonal_num(10) 190 """ return n * (2 * n - 1) 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(start: int = 144) -> int: """ Returns the next number which is triangular, pentagonal and hexagonal. >>> solution(144) 1533776805 """ n = start num = hexagonal_num(n) while not is_pentagonal(num): n += 1 num = hexagonal_num(n) return num if __name__ == "__main__": print(f"{solution()} = ")
""" Problem 45: https://projecteuler.net/problem=45 Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: Triangle T(n) = (n * (n + 1)) / 2 1, 3, 6, 10, 15, ... Pentagonal P(n) = (n * (3 * n − 1)) / 2 1, 5, 12, 22, 35, ... Hexagonal H(n) = n * (2 * n − 1) 1, 6, 15, 28, 45, ... It can be verified that T(285) = P(165) = H(143) = 40755. Find the next triangle number that is also pentagonal and hexagonal. All triangle numbers are hexagonal numbers. T(2n-1) = n * (2 * n - 1) = H(n) So we shall check only for hexagonal numbers which are also pentagonal. """ def hexagonal_num(n: int) -> int: """ Returns nth hexagonal number >>> hexagonal_num(143) 40755 >>> hexagonal_num(21) 861 >>> hexagonal_num(10) 190 """ return n * (2 * n - 1) 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(start: int = 144) -> int: """ Returns the next number which is triangular, pentagonal and hexagonal. >>> solution(144) 1533776805 """ n = start num = hexagonal_num(n) while not is_pentagonal(num): n += 1 num = hexagonal_num(n) return num if __name__ == "__main__": print(f"{solution()} = ")
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# @Author : lightXu # @File : sobel_filter.py # @Time : 2019/7/8 0008 下午 16:26 import numpy as np from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from digital_image_processing.filters.convolve import img_convolve def sobel_filter(image): kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) kernel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) dst_x = np.abs(img_convolve(image, kernel_x)) dst_y = np.abs(img_convolve(image, kernel_y)) # modify the pix within [0, 255] dst_x = dst_x * 255 / np.max(dst_x) dst_y = dst_y * 255 / np.max(dst_y) dst_xy = np.sqrt((np.square(dst_x)) + (np.square(dst_y))) dst_xy = dst_xy * 255 / np.max(dst_xy) dst = dst_xy.astype(np.uint8) theta = np.arctan2(dst_y, dst_x) return dst, theta if __name__ == "__main__": # read original image img = imread("../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) sobel_grad, sobel_theta = sobel_filter(gray) # show result images imshow("sobel filter", sobel_grad) imshow("sobel theta", sobel_theta) waitKey(0)
# @Author : lightXu # @File : sobel_filter.py # @Time : 2019/7/8 0008 下午 16:26 import numpy as np from cv2 import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from digital_image_processing.filters.convolve import img_convolve def sobel_filter(image): kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) kernel_y = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) dst_x = np.abs(img_convolve(image, kernel_x)) dst_y = np.abs(img_convolve(image, kernel_y)) # modify the pix within [0, 255] dst_x = dst_x * 255 / np.max(dst_x) dst_y = dst_y * 255 / np.max(dst_y) dst_xy = np.sqrt((np.square(dst_x)) + (np.square(dst_y))) dst_xy = dst_xy * 255 / np.max(dst_xy) dst = dst_xy.astype(np.uint8) theta = np.arctan2(dst_y, dst_x) return dst, theta if __name__ == "__main__": # read original image img = imread("../image_data/lena.jpg") # turn image in gray scale value gray = cvtColor(img, COLOR_BGR2GRAY) sobel_grad, sobel_theta = sobel_filter(gray) # show result images imshow("sobel filter", sobel_grad) imshow("sobel theta", sobel_theta) waitKey(0)
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Ordered fractions Problem 71 https://projecteuler.net/problem=71 Consider the fraction n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that 2/5 is the fraction immediately to the left of 3/7. By listing the set of reduced proper fractions for d ≤ 1,000,000 in ascending order of size, find the numerator of the fraction immediately to the left of 3/7. """ def solution(numerator: int = 3, denominator: int = 7, limit: int = 1000000) -> int: """ Returns the closest numerator of the fraction immediately to the left of given fraction (numerator/denominator) from a list of reduced proper fractions. >>> solution() 428570 >>> solution(3, 7, 8) 2 >>> solution(6, 7, 60) 47 """ max_numerator = 0 max_denominator = 1 for current_denominator in range(1, limit + 1): current_numerator = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: max_numerator = current_numerator max_denominator = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1000000))
""" Ordered fractions Problem 71 https://projecteuler.net/problem=71 Consider the fraction n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that 2/5 is the fraction immediately to the left of 3/7. By listing the set of reduced proper fractions for d ≤ 1,000,000 in ascending order of size, find the numerator of the fraction immediately to the left of 3/7. """ def solution(numerator: int = 3, denominator: int = 7, limit: int = 1000000) -> int: """ Returns the closest numerator of the fraction immediately to the left of given fraction (numerator/denominator) from a list of reduced proper fractions. >>> solution() 428570 >>> solution(3, 7, 8) 2 >>> solution(6, 7, 60) 47 """ max_numerator = 0 max_denominator = 1 for current_denominator in range(1, limit + 1): current_numerator = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: max_numerator = current_numerator max_denominator = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=1000000))
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Binomial Heap Reference: Advanced Data Structures, Peter Brass """ class Node: """ Node in a doubly-linked binomial tree, containing: - value - size of left subtree - link to left, right and parent nodes """ def __init__(self, val): self.val = val # Number of nodes in left subtree self.left_tree_size = 0 self.left = None self.right = None self.parent = None def merge_trees(self, other): """ In-place merge of two binomial trees of equal size. Returns the root of the resulting tree """ assert self.left_tree_size == other.left_tree_size, "Unequal Sizes of Blocks" if self.val < other.val: other.left = self.right other.parent = None if self.right: self.right.parent = other self.right = other self.left_tree_size = self.left_tree_size * 2 + 1 return self else: self.left = other.right self.parent = None if other.right: other.right.parent = self other.right = self other.left_tree_size = other.left_tree_size * 2 + 1 return other class BinomialHeap: r""" Min-oriented priority queue implemented with the Binomial Heap data structure implemented with the BinomialHeap class. It supports: - Insert element in a heap with n elements: Guaranteed logn, amoratized 1 - Merge (meld) heaps of size m and n: O(logn + logm) - Delete Min: O(logn) - Peek (return min without deleting it): O(1) Example: Create a random permutation of 30 integers to be inserted and 19 of them deleted >>> import numpy as np >>> permutation = np.random.permutation(list(range(30))) Create a Heap and insert the 30 integers __init__() test >>> first_heap = BinomialHeap() 30 inserts - insert() test >>> for number in permutation: ... first_heap.insert(number) Size test >>> first_heap.size 30 Deleting - delete() test >>> [first_heap.delete_min() for _ in range(20)] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] Create a new Heap >>> second_heap = BinomialHeap() >>> vals = [17, 20, 31, 34] >>> for value in vals: ... second_heap.insert(value) The heap should have the following structure: 17 / \ # 31 / \ 20 34 / \ / \ # # # # preOrder() test >>> " ".join(str(x) for x in second_heap.pre_order()) "(17, 0) ('#', 1) (31, 1) (20, 2) ('#', 3) ('#', 3) (34, 2) ('#', 3) ('#', 3)" printing Heap - __str__() test >>> print(second_heap) 17 -# -31 --20 ---# ---# --34 ---# ---# mergeHeaps() test >>> >>> merged = second_heap.merge_heaps(first_heap) >>> merged.peek() 17 values in merged heap; (merge is inplace) >>> results = [] >>> while not first_heap.is_empty(): ... results.append(first_heap.delete_min()) >>> results [17, 20, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 31, 34] """ def __init__(self, bottom_root=None, min_node=None, heap_size=0): self.size = heap_size self.bottom_root = bottom_root self.min_node = min_node def merge_heaps(self, other): """ In-place merge of two binomial heaps. Both of them become the resulting merged heap """ # Empty heaps corner cases if other.size == 0: return None if self.size == 0: self.size = other.size self.bottom_root = other.bottom_root self.min_node = other.min_node return None # Update size self.size = self.size + other.size # Update min.node if self.min_node.val > other.min_node.val: self.min_node = other.min_node # Merge # Order roots by left_subtree_size combined_roots_list = [] i, j = self.bottom_root, other.bottom_root while i or j: if i and ((not j) or i.left_tree_size < j.left_tree_size): combined_roots_list.append((i, True)) i = i.parent else: combined_roots_list.append((j, False)) j = j.parent # Insert links between them for i in range(len(combined_roots_list) - 1): if combined_roots_list[i][1] != combined_roots_list[i + 1][1]: combined_roots_list[i][0].parent = combined_roots_list[i + 1][0] combined_roots_list[i + 1][0].left = combined_roots_list[i][0] # Consecutively merge roots with same left_tree_size i = combined_roots_list[0][0] while i.parent: if ( (i.left_tree_size == i.parent.left_tree_size) and (not i.parent.parent) ) or ( i.left_tree_size == i.parent.left_tree_size and i.left_tree_size != i.parent.parent.left_tree_size ): # Neighbouring Nodes previous_node = i.left next_node = i.parent.parent # Merging trees i = i.merge_trees(i.parent) # Updating links i.left = previous_node i.parent = next_node if previous_node: previous_node.parent = i if next_node: next_node.left = i else: i = i.parent # Updating self.bottom_root while i.left: i = i.left self.bottom_root = i # Update other other.size = self.size other.bottom_root = self.bottom_root other.min_node = self.min_node # Return the merged heap return self def insert(self, val): """ insert a value in the heap """ if self.size == 0: self.bottom_root = Node(val) self.size = 1 self.min_node = self.bottom_root else: # Create new node new_node = Node(val) # Update size self.size += 1 # update min_node if val < self.min_node.val: self.min_node = new_node # Put new_node as a bottom_root in heap self.bottom_root.left = new_node new_node.parent = self.bottom_root self.bottom_root = new_node # Consecutively merge roots with same left_tree_size while ( self.bottom_root.parent and self.bottom_root.left_tree_size == self.bottom_root.parent.left_tree_size ): # Next node next_node = self.bottom_root.parent.parent # Merge self.bottom_root = self.bottom_root.merge_trees(self.bottom_root.parent) # Update Links self.bottom_root.parent = next_node self.bottom_root.left = None if next_node: next_node.left = self.bottom_root def peek(self): """ return min element without deleting it """ return self.min_node.val def is_empty(self): return self.size == 0 def delete_min(self): """ delete min element and return it """ # assert not self.isEmpty(), "Empty Heap" # Save minimal value min_value = self.min_node.val # Last element in heap corner case if self.size == 1: # Update size self.size = 0 # Update bottom root self.bottom_root = None # Update min_node self.min_node = None return min_value # No right subtree corner case # The structure of the tree implies that this should be the bottom root # and there is at least one other root if self.min_node.right is None: # Update size self.size -= 1 # Update bottom root self.bottom_root = self.bottom_root.parent self.bottom_root.left = None # Update min_node self.min_node = self.bottom_root i = self.bottom_root.parent while i: if i.val < self.min_node.val: self.min_node = i i = i.parent return min_value # General case # Find the BinomialHeap of the right subtree of min_node bottom_of_new = self.min_node.right bottom_of_new.parent = None min_of_new = bottom_of_new size_of_new = 1 # Size, min_node and bottom_root while bottom_of_new.left: size_of_new = size_of_new * 2 + 1 bottom_of_new = bottom_of_new.left if bottom_of_new.val < min_of_new.val: min_of_new = bottom_of_new # Corner case of single root on top left path if (not self.min_node.left) and (not self.min_node.parent): self.size = size_of_new self.bottom_root = bottom_of_new self.min_node = min_of_new # print("Single root, multiple nodes case") return min_value # Remaining cases # Construct heap of right subtree new_heap = BinomialHeap( bottom_root=bottom_of_new, min_node=min_of_new, heap_size=size_of_new ) # Update size self.size = self.size - 1 - size_of_new # Neighbour nodes previous_node = self.min_node.left next_node = self.min_node.parent # Initialize new bottom_root and min_node self.min_node = previous_node or next_node self.bottom_root = next_node # Update links of previous_node and search below for new min_node and # bottom_root if previous_node: previous_node.parent = next_node # Update bottom_root and search for min_node below self.bottom_root = previous_node self.min_node = previous_node while self.bottom_root.left: self.bottom_root = self.bottom_root.left if self.bottom_root.val < self.min_node.val: self.min_node = self.bottom_root if next_node: next_node.left = previous_node # Search for new min_node above min_node i = next_node while i: if i.val < self.min_node.val: self.min_node = i i = i.parent # Merge heaps self.merge_heaps(new_heap) return min_value def pre_order(self): """ Returns the Pre-order representation of the heap including values of nodes plus their level distance from the root; Empty nodes appear as # """ # Find top root top_root = self.bottom_root while top_root.parent: top_root = top_root.parent # preorder heap_pre_order = [] self.__traversal(top_root, heap_pre_order) return heap_pre_order def __traversal(self, curr_node, preorder, level=0): """ Pre-order traversal of nodes """ if curr_node: preorder.append((curr_node.val, level)) self.__traversal(curr_node.left, preorder, level + 1) self.__traversal(curr_node.right, preorder, level + 1) else: preorder.append(("#", level)) def __str__(self): """ Overwriting str for a pre-order print of nodes in heap; Performance is poor, so use only for small examples """ if self.is_empty(): return "" preorder_heap = self.pre_order() return "\n".join(("-" * level + str(value)) for value, level in preorder_heap) # Unit Tests if __name__ == "__main__": import doctest doctest.testmod()
""" Binomial Heap Reference: Advanced Data Structures, Peter Brass """ class Node: """ Node in a doubly-linked binomial tree, containing: - value - size of left subtree - link to left, right and parent nodes """ def __init__(self, val): self.val = val # Number of nodes in left subtree self.left_tree_size = 0 self.left = None self.right = None self.parent = None def merge_trees(self, other): """ In-place merge of two binomial trees of equal size. Returns the root of the resulting tree """ assert self.left_tree_size == other.left_tree_size, "Unequal Sizes of Blocks" if self.val < other.val: other.left = self.right other.parent = None if self.right: self.right.parent = other self.right = other self.left_tree_size = self.left_tree_size * 2 + 1 return self else: self.left = other.right self.parent = None if other.right: other.right.parent = self other.right = self other.left_tree_size = other.left_tree_size * 2 + 1 return other class BinomialHeap: r""" Min-oriented priority queue implemented with the Binomial Heap data structure implemented with the BinomialHeap class. It supports: - Insert element in a heap with n elements: Guaranteed logn, amoratized 1 - Merge (meld) heaps of size m and n: O(logn + logm) - Delete Min: O(logn) - Peek (return min without deleting it): O(1) Example: Create a random permutation of 30 integers to be inserted and 19 of them deleted >>> import numpy as np >>> permutation = np.random.permutation(list(range(30))) Create a Heap and insert the 30 integers __init__() test >>> first_heap = BinomialHeap() 30 inserts - insert() test >>> for number in permutation: ... first_heap.insert(number) Size test >>> first_heap.size 30 Deleting - delete() test >>> [first_heap.delete_min() for _ in range(20)] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] Create a new Heap >>> second_heap = BinomialHeap() >>> vals = [17, 20, 31, 34] >>> for value in vals: ... second_heap.insert(value) The heap should have the following structure: 17 / \ # 31 / \ 20 34 / \ / \ # # # # preOrder() test >>> " ".join(str(x) for x in second_heap.pre_order()) "(17, 0) ('#', 1) (31, 1) (20, 2) ('#', 3) ('#', 3) (34, 2) ('#', 3) ('#', 3)" printing Heap - __str__() test >>> print(second_heap) 17 -# -31 --20 ---# ---# --34 ---# ---# mergeHeaps() test >>> >>> merged = second_heap.merge_heaps(first_heap) >>> merged.peek() 17 values in merged heap; (merge is inplace) >>> results = [] >>> while not first_heap.is_empty(): ... results.append(first_heap.delete_min()) >>> results [17, 20, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 31, 34] """ def __init__(self, bottom_root=None, min_node=None, heap_size=0): self.size = heap_size self.bottom_root = bottom_root self.min_node = min_node def merge_heaps(self, other): """ In-place merge of two binomial heaps. Both of them become the resulting merged heap """ # Empty heaps corner cases if other.size == 0: return None if self.size == 0: self.size = other.size self.bottom_root = other.bottom_root self.min_node = other.min_node return None # Update size self.size = self.size + other.size # Update min.node if self.min_node.val > other.min_node.val: self.min_node = other.min_node # Merge # Order roots by left_subtree_size combined_roots_list = [] i, j = self.bottom_root, other.bottom_root while i or j: if i and ((not j) or i.left_tree_size < j.left_tree_size): combined_roots_list.append((i, True)) i = i.parent else: combined_roots_list.append((j, False)) j = j.parent # Insert links between them for i in range(len(combined_roots_list) - 1): if combined_roots_list[i][1] != combined_roots_list[i + 1][1]: combined_roots_list[i][0].parent = combined_roots_list[i + 1][0] combined_roots_list[i + 1][0].left = combined_roots_list[i][0] # Consecutively merge roots with same left_tree_size i = combined_roots_list[0][0] while i.parent: if ( (i.left_tree_size == i.parent.left_tree_size) and (not i.parent.parent) ) or ( i.left_tree_size == i.parent.left_tree_size and i.left_tree_size != i.parent.parent.left_tree_size ): # Neighbouring Nodes previous_node = i.left next_node = i.parent.parent # Merging trees i = i.merge_trees(i.parent) # Updating links i.left = previous_node i.parent = next_node if previous_node: previous_node.parent = i if next_node: next_node.left = i else: i = i.parent # Updating self.bottom_root while i.left: i = i.left self.bottom_root = i # Update other other.size = self.size other.bottom_root = self.bottom_root other.min_node = self.min_node # Return the merged heap return self def insert(self, val): """ insert a value in the heap """ if self.size == 0: self.bottom_root = Node(val) self.size = 1 self.min_node = self.bottom_root else: # Create new node new_node = Node(val) # Update size self.size += 1 # update min_node if val < self.min_node.val: self.min_node = new_node # Put new_node as a bottom_root in heap self.bottom_root.left = new_node new_node.parent = self.bottom_root self.bottom_root = new_node # Consecutively merge roots with same left_tree_size while ( self.bottom_root.parent and self.bottom_root.left_tree_size == self.bottom_root.parent.left_tree_size ): # Next node next_node = self.bottom_root.parent.parent # Merge self.bottom_root = self.bottom_root.merge_trees(self.bottom_root.parent) # Update Links self.bottom_root.parent = next_node self.bottom_root.left = None if next_node: next_node.left = self.bottom_root def peek(self): """ return min element without deleting it """ return self.min_node.val def is_empty(self): return self.size == 0 def delete_min(self): """ delete min element and return it """ # assert not self.isEmpty(), "Empty Heap" # Save minimal value min_value = self.min_node.val # Last element in heap corner case if self.size == 1: # Update size self.size = 0 # Update bottom root self.bottom_root = None # Update min_node self.min_node = None return min_value # No right subtree corner case # The structure of the tree implies that this should be the bottom root # and there is at least one other root if self.min_node.right is None: # Update size self.size -= 1 # Update bottom root self.bottom_root = self.bottom_root.parent self.bottom_root.left = None # Update min_node self.min_node = self.bottom_root i = self.bottom_root.parent while i: if i.val < self.min_node.val: self.min_node = i i = i.parent return min_value # General case # Find the BinomialHeap of the right subtree of min_node bottom_of_new = self.min_node.right bottom_of_new.parent = None min_of_new = bottom_of_new size_of_new = 1 # Size, min_node and bottom_root while bottom_of_new.left: size_of_new = size_of_new * 2 + 1 bottom_of_new = bottom_of_new.left if bottom_of_new.val < min_of_new.val: min_of_new = bottom_of_new # Corner case of single root on top left path if (not self.min_node.left) and (not self.min_node.parent): self.size = size_of_new self.bottom_root = bottom_of_new self.min_node = min_of_new # print("Single root, multiple nodes case") return min_value # Remaining cases # Construct heap of right subtree new_heap = BinomialHeap( bottom_root=bottom_of_new, min_node=min_of_new, heap_size=size_of_new ) # Update size self.size = self.size - 1 - size_of_new # Neighbour nodes previous_node = self.min_node.left next_node = self.min_node.parent # Initialize new bottom_root and min_node self.min_node = previous_node or next_node self.bottom_root = next_node # Update links of previous_node and search below for new min_node and # bottom_root if previous_node: previous_node.parent = next_node # Update bottom_root and search for min_node below self.bottom_root = previous_node self.min_node = previous_node while self.bottom_root.left: self.bottom_root = self.bottom_root.left if self.bottom_root.val < self.min_node.val: self.min_node = self.bottom_root if next_node: next_node.left = previous_node # Search for new min_node above min_node i = next_node while i: if i.val < self.min_node.val: self.min_node = i i = i.parent # Merge heaps self.merge_heaps(new_heap) return min_value def pre_order(self): """ Returns the Pre-order representation of the heap including values of nodes plus their level distance from the root; Empty nodes appear as # """ # Find top root top_root = self.bottom_root while top_root.parent: top_root = top_root.parent # preorder heap_pre_order = [] self.__traversal(top_root, heap_pre_order) return heap_pre_order def __traversal(self, curr_node, preorder, level=0): """ Pre-order traversal of nodes """ if curr_node: preorder.append((curr_node.val, level)) self.__traversal(curr_node.left, preorder, level + 1) self.__traversal(curr_node.right, preorder, level + 1) else: preorder.append(("#", level)) def __str__(self): """ Overwriting str for a pre-order print of nodes in heap; Performance is poor, so use only for small examples """ if self.is_empty(): return "" preorder_heap = self.pre_order() return "\n".join(("-" * level + str(value)) for value, level in preorder_heap) # Unit Tests if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Permuted multiples Problem 52 It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. """ def solution(): """Returns the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. >>> solution() 142857 """ i = 1 while True: if ( sorted(str(i)) == sorted(str(2 * i)) == sorted(str(3 * i)) == sorted(str(4 * i)) == sorted(str(5 * i)) == sorted(str(6 * i)) ): return i i += 1 if __name__ == "__main__": print(solution())
""" Permuted multiples Problem 52 It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. """ def solution(): """Returns the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. >>> solution() 142857 """ i = 1 while True: if ( sorted(str(i)) == sorted(str(2 * i)) == sorted(str(3 * i)) == sorted(str(4 * i)) == sorted(str(5 * i)) == sorted(str(6 * i)) ): return i i += 1 if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" A NOR Gate is a logic gate in boolean algebra which results to false(0) if any of the input is 1, and True(1) if both the inputs are 0. Following is the truth table of a NOR Gate: | Input 1 | Input 2 | Output | | 0 | 0 | 1 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 0 | Following is the code implementation of the NOR Gate """ def nor_gate(input_1: int, input_2: int) -> int: """ >>> nor_gate(0, 0) 1 >>> nor_gate(0, 1) 0 >>> nor_gate(1, 0) 0 >>> nor_gate(1, 1) 0 >>> nor_gate(0.0, 0.0) 1 >>> nor_gate(0, -7) 0 """ return int(input_1 == input_2 == 0) def main() -> None: print("Truth Table of NOR Gate:") print("| Input 1 | Input 2 | Output |") print(f"| 0 | 0 | {nor_gate(0, 0)} |") print(f"| 0 | 1 | {nor_gate(0, 1)} |") print(f"| 1 | 0 | {nor_gate(1, 0)} |") print(f"| 1 | 1 | {nor_gate(1, 1)} |") if __name__ == "__main__": import doctest doctest.testmod() main() """Code provided by Akshaj Vishwanathan""" """Reference: https://www.geeksforgeeks.org/logic-gates-in-python/"""
""" A NOR Gate is a logic gate in boolean algebra which results to false(0) if any of the input is 1, and True(1) if both the inputs are 0. Following is the truth table of a NOR Gate: | Input 1 | Input 2 | Output | | 0 | 0 | 1 | | 0 | 1 | 0 | | 1 | 0 | 0 | | 1 | 1 | 0 | Following is the code implementation of the NOR Gate """ def nor_gate(input_1: int, input_2: int) -> int: """ >>> nor_gate(0, 0) 1 >>> nor_gate(0, 1) 0 >>> nor_gate(1, 0) 0 >>> nor_gate(1, 1) 0 >>> nor_gate(0.0, 0.0) 1 >>> nor_gate(0, -7) 0 """ return int(input_1 == input_2 == 0) def main() -> None: print("Truth Table of NOR Gate:") print("| Input 1 | Input 2 | Output |") print(f"| 0 | 0 | {nor_gate(0, 0)} |") print(f"| 0 | 1 | {nor_gate(0, 1)} |") print(f"| 1 | 0 | {nor_gate(1, 0)} |") print(f"| 1 | 1 | {nor_gate(1, 1)} |") if __name__ == "__main__": import doctest doctest.testmod() main() """Code provided by Akshaj Vishwanathan""" """Reference: https://www.geeksforgeeks.org/logic-gates-in-python/"""
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Heap's algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implementation of the Heap's algorithm (recursive version), returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(k: int, arr: list): if k == 1: res.append(tuple(arr[:])) return generate(k - 1, arr) for i in range(k - 1): if k % 2 == 0: # k is even arr[i], arr[k - 1] = arr[k - 1], arr[i] else: # k is odd arr[0], arr[k - 1] = arr[k - 1], arr[0] generate(k - 1, arr) generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
""" Heap's algorithm returns the list of all permutations possible from a list. It minimizes movement by generating each permutation from the previous one by swapping only two elements. More information: https://en.wikipedia.org/wiki/Heap%27s_algorithm. """ def heaps(arr: list) -> list: """ Pure python implementation of the Heap's algorithm (recursive version), returning all permutations of a list. >>> heaps([]) [()] >>> heaps([0]) [(0,)] >>> heaps([-1, 1]) [(-1, 1), (1, -1)] >>> heaps([1, 2, 3]) [(1, 2, 3), (2, 1, 3), (3, 1, 2), (1, 3, 2), (2, 3, 1), (3, 2, 1)] >>> from itertools import permutations >>> sorted(heaps([1,2,3])) == sorted(permutations([1,2,3])) True >>> all(sorted(heaps(x)) == sorted(permutations(x)) ... for x in ([], [0], [-1, 1], [1, 2, 3])) True """ if len(arr) <= 1: return [tuple(arr)] res = [] def generate(k: int, arr: list): if k == 1: res.append(tuple(arr[:])) return generate(k - 1, arr) for i in range(k - 1): if k % 2 == 0: # k is even arr[i], arr[k - 1] = arr[k - 1], arr[i] else: # k is odd arr[0], arr[k - 1] = arr[k - 1], arr[0] generate(k - 1, arr) generate(len(arr), arr) return res if __name__ == "__main__": user_input = input("Enter numbers separated by a comma:\n").strip() arr = [int(item) for item in user_input.split(",")] print(heaps(arr))
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from typing import Any def viterbi( observations_space: list, states_space: list, initial_probabilities: dict, transition_probabilities: dict, emission_probabilities: dict, ) -> list: """ Viterbi Algorithm, to find the most likely path of states from the start and the expected output. https://en.wikipedia.org/wiki/Viterbi_algorithm sdafads Wikipedia example >>> observations = ["normal", "cold", "dizzy"] >>> states = ["Healthy", "Fever"] >>> start_p = {"Healthy": 0.6, "Fever": 0.4} >>> trans_p = { ... "Healthy": {"Healthy": 0.7, "Fever": 0.3}, ... "Fever": {"Healthy": 0.4, "Fever": 0.6}, ... } >>> emit_p = { ... "Healthy": {"normal": 0.5, "cold": 0.4, "dizzy": 0.1}, ... "Fever": {"normal": 0.1, "cold": 0.3, "dizzy": 0.6}, ... } >>> viterbi(observations, states, start_p, trans_p, emit_p) ['Healthy', 'Healthy', 'Fever'] >>> viterbi((), states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, (), start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, states, {}, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, states, start_p, {}, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, states, start_p, trans_p, {}) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi("invalid", states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: observations_space must be a list >>> viterbi(["valid", 123], states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: observations_space must be a list of strings >>> viterbi(observations, "invalid", start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: states_space must be a list >>> viterbi(observations, ["valid", 123], start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: states_space must be a list of strings >>> viterbi(observations, states, "invalid", trans_p, emit_p) Traceback (most recent call last): ... ValueError: initial_probabilities must be a dict >>> viterbi(observations, states, {2:2}, trans_p, emit_p) Traceback (most recent call last): ... ValueError: initial_probabilities all keys must be strings >>> viterbi(observations, states, {"a":2}, trans_p, emit_p) Traceback (most recent call last): ... ValueError: initial_probabilities all values must be float >>> viterbi(observations, states, start_p, "invalid", emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities must be a dict >>> viterbi(observations, states, start_p, {"a":2}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities all values must be dict >>> viterbi(observations, states, start_p, {2:{2:2}}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities all keys must be strings >>> viterbi(observations, states, start_p, {"a":{2:2}}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities all keys must be strings >>> viterbi(observations, states, start_p, {"a":{"b":2}}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities nested dictionary all values must be float >>> viterbi(observations, states, start_p, trans_p, "invalid") Traceback (most recent call last): ... ValueError: emission_probabilities must be a dict >>> viterbi(observations, states, start_p, trans_p, None) Traceback (most recent call last): ... ValueError: There's an empty parameter """ _validation( observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ) # Creates data structures and fill initial step probabilities: dict = {} pointers: dict = {} for state in states_space: observation = observations_space[0] probabilities[(state, observation)] = ( initial_probabilities[state] * emission_probabilities[state][observation] ) pointers[(state, observation)] = None # Fills the data structure with the probabilities of # different transitions and pointers to previous states for o in range(1, len(observations_space)): observation = observations_space[o] prior_observation = observations_space[o - 1] for state in states_space: # Calculates the argmax for probability function arg_max = "" max_probability = -1 for k_state in states_space: probability = ( probabilities[(k_state, prior_observation)] * transition_probabilities[k_state][state] * emission_probabilities[state][observation] ) if probability > max_probability: max_probability = probability arg_max = k_state # Update probabilities and pointers dicts probabilities[(state, observation)] = ( probabilities[(arg_max, prior_observation)] * transition_probabilities[arg_max][state] * emission_probabilities[state][observation] ) pointers[(state, observation)] = arg_max # The final observation final_observation = observations_space[len(observations_space) - 1] # argmax for given final observation arg_max = "" max_probability = -1 for k_state in states_space: probability = probabilities[(k_state, final_observation)] if probability > max_probability: max_probability = probability arg_max = k_state last_state = arg_max # Process pointers backwards previous = last_state result = [] for o in range(len(observations_space) - 1, -1, -1): result.append(previous) previous = pointers[previous, observations_space[o]] result.reverse() return result def _validation( observations_space: Any, states_space: Any, initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: """ >>> observations = ["normal", "cold", "dizzy"] >>> states = ["Healthy", "Fever"] >>> start_p = {"Healthy": 0.6, "Fever": 0.4} >>> trans_p = { ... "Healthy": {"Healthy": 0.7, "Fever": 0.3}, ... "Fever": {"Healthy": 0.4, "Fever": 0.6}, ... } >>> emit_p = { ... "Healthy": {"normal": 0.5, "cold": 0.4, "dizzy": 0.1}, ... "Fever": {"normal": 0.1, "cold": 0.3, "dizzy": 0.6}, ... } >>> _validation(observations, states, start_p, trans_p, emit_p) >>> _validation([], states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter """ _validate_not_empty( observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ) _validate_lists(observations_space, states_space) _validate_dicts( initial_probabilities, transition_probabilities, emission_probabilities ) def _validate_not_empty( observations_space: Any, states_space: Any, initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: """ >>> _validate_not_empty(["a"], ["b"], {"c":0.5}, ... {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) >>> _validate_not_empty(["a"], ["b"], {"c":0.5}, {}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> _validate_not_empty(["a"], ["b"], None, {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: There's an empty parameter """ if not all( [ observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ] ): raise ValueError("There's an empty parameter") def _validate_lists(observations_space: Any, states_space: Any) -> None: """ >>> _validate_lists(["a"], ["b"]) >>> _validate_lists(1234, ["b"]) Traceback (most recent call last): ... ValueError: observations_space must be a list >>> _validate_lists(["a"], [3]) Traceback (most recent call last): ... ValueError: states_space must be a list of strings """ _validate_list(observations_space, "observations_space") _validate_list(states_space, "states_space") def _validate_list(_object: Any, var_name: str) -> None: """ >>> _validate_list(["a"], "mock_name") >>> _validate_list("a", "mock_name") Traceback (most recent call last): ... ValueError: mock_name must be a list >>> _validate_list([0.5], "mock_name") Traceback (most recent call last): ... ValueError: mock_name must be a list of strings """ if not isinstance(_object, list): msg = f"{var_name} must be a list" raise ValueError(msg) else: for x in _object: if not isinstance(x, str): msg = f"{var_name} must be a list of strings" raise ValueError(msg) def _validate_dicts( initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: """ >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) >>> _validate_dicts("invalid", {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: initial_probabilities must be a dict >>> _validate_dicts({"c":0.5}, {2: {"e": 0.6}}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: transition_probabilities all keys must be strings >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {2: 0.7}}) Traceback (most recent call last): ... ValueError: emission_probabilities all keys must be strings >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {"g": "h"}}) Traceback (most recent call last): ... ValueError: emission_probabilities nested dictionary all values must be float """ _validate_dict(initial_probabilities, "initial_probabilities", float) _validate_nested_dict(transition_probabilities, "transition_probabilities") _validate_nested_dict(emission_probabilities, "emission_probabilities") def _validate_nested_dict(_object: Any, var_name: str) -> None: """ >>> _validate_nested_dict({"a":{"b": 0.5}}, "mock_name") >>> _validate_nested_dict("invalid", "mock_name") Traceback (most recent call last): ... ValueError: mock_name must be a dict >>> _validate_nested_dict({"a": 8}, "mock_name") Traceback (most recent call last): ... ValueError: mock_name all values must be dict >>> _validate_nested_dict({"a":{2: 0.5}}, "mock_name") Traceback (most recent call last): ... ValueError: mock_name all keys must be strings >>> _validate_nested_dict({"a":{"b": 4}}, "mock_name") Traceback (most recent call last): ... ValueError: mock_name nested dictionary all values must be float """ _validate_dict(_object, var_name, dict) for x in _object.values(): _validate_dict(x, var_name, float, True) def _validate_dict( _object: Any, var_name: str, value_type: type, nested: bool = False ) -> None: """ >>> _validate_dict({"b": 0.5}, "mock_name", float) >>> _validate_dict("invalid", "mock_name", float) Traceback (most recent call last): ... ValueError: mock_name must be a dict >>> _validate_dict({"a": 8}, "mock_name", dict) Traceback (most recent call last): ... ValueError: mock_name all values must be dict >>> _validate_dict({2: 0.5}, "mock_name",float, True) Traceback (most recent call last): ... ValueError: mock_name all keys must be strings >>> _validate_dict({"b": 4}, "mock_name", float,True) Traceback (most recent call last): ... ValueError: mock_name nested dictionary all values must be float """ if not isinstance(_object, dict): msg = f"{var_name} must be a dict" raise ValueError(msg) if not all(isinstance(x, str) for x in _object): msg = f"{var_name} all keys must be strings" raise ValueError(msg) if not all(isinstance(x, value_type) for x in _object.values()): nested_text = "nested dictionary " if nested else "" msg = f"{var_name} {nested_text}all values must be {value_type.__name__}" raise ValueError(msg) if __name__ == "__main__": from doctest import testmod testmod()
from typing import Any def viterbi( observations_space: list, states_space: list, initial_probabilities: dict, transition_probabilities: dict, emission_probabilities: dict, ) -> list: """ Viterbi Algorithm, to find the most likely path of states from the start and the expected output. https://en.wikipedia.org/wiki/Viterbi_algorithm sdafads Wikipedia example >>> observations = ["normal", "cold", "dizzy"] >>> states = ["Healthy", "Fever"] >>> start_p = {"Healthy": 0.6, "Fever": 0.4} >>> trans_p = { ... "Healthy": {"Healthy": 0.7, "Fever": 0.3}, ... "Fever": {"Healthy": 0.4, "Fever": 0.6}, ... } >>> emit_p = { ... "Healthy": {"normal": 0.5, "cold": 0.4, "dizzy": 0.1}, ... "Fever": {"normal": 0.1, "cold": 0.3, "dizzy": 0.6}, ... } >>> viterbi(observations, states, start_p, trans_p, emit_p) ['Healthy', 'Healthy', 'Fever'] >>> viterbi((), states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, (), start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, states, {}, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, states, start_p, {}, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi(observations, states, start_p, trans_p, {}) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> viterbi("invalid", states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: observations_space must be a list >>> viterbi(["valid", 123], states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: observations_space must be a list of strings >>> viterbi(observations, "invalid", start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: states_space must be a list >>> viterbi(observations, ["valid", 123], start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: states_space must be a list of strings >>> viterbi(observations, states, "invalid", trans_p, emit_p) Traceback (most recent call last): ... ValueError: initial_probabilities must be a dict >>> viterbi(observations, states, {2:2}, trans_p, emit_p) Traceback (most recent call last): ... ValueError: initial_probabilities all keys must be strings >>> viterbi(observations, states, {"a":2}, trans_p, emit_p) Traceback (most recent call last): ... ValueError: initial_probabilities all values must be float >>> viterbi(observations, states, start_p, "invalid", emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities must be a dict >>> viterbi(observations, states, start_p, {"a":2}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities all values must be dict >>> viterbi(observations, states, start_p, {2:{2:2}}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities all keys must be strings >>> viterbi(observations, states, start_p, {"a":{2:2}}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities all keys must be strings >>> viterbi(observations, states, start_p, {"a":{"b":2}}, emit_p) Traceback (most recent call last): ... ValueError: transition_probabilities nested dictionary all values must be float >>> viterbi(observations, states, start_p, trans_p, "invalid") Traceback (most recent call last): ... ValueError: emission_probabilities must be a dict >>> viterbi(observations, states, start_p, trans_p, None) Traceback (most recent call last): ... ValueError: There's an empty parameter """ _validation( observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ) # Creates data structures and fill initial step probabilities: dict = {} pointers: dict = {} for state in states_space: observation = observations_space[0] probabilities[(state, observation)] = ( initial_probabilities[state] * emission_probabilities[state][observation] ) pointers[(state, observation)] = None # Fills the data structure with the probabilities of # different transitions and pointers to previous states for o in range(1, len(observations_space)): observation = observations_space[o] prior_observation = observations_space[o - 1] for state in states_space: # Calculates the argmax for probability function arg_max = "" max_probability = -1 for k_state in states_space: probability = ( probabilities[(k_state, prior_observation)] * transition_probabilities[k_state][state] * emission_probabilities[state][observation] ) if probability > max_probability: max_probability = probability arg_max = k_state # Update probabilities and pointers dicts probabilities[(state, observation)] = ( probabilities[(arg_max, prior_observation)] * transition_probabilities[arg_max][state] * emission_probabilities[state][observation] ) pointers[(state, observation)] = arg_max # The final observation final_observation = observations_space[len(observations_space) - 1] # argmax for given final observation arg_max = "" max_probability = -1 for k_state in states_space: probability = probabilities[(k_state, final_observation)] if probability > max_probability: max_probability = probability arg_max = k_state last_state = arg_max # Process pointers backwards previous = last_state result = [] for o in range(len(observations_space) - 1, -1, -1): result.append(previous) previous = pointers[previous, observations_space[o]] result.reverse() return result def _validation( observations_space: Any, states_space: Any, initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: """ >>> observations = ["normal", "cold", "dizzy"] >>> states = ["Healthy", "Fever"] >>> start_p = {"Healthy": 0.6, "Fever": 0.4} >>> trans_p = { ... "Healthy": {"Healthy": 0.7, "Fever": 0.3}, ... "Fever": {"Healthy": 0.4, "Fever": 0.6}, ... } >>> emit_p = { ... "Healthy": {"normal": 0.5, "cold": 0.4, "dizzy": 0.1}, ... "Fever": {"normal": 0.1, "cold": 0.3, "dizzy": 0.6}, ... } >>> _validation(observations, states, start_p, trans_p, emit_p) >>> _validation([], states, start_p, trans_p, emit_p) Traceback (most recent call last): ... ValueError: There's an empty parameter """ _validate_not_empty( observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ) _validate_lists(observations_space, states_space) _validate_dicts( initial_probabilities, transition_probabilities, emission_probabilities ) def _validate_not_empty( observations_space: Any, states_space: Any, initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: """ >>> _validate_not_empty(["a"], ["b"], {"c":0.5}, ... {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) >>> _validate_not_empty(["a"], ["b"], {"c":0.5}, {}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: There's an empty parameter >>> _validate_not_empty(["a"], ["b"], None, {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: There's an empty parameter """ if not all( [ observations_space, states_space, initial_probabilities, transition_probabilities, emission_probabilities, ] ): raise ValueError("There's an empty parameter") def _validate_lists(observations_space: Any, states_space: Any) -> None: """ >>> _validate_lists(["a"], ["b"]) >>> _validate_lists(1234, ["b"]) Traceback (most recent call last): ... ValueError: observations_space must be a list >>> _validate_lists(["a"], [3]) Traceback (most recent call last): ... ValueError: states_space must be a list of strings """ _validate_list(observations_space, "observations_space") _validate_list(states_space, "states_space") def _validate_list(_object: Any, var_name: str) -> None: """ >>> _validate_list(["a"], "mock_name") >>> _validate_list("a", "mock_name") Traceback (most recent call last): ... ValueError: mock_name must be a list >>> _validate_list([0.5], "mock_name") Traceback (most recent call last): ... ValueError: mock_name must be a list of strings """ if not isinstance(_object, list): msg = f"{var_name} must be a list" raise ValueError(msg) else: for x in _object: if not isinstance(x, str): msg = f"{var_name} must be a list of strings" raise ValueError(msg) def _validate_dicts( initial_probabilities: Any, transition_probabilities: Any, emission_probabilities: Any, ) -> None: """ >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) >>> _validate_dicts("invalid", {"d": {"e": 0.6}}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: initial_probabilities must be a dict >>> _validate_dicts({"c":0.5}, {2: {"e": 0.6}}, {"f": {"g": 0.7}}) Traceback (most recent call last): ... ValueError: transition_probabilities all keys must be strings >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {2: 0.7}}) Traceback (most recent call last): ... ValueError: emission_probabilities all keys must be strings >>> _validate_dicts({"c":0.5}, {"d": {"e": 0.6}}, {"f": {"g": "h"}}) Traceback (most recent call last): ... ValueError: emission_probabilities nested dictionary all values must be float """ _validate_dict(initial_probabilities, "initial_probabilities", float) _validate_nested_dict(transition_probabilities, "transition_probabilities") _validate_nested_dict(emission_probabilities, "emission_probabilities") def _validate_nested_dict(_object: Any, var_name: str) -> None: """ >>> _validate_nested_dict({"a":{"b": 0.5}}, "mock_name") >>> _validate_nested_dict("invalid", "mock_name") Traceback (most recent call last): ... ValueError: mock_name must be a dict >>> _validate_nested_dict({"a": 8}, "mock_name") Traceback (most recent call last): ... ValueError: mock_name all values must be dict >>> _validate_nested_dict({"a":{2: 0.5}}, "mock_name") Traceback (most recent call last): ... ValueError: mock_name all keys must be strings >>> _validate_nested_dict({"a":{"b": 4}}, "mock_name") Traceback (most recent call last): ... ValueError: mock_name nested dictionary all values must be float """ _validate_dict(_object, var_name, dict) for x in _object.values(): _validate_dict(x, var_name, float, True) def _validate_dict( _object: Any, var_name: str, value_type: type, nested: bool = False ) -> None: """ >>> _validate_dict({"b": 0.5}, "mock_name", float) >>> _validate_dict("invalid", "mock_name", float) Traceback (most recent call last): ... ValueError: mock_name must be a dict >>> _validate_dict({"a": 8}, "mock_name", dict) Traceback (most recent call last): ... ValueError: mock_name all values must be dict >>> _validate_dict({2: 0.5}, "mock_name",float, True) Traceback (most recent call last): ... ValueError: mock_name all keys must be strings >>> _validate_dict({"b": 4}, "mock_name", float,True) Traceback (most recent call last): ... ValueError: mock_name nested dictionary all values must be float """ if not isinstance(_object, dict): msg = f"{var_name} must be a dict" raise ValueError(msg) if not all(isinstance(x, str) for x in _object): msg = f"{var_name} all keys must be strings" raise ValueError(msg) if not all(isinstance(x, value_type) for x in _object.values()): nested_text = "nested dictionary " if nested else "" msg = f"{var_name} {nested_text}all values must be {value_type.__name__}" raise ValueError(msg) if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Task: Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return compute the researcher's h-index. According to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n - h papers have no more than h citations each. If there are several possible values for h, the maximum one is taken as the h-index. H-Index link: https://en.wikipedia.org/wiki/H-index Implementation notes: Use sorting of array Leetcode link: https://leetcode.com/problems/h-index/description/ n = len(citations) Runtime Complexity: O(n * log(n)) Space Complexity: O(1) """ def h_index(citations: list[int]) -> int: """ Return H-index of citations >>> h_index([3, 0, 6, 1, 5]) 3 >>> h_index([1, 3, 1]) 1 >>> h_index([1, 2, 3]) 2 >>> h_index('test') Traceback (most recent call last): ... ValueError: The citations should be a list of non negative integers. >>> h_index([1,2,'3']) Traceback (most recent call last): ... ValueError: The citations should be a list of non negative integers. >>> h_index([1,2,-3]) Traceback (most recent call last): ... ValueError: The citations should be a list of non negative integers. """ # validate: if not isinstance(citations, list) or not all( isinstance(item, int) and item >= 0 for item in citations ): raise ValueError("The citations should be a list of non negative integers.") citations.sort() len_citations = len(citations) for i in range(len_citations): if citations[len_citations - 1 - i] <= i: return i return len_citations if __name__ == "__main__": import doctest doctest.testmod()
""" Task: Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, return compute the researcher's h-index. According to the definition of h-index on Wikipedia: A scientist has an index h if h of their n papers have at least h citations each, and the other n - h papers have no more than h citations each. If there are several possible values for h, the maximum one is taken as the h-index. H-Index link: https://en.wikipedia.org/wiki/H-index Implementation notes: Use sorting of array Leetcode link: https://leetcode.com/problems/h-index/description/ n = len(citations) Runtime Complexity: O(n * log(n)) Space Complexity: O(1) """ def h_index(citations: list[int]) -> int: """ Return H-index of citations >>> h_index([3, 0, 6, 1, 5]) 3 >>> h_index([1, 3, 1]) 1 >>> h_index([1, 2, 3]) 2 >>> h_index('test') Traceback (most recent call last): ... ValueError: The citations should be a list of non negative integers. >>> h_index([1,2,'3']) Traceback (most recent call last): ... ValueError: The citations should be a list of non negative integers. >>> h_index([1,2,-3]) Traceback (most recent call last): ... ValueError: The citations should be a list of non negative integers. """ # validate: if not isinstance(citations, list) or not all( isinstance(item, int) and item >= 0 for item in citations ): raise ValueError("The citations should be a list of non negative integers.") citations.sort() len_citations = len(citations) for i in range(len_citations): if citations[len_citations - 1 - i] <= i: return i return len_citations if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from collections import deque def tarjan(g): """ Tarjan's algo for finding strongly connected components in a directed graph Uses two main attributes of each node to track reachability, the index of that node within a component(index), and the lowest index reachable from that node(lowlink). We then perform a dfs of the each component making sure to update these parameters for each node and saving the nodes we visit on the way. If ever we find that the lowest reachable node from a current node is equal to the index of the current node then it must be the root of a strongly connected component and so we save it and it's equireachable vertices as a strongly connected component. Complexity: strong_connect() is called at most once for each node and has a complexity of O(|E|) as it is DFS. Therefore this has complexity O(|V| + |E|) for a graph G = (V, E) """ n = len(g) stack = deque() on_stack = [False for _ in range(n)] index_of = [-1 for _ in range(n)] lowlink_of = index_of[:] def strong_connect(v, index, components): index_of[v] = index # the number when this node is seen lowlink_of[v] = index # lowest rank node reachable from here index += 1 stack.append(v) on_stack[v] = True for w in g[v]: if index_of[w] == -1: index = strong_connect(w, index, components) lowlink_of[v] = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) elif on_stack[w]: lowlink_of[v] = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) if lowlink_of[v] == index_of[v]: component = [] w = stack.pop() on_stack[w] = False component.append(w) while w != v: w = stack.pop() on_stack[w] = False component.append(w) components.append(component) return index components = [] for v in range(n): if index_of[v] == -1: strong_connect(v, 0, components) return components def create_graph(n, edges): g = [[] for _ in range(n)] for u, v in edges: g[u].append(v) return g if __name__ == "__main__": # Test n_vertices = 7 source = [0, 0, 1, 2, 3, 3, 4, 4, 6] target = [1, 3, 2, 0, 1, 4, 5, 6, 5] edges = [(u, v) for u, v in zip(source, target)] g = create_graph(n_vertices, edges) assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
from collections import deque def tarjan(g): """ Tarjan's algo for finding strongly connected components in a directed graph Uses two main attributes of each node to track reachability, the index of that node within a component(index), and the lowest index reachable from that node(lowlink). We then perform a dfs of the each component making sure to update these parameters for each node and saving the nodes we visit on the way. If ever we find that the lowest reachable node from a current node is equal to the index of the current node then it must be the root of a strongly connected component and so we save it and it's equireachable vertices as a strongly connected component. Complexity: strong_connect() is called at most once for each node and has a complexity of O(|E|) as it is DFS. Therefore this has complexity O(|V| + |E|) for a graph G = (V, E) """ n = len(g) stack = deque() on_stack = [False for _ in range(n)] index_of = [-1 for _ in range(n)] lowlink_of = index_of[:] def strong_connect(v, index, components): index_of[v] = index # the number when this node is seen lowlink_of[v] = index # lowest rank node reachable from here index += 1 stack.append(v) on_stack[v] = True for w in g[v]: if index_of[w] == -1: index = strong_connect(w, index, components) lowlink_of[v] = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) elif on_stack[w]: lowlink_of[v] = ( lowlink_of[w] if lowlink_of[w] < lowlink_of[v] else lowlink_of[v] ) if lowlink_of[v] == index_of[v]: component = [] w = stack.pop() on_stack[w] = False component.append(w) while w != v: w = stack.pop() on_stack[w] = False component.append(w) components.append(component) return index components = [] for v in range(n): if index_of[v] == -1: strong_connect(v, 0, components) return components def create_graph(n, edges): g = [[] for _ in range(n)] for u, v in edges: g[u].append(v) return g if __name__ == "__main__": # Test n_vertices = 7 source = [0, 0, 1, 2, 3, 3, 4, 4, 6] target = [1, 3, 2, 0, 1, 4, 5, 6, 5] edges = [(u, v) for u, v in zip(source, target)] g = create_graph(n_vertices, edges) assert [[5], [6], [4], [3, 2, 1, 0]] == tarjan(g)
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
def remove_digit(num: int) -> int: """ returns the biggest possible result that can be achieved by removing one digit from the given number >>> remove_digit(152) 52 >>> remove_digit(6385) 685 >>> remove_digit(-11) 1 >>> remove_digit(2222222) 222222 >>> remove_digit("2222222") Traceback (most recent call last): TypeError: only integers accepted as input >>> remove_digit("string input") Traceback (most recent call last): TypeError: only integers accepted as input """ if not isinstance(num, int): raise TypeError("only integers accepted as input") else: num_str = str(abs(num)) num_transpositions = [list(num_str) for char in range(len(num_str))] for index in range(len(num_str)): num_transpositions[index].pop(index) return max( int("".join(list(transposition))) for transposition in num_transpositions ) if __name__ == "__main__": __import__("doctest").testmod()
def remove_digit(num: int) -> int: """ returns the biggest possible result that can be achieved by removing one digit from the given number >>> remove_digit(152) 52 >>> remove_digit(6385) 685 >>> remove_digit(-11) 1 >>> remove_digit(2222222) 222222 >>> remove_digit("2222222") Traceback (most recent call last): TypeError: only integers accepted as input >>> remove_digit("string input") Traceback (most recent call last): TypeError: only integers accepted as input """ if not isinstance(num, int): raise TypeError("only integers accepted as input") else: num_str = str(abs(num)) num_transpositions = [list(num_str) for char in range(len(num_str))] for index in range(len(num_str)): num_transpositions[index].pop(index) return max( int("".join(list(transposition))) for transposition in num_transpositions ) if __name__ == "__main__": __import__("doctest").testmod()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" == Automorphic Numbers == A number n is said to be a Automorphic number if the square of n "ends" in the same digits as n itself. Examples of Automorphic Numbers: 0, 1, 5, 6, 25, 76, 376, 625, 9376, 90625, ... https://en.wikipedia.org/wiki/Automorphic_number """ # Author : Akshay Dubey (https://github.com/itsAkshayDubey) # Time Complexity : O(log10n) def is_automorphic_number(number: int) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes an integer number as input. returns True if the number is automorphic. >>> is_automorphic_number(-1) False >>> is_automorphic_number(0) True >>> is_automorphic_number(5) True >>> is_automorphic_number(6) True >>> is_automorphic_number(7) False >>> is_automorphic_number(25) True >>> is_automorphic_number(259918212890625) True >>> is_automorphic_number(259918212890636) False >>> is_automorphic_number(740081787109376) True >>> is_automorphic_number(5.0) Traceback (most recent call last): ... TypeError: Input value of [number=5.0] must be an integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 0: return False number_square = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
""" == Automorphic Numbers == A number n is said to be a Automorphic number if the square of n "ends" in the same digits as n itself. Examples of Automorphic Numbers: 0, 1, 5, 6, 25, 76, 376, 625, 9376, 90625, ... https://en.wikipedia.org/wiki/Automorphic_number """ # Author : Akshay Dubey (https://github.com/itsAkshayDubey) # Time Complexity : O(log10n) def is_automorphic_number(number: int) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes an integer number as input. returns True if the number is automorphic. >>> is_automorphic_number(-1) False >>> is_automorphic_number(0) True >>> is_automorphic_number(5) True >>> is_automorphic_number(6) True >>> is_automorphic_number(7) False >>> is_automorphic_number(25) True >>> is_automorphic_number(259918212890625) True >>> is_automorphic_number(259918212890636) False >>> is_automorphic_number(740081787109376) True >>> is_automorphic_number(5.0) Traceback (most recent call last): ... TypeError: Input value of [number=5.0] must be an integer """ if not isinstance(number, int): msg = f"Input value of [number={number}] must be an integer" raise TypeError(msg) if number < 0: return False number_square = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 3: https://projecteuler.net/problem=3 Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? References: - https://en.wikipedia.org/wiki/Prime_number#Unique_factorization """ def solution(n: int = 600851475143) -> int: """ Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 >>> solution(3.4) 3 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") i = 2 ans = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 ans = i while n % i == 0: n = n // i i += 1 return int(ans) if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 3: https://projecteuler.net/problem=3 Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? References: - https://en.wikipedia.org/wiki/Prime_number#Unique_factorization """ def solution(n: int = 600851475143) -> int: """ Returns the largest prime factor of a given number n. >>> solution(13195) 29 >>> solution(10) 5 >>> solution(17) 17 >>> solution(3.4) 3 >>> solution(0) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution(-17) Traceback (most recent call last): ... ValueError: Parameter n must be greater than or equal to one. >>> solution([]) Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. >>> solution("asd") Traceback (most recent call last): ... TypeError: Parameter n must be int or castable to int. """ try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") i = 2 ans = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 ans = i while n % i == 0: n = n // i i += 1 return int(ans) if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Fast Polynomial Multiplication using radix-2 fast Fourier Transform. """ import mpmath # for roots of unity import numpy as np class FFT: """ Fast Polynomial Multiplication using radix-2 fast Fourier Transform. Reference: https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#The_radix-2_DIT_case For polynomials of degree m and n the algorithms has complexity O(n*logn + m*logm) The main part of the algorithm is split in two parts: 1) __DFT: We compute the discrete fourier transform (DFT) of A and B using a bottom-up dynamic approach - 2) __multiply: Once we obtain the DFT of A*B, we can similarly invert it to obtain A*B The class FFT takes two polynomials A and B with complex coefficients as arguments; The two polynomials should be represented as a sequence of coefficients starting from the free term. Thus, for instance x + 2*x^3 could be represented as [0,1,0,2] or (0,1,0,2). The constructor adds some zeros at the end so that the polynomials have the same length which is a power of 2 at least the length of their product. Example: Create two polynomials as sequences >>> A = [0, 1, 0, 2] # x+2x^3 >>> B = (2, 3, 4, 0) # 2+3x+4x^2 Create an FFT object with them >>> x = FFT(A, B) Print product >>> x.product # 2x + 3x^2 + 8x^3 + 4x^4 + 6x^5 [(-0+0j), (2+0j), (3+0j), (8+0j), (6+0j), (8+0j)] __str__ test >>> print(x) A = 0*x^0 + 1*x^1 + 2*x^0 + 3*x^2 B = 0*x^2 + 1*x^3 + 2*x^4 A*B = 0*x^(-0+0j) + 1*x^(2+0j) + 2*x^(3+0j) + 3*x^(8+0j) + 4*x^(6+0j) + 5*x^(8+0j) """ def __init__(self, poly_a=None, poly_b=None): # Input as list self.polyA = list(poly_a or [0])[:] self.polyB = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() self.len_A = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() self.len_B = len(self.polyB) # Add 0 to make lengths equal a power of 2 self.c_max_length = int( 2 ** np.ceil(np.log2(len(self.polyA) + len(self.polyB) - 1)) ) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform self.root = complex(mpmath.root(x=1, n=self.c_max_length, k=1)) # The product self.product = self.__multiply() # Discrete fourier transform of A and B def __dft(self, which): dft = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB] # Corner case if len(dft) <= 1: return dft[0] # next_ncol = self.c_max_length // 2 while next_ncol > 0: new_dft = [[] for i in range(next_ncol)] root = self.root**next_ncol # First half of next step current_root = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step current_root = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update dft = new_dft next_ncol = next_ncol // 2 return dft[0] # multiply the DFTs of A and B and find A*B def __multiply(self): dft_a = self.__dft("A") dft_b = self.__dft("B") inverce_c = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT next_ncol = 2 while next_ncol <= self.c_max_length: new_inverse_c = [[] for i in range(next_ncol)] root = self.root ** (next_ncol // 2) current_root = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2 ) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root # Update inverce_c = new_inverse_c next_ncol *= 2 # Unpack inverce_c = [round(x[0].real, 8) + round(x[0].imag, 8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c # Overwrite __str__ for print(); Shows A, B and A*B def __str__(self): a = "A = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyA[: self.len_A]) ) b = "B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyB[: self.len_B]) ) c = "A*B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.product) ) return f"{a}\n{b}\n{c}" # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
""" Fast Polynomial Multiplication using radix-2 fast Fourier Transform. """ import mpmath # for roots of unity import numpy as np class FFT: """ Fast Polynomial Multiplication using radix-2 fast Fourier Transform. Reference: https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#The_radix-2_DIT_case For polynomials of degree m and n the algorithms has complexity O(n*logn + m*logm) The main part of the algorithm is split in two parts: 1) __DFT: We compute the discrete fourier transform (DFT) of A and B using a bottom-up dynamic approach - 2) __multiply: Once we obtain the DFT of A*B, we can similarly invert it to obtain A*B The class FFT takes two polynomials A and B with complex coefficients as arguments; The two polynomials should be represented as a sequence of coefficients starting from the free term. Thus, for instance x + 2*x^3 could be represented as [0,1,0,2] or (0,1,0,2). The constructor adds some zeros at the end so that the polynomials have the same length which is a power of 2 at least the length of their product. Example: Create two polynomials as sequences >>> A = [0, 1, 0, 2] # x+2x^3 >>> B = (2, 3, 4, 0) # 2+3x+4x^2 Create an FFT object with them >>> x = FFT(A, B) Print product >>> x.product # 2x + 3x^2 + 8x^3 + 4x^4 + 6x^5 [(-0+0j), (2+0j), (3+0j), (8+0j), (6+0j), (8+0j)] __str__ test >>> print(x) A = 0*x^0 + 1*x^1 + 2*x^0 + 3*x^2 B = 0*x^2 + 1*x^3 + 2*x^4 A*B = 0*x^(-0+0j) + 1*x^(2+0j) + 2*x^(3+0j) + 3*x^(8+0j) + 4*x^(6+0j) + 5*x^(8+0j) """ def __init__(self, poly_a=None, poly_b=None): # Input as list self.polyA = list(poly_a or [0])[:] self.polyB = list(poly_b or [0])[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() self.len_A = len(self.polyA) while self.polyB[-1] == 0: self.polyB.pop() self.len_B = len(self.polyB) # Add 0 to make lengths equal a power of 2 self.c_max_length = int( 2 ** np.ceil(np.log2(len(self.polyA) + len(self.polyB) - 1)) ) while len(self.polyA) < self.c_max_length: self.polyA.append(0) while len(self.polyB) < self.c_max_length: self.polyB.append(0) # A complex root used for the fourier transform self.root = complex(mpmath.root(x=1, n=self.c_max_length, k=1)) # The product self.product = self.__multiply() # Discrete fourier transform of A and B def __dft(self, which): dft = [[x] for x in self.polyA] if which == "A" else [[x] for x in self.polyB] # Corner case if len(dft) <= 1: return dft[0] # next_ncol = self.c_max_length // 2 while next_ncol > 0: new_dft = [[] for i in range(next_ncol)] root = self.root**next_ncol # First half of next step current_root = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j]) current_root *= root # Second half of next step current_root = 1 for j in range(self.c_max_length // (next_ncol * 2)): for i in range(next_ncol): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j]) current_root *= root # Update dft = new_dft next_ncol = next_ncol // 2 return dft[0] # multiply the DFTs of A and B and find A*B def __multiply(self): dft_a = self.__dft("A") dft_b = self.__dft("B") inverce_c = [[dft_a[i] * dft_b[i] for i in range(self.c_max_length)]] del dft_a del dft_b # Corner Case if len(inverce_c[0]) <= 1: return inverce_c[0] # Inverse DFT next_ncol = 2 while next_ncol <= self.c_max_length: new_inverse_c = [[] for i in range(next_ncol)] root = self.root ** (next_ncol // 2) current_root = 1 # First half of next step for j in range(self.c_max_length // next_ncol): for i in range(next_ncol // 2): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2 ) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root # Update inverce_c = new_inverse_c next_ncol *= 2 # Unpack inverce_c = [round(x[0].real, 8) + round(x[0].imag, 8) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c # Overwrite __str__ for print(); Shows A, B and A*B def __str__(self): a = "A = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyA[: self.len_A]) ) b = "B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.polyB[: self.len_B]) ) c = "A*B = " + " + ".join( f"{coef}*x^{i}" for coef, i in enumerate(self.product) ) return f"{a}\n{b}\n{c}" # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# Algorithms to determine if a string is palindrome from timeit import timeit test_data = { "MALAYALAM": True, "String": False, "rotor": True, "level": True, "A": True, "BB": True, "ABC": False, "amanaplanacanalpanama": True, # "a man a plan a canal panama" } # Ensure our test data is valid assert all((key == key[::-1]) is value for key, value in test_data.items()) def is_palindrome(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome(key) is value for key, value in test_data.items()) True """ start_i = 0 end_i = len(s) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True def is_palindrome_traversal(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_traversal(key) is value for key, value in test_data.items()) True """ end = len(s) // 2 n = len(s) # We need to traverse till half of the length of string # as we can get access of the i'th last element from # i'th index. # eg: [0,1,2,3,4,5] => 4th index can be accessed # with the help of 1st index (i==n-i-1) # where n is length of string return all(s[i] == s[n - i - 1] for i in range(end)) def is_palindrome_recursive(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_recursive(key) is value for key, value in test_data.items()) True """ if len(s) <= 2: return True if s[0] == s[len(s) - 1]: return is_palindrome_recursive(s[1:-1]) else: return False def is_palindrome_slice(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_slice(key) is value for key, value in test_data.items()) True """ return s == s[::-1] def benchmark_function(name: str) -> None: stmt = f"all({name}(key) is value for key, value in test_data.items())" setup = f"from __main__ import test_data, {name}" number = 500000 result = timeit(stmt=stmt, setup=setup, number=number) print(f"{name:<35} finished {number:,} runs in {result:.5f} seconds") if __name__ == "__main__": for key, value in test_data.items(): assert is_palindrome(key) is is_palindrome_recursive(key) assert is_palindrome(key) is is_palindrome_slice(key) print(f"{key:21} {value}") print("a man a plan a canal panama") # finished 500,000 runs in 0.46793 seconds benchmark_function("is_palindrome_slice") # finished 500,000 runs in 0.85234 seconds benchmark_function("is_palindrome") # finished 500,000 runs in 1.32028 seconds benchmark_function("is_palindrome_recursive") # finished 500,000 runs in 2.08679 seconds benchmark_function("is_palindrome_traversal")
# Algorithms to determine if a string is palindrome from timeit import timeit test_data = { "MALAYALAM": True, "String": False, "rotor": True, "level": True, "A": True, "BB": True, "ABC": False, "amanaplanacanalpanama": True, # "a man a plan a canal panama" } # Ensure our test data is valid assert all((key == key[::-1]) is value for key, value in test_data.items()) def is_palindrome(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome(key) is value for key, value in test_data.items()) True """ start_i = 0 end_i = len(s) - 1 while start_i < end_i: if s[start_i] == s[end_i]: start_i += 1 end_i -= 1 else: return False return True def is_palindrome_traversal(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_traversal(key) is value for key, value in test_data.items()) True """ end = len(s) // 2 n = len(s) # We need to traverse till half of the length of string # as we can get access of the i'th last element from # i'th index. # eg: [0,1,2,3,4,5] => 4th index can be accessed # with the help of 1st index (i==n-i-1) # where n is length of string return all(s[i] == s[n - i - 1] for i in range(end)) def is_palindrome_recursive(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_recursive(key) is value for key, value in test_data.items()) True """ if len(s) <= 2: return True if s[0] == s[len(s) - 1]: return is_palindrome_recursive(s[1:-1]) else: return False def is_palindrome_slice(s: str) -> bool: """ Return True if s is a palindrome otherwise return False. >>> all(is_palindrome_slice(key) is value for key, value in test_data.items()) True """ return s == s[::-1] def benchmark_function(name: str) -> None: stmt = f"all({name}(key) is value for key, value in test_data.items())" setup = f"from __main__ import test_data, {name}" number = 500000 result = timeit(stmt=stmt, setup=setup, number=number) print(f"{name:<35} finished {number:,} runs in {result:.5f} seconds") if __name__ == "__main__": for key, value in test_data.items(): assert is_palindrome(key) is is_palindrome_recursive(key) assert is_palindrome(key) is is_palindrome_slice(key) print(f"{key:21} {value}") print("a man a plan a canal panama") # finished 500,000 runs in 0.46793 seconds benchmark_function("is_palindrome_slice") # finished 500,000 runs in 0.85234 seconds benchmark_function("is_palindrome") # finished 500,000 runs in 1.32028 seconds benchmark_function("is_palindrome_recursive") # finished 500,000 runs in 2.08679 seconds benchmark_function("is_palindrome_traversal")
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Arithmetic mean Reference: https://en.wikipedia.org/wiki/Arithmetic_mean Arithmetic series Reference: https://en.wikipedia.org/wiki/Arithmetic_series (The URL above will redirect you to arithmetic progression) """ def is_arithmetic_series(series: list) -> bool: """ checking whether the input series is arithmetic series or not >>> is_arithmetic_series([2, 4, 6]) True >>> is_arithmetic_series([3, 6, 12, 24]) False >>> is_arithmetic_series([1, 2, 3]) True >>> is_arithmetic_series(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> is_arithmetic_series([]) 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, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1: return True common_diff = series[1] - series[0] for index in range(len(series) - 1): if series[index + 1] - series[index] != common_diff: return False return True def arithmetic_mean(series: list) -> float: """ return the arithmetic mean of series >>> arithmetic_mean([2, 4, 6]) 4.0 >>> arithmetic_mean([3, 6, 9, 12]) 7.5 >>> arithmetic_mean(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> arithmetic_mean([4, 8, 1]) 4.333333333333333 >>> arithmetic_mean([1, 2, 3]) 2.0 >>> arithmetic_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, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") answer = 0 for val in series: answer += val return answer / len(series) if __name__ == "__main__": import doctest doctest.testmod()
""" Arithmetic mean Reference: https://en.wikipedia.org/wiki/Arithmetic_mean Arithmetic series Reference: https://en.wikipedia.org/wiki/Arithmetic_series (The URL above will redirect you to arithmetic progression) """ def is_arithmetic_series(series: list) -> bool: """ checking whether the input series is arithmetic series or not >>> is_arithmetic_series([2, 4, 6]) True >>> is_arithmetic_series([3, 6, 12, 24]) False >>> is_arithmetic_series([1, 2, 3]) True >>> is_arithmetic_series(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> is_arithmetic_series([]) 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, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") if len(series) == 1: return True common_diff = series[1] - series[0] for index in range(len(series) - 1): if series[index + 1] - series[index] != common_diff: return False return True def arithmetic_mean(series: list) -> float: """ return the arithmetic mean of series >>> arithmetic_mean([2, 4, 6]) 4.0 >>> arithmetic_mean([3, 6, 9, 12]) 7.5 >>> arithmetic_mean(4) Traceback (most recent call last): ... ValueError: Input series is not valid, valid series - [2, 4, 6] >>> arithmetic_mean([4, 8, 1]) 4.333333333333333 >>> arithmetic_mean([1, 2, 3]) 2.0 >>> arithmetic_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, 6]") if len(series) == 0: raise ValueError("Input list must be a non empty list") answer = 0 for val in series: answer += val return answer / len(series) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Minimalist file that allows pytest to find and run the Test unittest. For details, see: https://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: https://doc.pytest.org/en/latest/goodpractices.html#conventions-for-python-test-discovery """ from .prime_check import Test Test()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
"""Non recursive implementation of a DFS algorithm.""" from __future__ import annotations def depth_first_search(graph: dict, start: str) -> set[str]: """Depth First Search on Graph :param graph: directed graph in dictionary format :param start: starting vertex as a string :returns: the trace of the search >>> input_G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"], ... "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"], ... "F": ["C", "E", "G"], "G": ["F"] } >>> output_G = list({'A', 'B', 'C', 'D', 'E', 'F', 'G'}) >>> all(x in output_G for x in list(depth_first_search(input_G, "A"))) True >>> all(x in output_G for x in list(depth_first_search(input_G, "G"))) True """ explored, stack = set(start), [start] while stack: v = stack.pop() explored.add(v) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v]): if adj not in explored: stack.append(adj) return explored G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"], "F": ["C", "E", "G"], "G": ["F"], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, "A"))
"""Non recursive implementation of a DFS algorithm.""" from __future__ import annotations def depth_first_search(graph: dict, start: str) -> set[str]: """Depth First Search on Graph :param graph: directed graph in dictionary format :param start: starting vertex as a string :returns: the trace of the search >>> input_G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"], ... "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"], ... "F": ["C", "E", "G"], "G": ["F"] } >>> output_G = list({'A', 'B', 'C', 'D', 'E', 'F', 'G'}) >>> all(x in output_G for x in list(depth_first_search(input_G, "A"))) True >>> all(x in output_G for x in list(depth_first_search(input_G, "G"))) True """ explored, stack = set(start), [start] while stack: v = stack.pop() explored.add(v) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v]): if adj not in explored: stack.append(adj) return explored G = { "A": ["B", "C", "D"], "B": ["A", "D", "E"], "C": ["A", "F"], "D": ["B", "D"], "E": ["B", "F"], "F": ["C", "E", "G"], "G": ["F"], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, "A"))
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
import socket def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() port = 12312 sock.connect((host, port)) sock.send(b"Hello server!") with open("Received_file", "wb") as out_file: print("File opened") print("Receiving data...") while True: data = sock.recv(1024) if not data: break out_file.write(data) print("Successfully received the file") sock.close() print("Connection closed") if __name__ == "__main__": main()
import socket def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() port = 12312 sock.connect((host, port)) sock.send(b"Hello server!") with open("Received_file", "wb") as out_file: print("File opened") print("Receiving data...") while True: data = sock.recv(1024) if not data: break out_file.write(data) print("Successfully received the file") sock.close() print("Connection closed") if __name__ == "__main__": main()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" https://en.wikipedia.org/wiki/N-gram """ def create_ngram(sentence: str, ngram_size: int) -> list[str]: """ Create ngrams from a sentence >>> create_ngram("I am a sentence", 2) ['I ', ' a', 'am', 'm ', ' a', 'a ', ' s', 'se', 'en', 'nt', 'te', 'en', 'nc', 'ce'] >>> create_ngram("I am an NLPer", 2) ['I ', ' a', 'am', 'm ', ' a', 'an', 'n ', ' N', 'NL', 'LP', 'Pe', 'er'] >>> create_ngram("This is short", 50) [] """ return [sentence[i : i + ngram_size] for i in range(len(sentence) - ngram_size + 1)] if __name__ == "__main__": from doctest import testmod testmod()
""" https://en.wikipedia.org/wiki/N-gram """ def create_ngram(sentence: str, ngram_size: int) -> list[str]: """ Create ngrams from a sentence >>> create_ngram("I am a sentence", 2) ['I ', ' a', 'am', 'm ', ' a', 'a ', ' s', 'se', 'en', 'nt', 'te', 'en', 'nc', 'ce'] >>> create_ngram("I am an NLPer", 2) ['I ', ' a', 'am', 'm ', ' a', 'an', 'n ', ' N', 'NL', 'LP', 'Pe', 'er'] >>> create_ngram("This is short", 50) [] """ return [sentence[i : i + ngram_size] for i in range(len(sentence) - ngram_size + 1)] if __name__ == "__main__": from doctest import testmod testmod()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" The root-mean-square speed is essential in measuring the average speed of particles contained in a gas, defined as, ----------------- | Vrms = √3RT/M | ----------------- In Kinetic Molecular Theory, gasified particles are in a condition of constant random motion; each particle moves at a completely different pace, perpetually clashing and changing directions consistently velocity is used to describe the movement of gas particles, thereby taking into account both speed and direction. Although the velocity of gaseous particles is constantly changing, the distribution of velocities does not change. We cannot gauge the velocity of every individual particle, thus we frequently reason in terms of the particles average behavior. Particles moving in opposite directions have velocities of opposite signs. Since gas particles are in random motion, it's plausible that there'll be about as several moving in one direction as within the other way, which means that the average velocity for a collection of gas particles equals zero; as this value is unhelpful, the average of velocities can be determined using an alternative method. """ UNIVERSAL_GAS_CONSTANT = 8.3144598 def rms_speed_of_molecule(temperature: float, molar_mass: float) -> float: """ >>> rms_speed_of_molecule(100, 2) 35.315279554323226 >>> rms_speed_of_molecule(273, 12) 23.821458421977443 """ if temperature < 0: raise Exception("Temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass cannot be less than or equal to 0 kg/mol") else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example temperature = 300 molar_mass = 28 vrms = rms_speed_of_molecule(temperature, molar_mass) print(f"Vrms of Nitrogen gas at 300 K is {vrms} m/s")
""" The root-mean-square speed is essential in measuring the average speed of particles contained in a gas, defined as, ----------------- | Vrms = √3RT/M | ----------------- In Kinetic Molecular Theory, gasified particles are in a condition of constant random motion; each particle moves at a completely different pace, perpetually clashing and changing directions consistently velocity is used to describe the movement of gas particles, thereby taking into account both speed and direction. Although the velocity of gaseous particles is constantly changing, the distribution of velocities does not change. We cannot gauge the velocity of every individual particle, thus we frequently reason in terms of the particles average behavior. Particles moving in opposite directions have velocities of opposite signs. Since gas particles are in random motion, it's plausible that there'll be about as several moving in one direction as within the other way, which means that the average velocity for a collection of gas particles equals zero; as this value is unhelpful, the average of velocities can be determined using an alternative method. """ UNIVERSAL_GAS_CONSTANT = 8.3144598 def rms_speed_of_molecule(temperature: float, molar_mass: float) -> float: """ >>> rms_speed_of_molecule(100, 2) 35.315279554323226 >>> rms_speed_of_molecule(273, 12) 23.821458421977443 """ if temperature < 0: raise Exception("Temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass cannot be less than or equal to 0 kg/mol") else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example temperature = 300 molar_mass = 28 vrms = rms_speed_of_molecule(temperature, molar_mass) print(f"Vrms of Nitrogen gas at 300 K is {vrms} m/s")
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
import random import sys from . import cryptomath_module as cryptomath SYMBOLS = ( r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`""" r"""abcdefghijklmnopqrstuvwxyz{|}~""" ) def check_keys(key_a: int, key_b: int, mode: str) -> None: if mode == "encrypt": if key_a == 1: sys.exit( "The affine cipher becomes weak when key " "A is set to 1. Choose different key" ) if key_b == 0: sys.exit( "The affine cipher becomes weak when key " "B is set to 0. Choose different key" ) if key_a < 0 or key_b < 0 or key_b > len(SYMBOLS) - 1: sys.exit( "Key A must be greater than 0 and key B must " f"be between 0 and {len(SYMBOLS) - 1}." ) if cryptomath.gcd(key_a, len(SYMBOLS)) != 1: sys.exit( f"Key A {key_a} and the symbol set size {len(SYMBOLS)} " "are not relatively prime. Choose a different key." ) def encrypt_message(key: int, message: str) -> str: """ >>> encrypt_message(4545, 'The affine cipher is a type of monoalphabetic ' ... 'substitution cipher.') 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF{xIp~{HL}Gi' """ key_a, key_b = divmod(key, len(SYMBOLS)) check_keys(key_a, key_b, "encrypt") cipher_text = "" for symbol in message: if symbol in SYMBOLS: sym_index = SYMBOLS.find(symbol) cipher_text += SYMBOLS[(sym_index * key_a + key_b) % len(SYMBOLS)] else: cipher_text += symbol return cipher_text def decrypt_message(key: int, message: str) -> str: """ >>> decrypt_message(4545, 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF' ... '{xIp~{HL}Gi') 'The affine cipher is a type of monoalphabetic substitution cipher.' """ key_a, key_b = divmod(key, len(SYMBOLS)) check_keys(key_a, key_b, "decrypt") plain_text = "" mod_inverse_of_key_a = cryptomath.find_mod_inverse(key_a, len(SYMBOLS)) for symbol in message: if symbol in SYMBOLS: sym_index = SYMBOLS.find(symbol) plain_text += SYMBOLS[ (sym_index - key_b) * mod_inverse_of_key_a % len(SYMBOLS) ] else: plain_text += symbol return plain_text def get_random_key() -> int: while True: key_b = random.randint(2, len(SYMBOLS)) key_b = random.randint(2, len(SYMBOLS)) if cryptomath.gcd(key_b, len(SYMBOLS)) == 1 and key_b % len(SYMBOLS) != 0: return key_b * len(SYMBOLS) + key_b def main() -> None: """ >>> key = get_random_key() >>> msg = "This is a test!" >>> decrypt_message(key, encrypt_message(key, msg)) == msg True """ message = input("Enter message: ").strip() key = int(input("Enter key [2000 - 9000]: ").strip()) mode = input("Encrypt/Decrypt [E/D]: ").strip().lower() if mode.startswith("e"): mode = "encrypt" translated = encrypt_message(key, message) elif mode.startswith("d"): mode = "decrypt" translated = decrypt_message(key, message) print(f"\n{mode.title()}ed text: \n{translated}") if __name__ == "__main__": import doctest doctest.testmod() # main()
import random import sys from . import cryptomath_module as cryptomath SYMBOLS = ( r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`""" r"""abcdefghijklmnopqrstuvwxyz{|}~""" ) def check_keys(key_a: int, key_b: int, mode: str) -> None: if mode == "encrypt": if key_a == 1: sys.exit( "The affine cipher becomes weak when key " "A is set to 1. Choose different key" ) if key_b == 0: sys.exit( "The affine cipher becomes weak when key " "B is set to 0. Choose different key" ) if key_a < 0 or key_b < 0 or key_b > len(SYMBOLS) - 1: sys.exit( "Key A must be greater than 0 and key B must " f"be between 0 and {len(SYMBOLS) - 1}." ) if cryptomath.gcd(key_a, len(SYMBOLS)) != 1: sys.exit( f"Key A {key_a} and the symbol set size {len(SYMBOLS)} " "are not relatively prime. Choose a different key." ) def encrypt_message(key: int, message: str) -> str: """ >>> encrypt_message(4545, 'The affine cipher is a type of monoalphabetic ' ... 'substitution cipher.') 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF{xIp~{HL}Gi' """ key_a, key_b = divmod(key, len(SYMBOLS)) check_keys(key_a, key_b, "encrypt") cipher_text = "" for symbol in message: if symbol in SYMBOLS: sym_index = SYMBOLS.find(symbol) cipher_text += SYMBOLS[(sym_index * key_a + key_b) % len(SYMBOLS)] else: cipher_text += symbol return cipher_text def decrypt_message(key: int, message: str) -> str: """ >>> decrypt_message(4545, 'VL}p MM{I}p~{HL}Gp{vp pFsH}pxMpyxIx JHL O}F{~pvuOvF{FuF' ... '{xIp~{HL}Gi') 'The affine cipher is a type of monoalphabetic substitution cipher.' """ key_a, key_b = divmod(key, len(SYMBOLS)) check_keys(key_a, key_b, "decrypt") plain_text = "" mod_inverse_of_key_a = cryptomath.find_mod_inverse(key_a, len(SYMBOLS)) for symbol in message: if symbol in SYMBOLS: sym_index = SYMBOLS.find(symbol) plain_text += SYMBOLS[ (sym_index - key_b) * mod_inverse_of_key_a % len(SYMBOLS) ] else: plain_text += symbol return plain_text def get_random_key() -> int: while True: key_b = random.randint(2, len(SYMBOLS)) key_b = random.randint(2, len(SYMBOLS)) if cryptomath.gcd(key_b, len(SYMBOLS)) == 1 and key_b % len(SYMBOLS) != 0: return key_b * len(SYMBOLS) + key_b def main() -> None: """ >>> key = get_random_key() >>> msg = "This is a test!" >>> decrypt_message(key, encrypt_message(key, msg)) == msg True """ message = input("Enter message: ").strip() key = int(input("Enter key [2000 - 9000]: ").strip()) mode = input("Encrypt/Decrypt [E/D]: ").strip().lower() if mode.startswith("e"): mode = "encrypt" translated = encrypt_message(key, message) elif mode.startswith("d"): mode = "decrypt" translated = decrypt_message(key, message) print(f"\n{mode.title()}ed text: \n{translated}") if __name__ == "__main__": import doctest doctest.testmod() # main()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" This script demonstrates an implementation of the Gaussian Error Linear Unit function. * https://en.wikipedia.org/wiki/Activation_function#Comparison_of_activation_functions The function takes a vector of K real numbers as input and returns x * sigmoid(1.702*x). Gaussian Error Linear Unit (GELU) is a high-performing neural network activation function. This script is inspired by a corresponding research paper. * https://arxiv.org/abs/1606.08415 """ import numpy as np def sigmoid(vector: np.array) -> np.array: """ Mathematical function sigmoid takes a vector x of K real numbers as input and returns 1/ (1 + e^-x). https://en.wikipedia.org/wiki/Sigmoid_function >>> sigmoid(np.array([-1.0, 1.0, 2.0])) array([0.26894142, 0.73105858, 0.88079708]) """ return 1 / (1 + np.exp(-vector)) def gaussian_error_linear_unit(vector: np.array) -> np.array: """ Implements the Gaussian Error Linear Unit (GELU) function Parameters: vector (np.array): A numpy array of shape (1,n) consisting of real values Returns: gelu_vec (np.array): The input numpy array, after applying gelu. Examples: >>> gaussian_error_linear_unit(np.array([-1.0, 1.0, 2.0])) array([-0.15420423, 0.84579577, 1.93565862]) >>> gaussian_error_linear_unit(np.array([-3])) array([-0.01807131]) """ return vector * sigmoid(1.702 * vector) if __name__ == "__main__": import doctest doctest.testmod()
""" This script demonstrates an implementation of the Gaussian Error Linear Unit function. * https://en.wikipedia.org/wiki/Activation_function#Comparison_of_activation_functions The function takes a vector of K real numbers as input and returns x * sigmoid(1.702*x). Gaussian Error Linear Unit (GELU) is a high-performing neural network activation function. This script is inspired by a corresponding research paper. * https://arxiv.org/abs/1606.08415 """ import numpy as np def sigmoid(vector: np.array) -> np.array: """ Mathematical function sigmoid takes a vector x of K real numbers as input and returns 1/ (1 + e^-x). https://en.wikipedia.org/wiki/Sigmoid_function >>> sigmoid(np.array([-1.0, 1.0, 2.0])) array([0.26894142, 0.73105858, 0.88079708]) """ return 1 / (1 + np.exp(-vector)) def gaussian_error_linear_unit(vector: np.array) -> np.array: """ Implements the Gaussian Error Linear Unit (GELU) function Parameters: vector (np.array): A numpy array of shape (1,n) consisting of real values Returns: gelu_vec (np.array): The input numpy array, after applying gelu. Examples: >>> gaussian_error_linear_unit(np.array([-1.0, 1.0, 2.0])) array([-0.15420423, 0.84579577, 1.93565862]) >>> gaussian_error_linear_unit(np.array([-3])) array([-0.01807131]) """ return vector * sigmoid(1.702 * vector) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
#
#
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Finding the 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
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from __future__ import annotations def 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
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" References: wikipedia:square free number psf/black : True ruff : True """ from __future__ import annotations def is_square_free(factors: list[int]) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes a list of prime factors as input. returns True if the factors are square free. >>> is_square_free([1, 1, 2, 3, 4]) False These are wrong but should return some value it simply checks for repetition in the numbers. >>> is_square_free([1, 3, 4, 'sd', 0.0]) True >>> is_square_free([1, 0.5, 2, 0.0]) True >>> is_square_free([1, 2, 2, 5]) False >>> is_square_free('asd') True >>> is_square_free(24) Traceback (most recent call last): ... TypeError: 'int' object is not iterable """ return len(set(factors)) == len(factors) if __name__ == "__main__": import doctest doctest.testmod()
""" References: wikipedia:square free number psf/black : True ruff : True """ from __future__ import annotations def is_square_free(factors: list[int]) -> bool: """ # doctest: +NORMALIZE_WHITESPACE This functions takes a list of prime factors as input. returns True if the factors are square free. >>> is_square_free([1, 1, 2, 3, 4]) False These are wrong but should return some value it simply checks for repetition in the numbers. >>> is_square_free([1, 3, 4, 'sd', 0.0]) True >>> is_square_free([1, 0.5, 2, 0.0]) True >>> is_square_free([1, 2, 2, 5]) False >>> is_square_free('asd') True >>> is_square_free(24) Traceback (most recent call last): ... TypeError: 'int' object is not iterable """ return len(set(factors)) == len(factors) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Non-preemptive Shortest Job First Shortest execution time process is chosen for the next execution. https://www.guru99.com/shortest-job-first-sjf-scheduling.html https://en.wikipedia.org/wiki/Shortest_job_next """ from __future__ import annotations from statistics import mean def calculate_waitingtime( arrival_time: list[int], burst_time: list[int], no_of_processes: int ) -> list[int]: """ Calculate the waiting time of each processes Return: The waiting time for each process. >>> calculate_waitingtime([0,1,2], [10, 5, 8], 3) [0, 9, 13] >>> calculate_waitingtime([1,2,2,4], [4, 6, 3, 1], 4) [0, 7, 4, 1] >>> calculate_waitingtime([0,0,0], [12, 2, 10],3) [12, 0, 2] """ waiting_time = [0] * no_of_processes remaining_time = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(no_of_processes): remaining_time[i] = burst_time[i] ready_process: list[int] = [] completed = 0 total_time = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: ready_process = [] target_process = -1 for i in range(no_of_processes): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(i) if len(ready_process) > 0: target_process = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: target_process = i total_time += burst_time[target_process] completed += 1 remaining_time[target_process] = 0 waiting_time[target_process] = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def calculate_turnaroundtime( burst_time: list[int], no_of_processes: int, waiting_time: list[int] ) -> list[int]: """ Calculate the turnaround time of each process. Return: The turnaround time for each process. >>> calculate_turnaroundtime([0,1,2], 3, [0, 10, 15]) [0, 11, 17] >>> calculate_turnaroundtime([1,2,2,4], 4, [1, 8, 5, 4]) [2, 10, 7, 8] >>> calculate_turnaroundtime([0,0,0], 3, [12, 0, 2]) [12, 0, 2] """ turn_around_time = [0] * no_of_processes for i in range(no_of_processes): turn_around_time[i] = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") no_of_processes = 4 burst_time = [2, 5, 3, 7] arrival_time = [0, 0, 0, 0] waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes) turn_around_time = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( f"{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t" f"{waiting_time[i]}\t\t\t\t{turn_around_time[i]}" ) print(f"\nAverage waiting time = {mean(waiting_time):.5f}") print(f"Average turnaround time = {mean(turn_around_time):.5f}")
""" Non-preemptive Shortest Job First Shortest execution time process is chosen for the next execution. https://www.guru99.com/shortest-job-first-sjf-scheduling.html https://en.wikipedia.org/wiki/Shortest_job_next """ from __future__ import annotations from statistics import mean def calculate_waitingtime( arrival_time: list[int], burst_time: list[int], no_of_processes: int ) -> list[int]: """ Calculate the waiting time of each processes Return: The waiting time for each process. >>> calculate_waitingtime([0,1,2], [10, 5, 8], 3) [0, 9, 13] >>> calculate_waitingtime([1,2,2,4], [4, 6, 3, 1], 4) [0, 7, 4, 1] >>> calculate_waitingtime([0,0,0], [12, 2, 10],3) [12, 0, 2] """ waiting_time = [0] * no_of_processes remaining_time = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(no_of_processes): remaining_time[i] = burst_time[i] ready_process: list[int] = [] completed = 0 total_time = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: ready_process = [] target_process = -1 for i in range(no_of_processes): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(i) if len(ready_process) > 0: target_process = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: target_process = i total_time += burst_time[target_process] completed += 1 remaining_time[target_process] = 0 waiting_time[target_process] = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def calculate_turnaroundtime( burst_time: list[int], no_of_processes: int, waiting_time: list[int] ) -> list[int]: """ Calculate the turnaround time of each process. Return: The turnaround time for each process. >>> calculate_turnaroundtime([0,1,2], 3, [0, 10, 15]) [0, 11, 17] >>> calculate_turnaroundtime([1,2,2,4], 4, [1, 8, 5, 4]) [2, 10, 7, 8] >>> calculate_turnaroundtime([0,0,0], 3, [12, 0, 2]) [12, 0, 2] """ turn_around_time = [0] * no_of_processes for i in range(no_of_processes): turn_around_time[i] = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") no_of_processes = 4 burst_time = [2, 5, 3, 7] arrival_time = [0, 0, 0, 0] waiting_time = calculate_waitingtime(arrival_time, burst_time, no_of_processes) turn_around_time = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( f"{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t" f"{waiting_time[i]}\t\t\t\t{turn_around_time[i]}" ) print(f"\nAverage waiting time = {mean(waiting_time):.5f}") print(f"Average turnaround time = {mean(turn_around_time):.5f}")
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# https://en.wikipedia.org/wiki/Fizz_buzz#Programming def fizz_buzz(number: int, iterations: int) -> str: """ Plays FizzBuzz. Prints Fizz if number is a multiple of 3. Prints Buzz if its a multiple of 5. Prints FizzBuzz if its a multiple of both 3 and 5 or 15. Else Prints The Number Itself. >>> fizz_buzz(1,7) '1 2 Fizz 4 Buzz Fizz 7 ' >>> fizz_buzz(1,0) Traceback (most recent call last): ... ValueError: Iterations must be done more than 0 times to play FizzBuzz >>> fizz_buzz(-5,5) Traceback (most recent call last): ... ValueError: starting number must be and integer and be more than 0 >>> fizz_buzz(10,-5) Traceback (most recent call last): ... ValueError: Iterations must be done more than 0 times to play FizzBuzz >>> fizz_buzz(1.5,5) Traceback (most recent call last): ... ValueError: starting number must be and integer and be more than 0 >>> fizz_buzz(1,5.5) Traceback (most recent call last): ... ValueError: iterations must be defined as integers """ if not isinstance(iterations, int): raise ValueError("iterations must be defined as integers") if not isinstance(number, int) or not number >= 1: raise ValueError( """starting number must be and integer and be more than 0""" ) if not iterations >= 1: raise ValueError("Iterations must be done more than 0 times to play FizzBuzz") out = "" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(number) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
# https://en.wikipedia.org/wiki/Fizz_buzz#Programming def fizz_buzz(number: int, iterations: int) -> str: """ Plays FizzBuzz. Prints Fizz if number is a multiple of 3. Prints Buzz if its a multiple of 5. Prints FizzBuzz if its a multiple of both 3 and 5 or 15. Else Prints The Number Itself. >>> fizz_buzz(1,7) '1 2 Fizz 4 Buzz Fizz 7 ' >>> fizz_buzz(1,0) Traceback (most recent call last): ... ValueError: Iterations must be done more than 0 times to play FizzBuzz >>> fizz_buzz(-5,5) Traceback (most recent call last): ... ValueError: starting number must be and integer and be more than 0 >>> fizz_buzz(10,-5) Traceback (most recent call last): ... ValueError: Iterations must be done more than 0 times to play FizzBuzz >>> fizz_buzz(1.5,5) Traceback (most recent call last): ... ValueError: starting number must be and integer and be more than 0 >>> fizz_buzz(1,5.5) Traceback (most recent call last): ... ValueError: iterations must be defined as integers """ if not isinstance(iterations, int): raise ValueError("iterations must be defined as integers") if not isinstance(number, int) or not number >= 1: raise ValueError( """starting number must be and integer and be more than 0""" ) if not iterations >= 1: raise ValueError("Iterations must be done more than 0 times to play FizzBuzz") out = "" while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(number) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 80: https://projecteuler.net/problem=80 Author: Sandeep Gupta Problem statement: For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits for all the irrational square roots. Time: 5 October 2020, 18:30 """ import decimal def solution() -> int: """ To evaluate the sum, Used decimal python module to calculate the decimal places up to 100, the most important thing would be take calculate a few extra places for decimal otherwise there will be rounding error. >>> solution() 40886 """ answer = 0 decimal_context = decimal.Context(prec=105) for i in range(2, 100): number = decimal.Decimal(i) sqrt_number = number.sqrt(decimal_context) if len(str(sqrt_number)) > 1: answer += int(str(sqrt_number)[0]) sqrt_number_str = str(sqrt_number)[2:101] answer += sum(int(x) for x in sqrt_number_str) return answer if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
""" Project Euler Problem 80: https://projecteuler.net/problem=80 Author: Sandeep Gupta Problem statement: For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits for all the irrational square roots. Time: 5 October 2020, 18:30 """ import decimal def solution() -> int: """ To evaluate the sum, Used decimal python module to calculate the decimal places up to 100, the most important thing would be take calculate a few extra places for decimal otherwise there will be rounding error. >>> solution() 40886 """ answer = 0 decimal_context = decimal.Context(prec=105) for i in range(2, 100): number = decimal.Decimal(i) sqrt_number = number.sqrt(decimal_context) if len(str(sqrt_number)) > 1: answer += int(str(sqrt_number)[0]) sqrt_number_str = str(sqrt_number)[2:101] answer += sum(int(x) for x in sqrt_number_str) return answer if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital. HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. """ import itertools def is_combination_valid(combination): """ Checks if a combination (a tuple of 9 digits) is a valid product equation. >>> is_combination_valid(('3', '9', '1', '8', '6', '7', '2', '5', '4')) True >>> is_combination_valid(('1', '2', '3', '4', '5', '6', '7', '8', '9')) False """ return ( int("".join(combination[0:2])) * int("".join(combination[2:5])) == int("".join(combination[5:9])) ) or ( int("".join(combination[0])) * int("".join(combination[1:5])) == int("".join(combination[5:9])) ) def solution(): """ Finds the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital >>> solution() 45228 """ return sum( { int("".join(pandigital[5:9])) for pandigital in itertools.permutations("123456789") if is_combination_valid(pandigital) } ) if __name__ == "__main__": print(solution())
""" We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital. The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital. Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital. HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum. """ import itertools def is_combination_valid(combination): """ Checks if a combination (a tuple of 9 digits) is a valid product equation. >>> is_combination_valid(('3', '9', '1', '8', '6', '7', '2', '5', '4')) True >>> is_combination_valid(('1', '2', '3', '4', '5', '6', '7', '8', '9')) False """ return ( int("".join(combination[0:2])) * int("".join(combination[2:5])) == int("".join(combination[5:9])) ) or ( int("".join(combination[0])) * int("".join(combination[1:5])) == int("".join(combination[5:9])) ) def solution(): """ Finds the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital >>> solution() 45228 """ return sum( { int("".join(pandigital[5:9])) for pandigital in itertools.permutations("123456789") if is_combination_valid(pandigital) } ) if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# Eulers Totient function finds the number of relative primes of a number n from 1 to n def totient(n: int) -> list: """ >>> 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. """ 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 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: """ >>> 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. """ 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 if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" What is the greatest product of four adjacent numbers (horizontally, vertically, or diagonally) in this 20x20 array? 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ import os def solution(): """Returns the greatest product of four adjacent numbers (horizontally, vertically, or diagonally). >>> solution() 70600674 """ with open(os.path.dirname(__file__) + "/grid.txt") as f: l = [] # noqa: E741 for _ in range(20): l.append([int(x) for x in f.readline().split()]) maximum = 0 # right for i in range(20): for j in range(17): temp = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: maximum = temp # down for i in range(17): for j in range(20): temp = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: maximum = temp # diagonal 1 for i in range(17): for j in range(17): temp = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: maximum = temp # diagonal 2 for i in range(17): for j in range(3, 20): temp = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: maximum = temp return maximum if __name__ == "__main__": print(solution())
""" What is the greatest product of four adjacent numbers (horizontally, vertically, or diagonally) in this 20x20 array? 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 """ import os def solution(): """Returns the greatest product of four adjacent numbers (horizontally, vertically, or diagonally). >>> solution() 70600674 """ with open(os.path.dirname(__file__) + "/grid.txt") as f: l = [] # noqa: E741 for _ in range(20): l.append([int(x) for x in f.readline().split()]) maximum = 0 # right for i in range(20): for j in range(17): temp = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: maximum = temp # down for i in range(17): for j in range(20): temp = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: maximum = temp # diagonal 1 for i in range(17): for j in range(17): temp = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: maximum = temp # diagonal 2 for i in range(17): for j in range(3, 20): temp = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: maximum = temp return maximum if __name__ == "__main__": print(solution())
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# Author: João Gustavo A. Amorim # Author email: [email protected] # Coding date: jan 2019 # python/black: True # Imports import numpy as np # Class implemented to calculus the index class IndexCalculation: """ # Class Summary This algorithm consists in calculating vegetation indices, these indices can be used for precision agriculture for example (or remote sensing). There are functions to define the data and to calculate the implemented indices. # Vegetation index https://en.wikipedia.org/wiki/Vegetation_Index A Vegetation Index (VI) is a spectral transformation of two or more bands designed to enhance the contribution of vegetation properties and allow reliable spatial and temporal inter-comparisons of terrestrial photosynthetic activity and canopy structural variations # Information about channels (Wavelength range for each) * nir - near-infrared https://www.malvernpanalytical.com/br/products/technology/near-infrared-spectroscopy Wavelength Range 700 nm to 2500 nm * Red Edge https://en.wikipedia.org/wiki/Red_edge Wavelength Range 680 nm to 730 nm * red https://en.wikipedia.org/wiki/Color Wavelength Range 635 nm to 700 nm * blue https://en.wikipedia.org/wiki/Color Wavelength Range 450 nm to 490 nm * green https://en.wikipedia.org/wiki/Color Wavelength Range 520 nm to 560 nm # Implemented index list #"abbreviationOfIndexName" -- list of channels used #"ARVI2" -- red, nir #"CCCI" -- red, redEdge, nir #"CVI" -- red, green, nir #"GLI" -- red, green, blue #"NDVI" -- red, nir #"BNDVI" -- blue, nir #"redEdgeNDVI" -- red, redEdge #"GNDVI" -- green, nir #"GBNDVI" -- green, blue, nir #"GRNDVI" -- red, green, nir #"RBNDVI" -- red, blue, nir #"PNDVI" -- red, green, blue, nir #"ATSAVI" -- red, nir #"BWDRVI" -- blue, nir #"CIgreen" -- green, nir #"CIrededge" -- redEdge, nir #"CI" -- red, blue #"CTVI" -- red, nir #"GDVI" -- green, nir #"EVI" -- red, blue, nir #"GEMI" -- red, nir #"GOSAVI" -- green, nir #"GSAVI" -- green, nir #"Hue" -- red, green, blue #"IVI" -- red, nir #"IPVI" -- red, nir #"I" -- red, green, blue #"RVI" -- red, nir #"MRVI" -- red, nir #"MSAVI" -- red, nir #"NormG" -- red, green, nir #"NormNIR" -- red, green, nir #"NormR" -- red, green, nir #"NGRDI" -- red, green #"RI" -- red, green #"S" -- red, green, blue #"IF" -- red, green, blue #"DVI" -- red, nir #"TVI" -- red, nir #"NDRE" -- redEdge, nir #list of all index implemented #allIndex = ["ARVI2", "CCCI", "CVI", "GLI", "NDVI", "BNDVI", "redEdgeNDVI", "GNDVI", "GBNDVI", "GRNDVI", "RBNDVI", "PNDVI", "ATSAVI", "BWDRVI", "CIgreen", "CIrededge", "CI", "CTVI", "GDVI", "EVI", "GEMI", "GOSAVI", "GSAVI", "Hue", "IVI", "IPVI", "I", "RVI", "MRVI", "MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI", "S", "IF", "DVI", "TVI", "NDRE"] #list of index with not blue channel #notBlueIndex = ["ARVI2", "CCCI", "CVI", "NDVI", "redEdgeNDVI", "GNDVI", "GRNDVI", "ATSAVI", "CIgreen", "CIrededge", "CTVI", "GDVI", "GEMI", "GOSAVI", "GSAVI", "IVI", "IPVI", "RVI", "MRVI", "MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI", "DVI", "TVI", "NDRE"] #list of index just with RGB channels #RGBIndex = ["GLI", "CI", "Hue", "I", "NGRDI", "RI", "S", "IF"] """ def __init__(self, red=None, green=None, blue=None, red_edge=None, nir=None): self.set_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir) def set_matricies(self, red=None, green=None, blue=None, red_edge=None, nir=None): if red is not None: self.red = red if green is not None: self.green = green if blue is not None: self.blue = blue if red_edge is not None: self.redEdge = red_edge if nir is not None: self.nir = nir return True def calculation( self, index="", red=None, green=None, blue=None, red_edge=None, nir=None ): """ performs the calculation of the index with the values instantiated in the class :str index: abbreviation of index name to perform """ self.set_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir) funcs = { "ARVI2": self.arv12, "CCCI": self.ccci, "CVI": self.cvi, "GLI": self.gli, "NDVI": self.ndvi, "BNDVI": self.bndvi, "redEdgeNDVI": self.red_edge_ndvi, "GNDVI": self.gndvi, "GBNDVI": self.gbndvi, "GRNDVI": self.grndvi, "RBNDVI": self.rbndvi, "PNDVI": self.pndvi, "ATSAVI": self.atsavi, "BWDRVI": self.bwdrvi, "CIgreen": self.ci_green, "CIrededge": self.ci_rededge, "CI": self.ci, "CTVI": self.ctvi, "GDVI": self.gdvi, "EVI": self.evi, "GEMI": self.gemi, "GOSAVI": self.gosavi, "GSAVI": self.gsavi, "Hue": self.hue, "IVI": self.ivi, "IPVI": self.ipvi, "I": self.i, "RVI": self.rvi, "MRVI": self.mrvi, "MSAVI": self.m_savi, "NormG": self.norm_g, "NormNIR": self.norm_nir, "NormR": self.norm_r, "NGRDI": self.ngrdi, "RI": self.ri, "S": self.s, "IF": self._if, "DVI": self.dvi, "TVI": self.tvi, "NDRE": self.ndre, } try: return funcs[index]() except KeyError: print("Index not in the list!") return False def arv12(self): """ Atmospherically Resistant Vegetation Index 2 https://www.indexdatabase.de/db/i-single.php?id=396 :return: index −0.18+1.17*(self.nir−self.red)/(self.nir+self.red) """ return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red))) def ccci(self): """ Canopy Chlorophyll Content Index https://www.indexdatabase.de/db/i-single.php?id=224 :return: index """ return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def cvi(self): """ Chlorophyll vegetation index https://www.indexdatabase.de/db/i-single.php?id=391 :return: index """ return self.nir * (self.red / (self.green**2)) def gli(self): """ self.green leaf index https://www.indexdatabase.de/db/i-single.php?id=375 :return: index """ return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def ndvi(self): """ Normalized Difference self.nir/self.red Normalized Difference Vegetation Index, Calibrated NDVI - CDVI https://www.indexdatabase.de/db/i-single.php?id=58 :return: index """ return (self.nir - self.red) / (self.nir + self.red) def bndvi(self): """ Normalized Difference self.nir/self.blue self.blue-normalized difference vegetation index https://www.indexdatabase.de/db/i-single.php?id=135 :return: index """ return (self.nir - self.blue) / (self.nir + self.blue) def red_edge_ndvi(self): """ Normalized Difference self.rededge/self.red https://www.indexdatabase.de/db/i-single.php?id=235 :return: index """ return (self.redEdge - self.red) / (self.redEdge + self.red) def gndvi(self): """ Normalized Difference self.nir/self.green self.green NDVI https://www.indexdatabase.de/db/i-single.php?id=401 :return: index """ return (self.nir - self.green) / (self.nir + self.green) def gbndvi(self): """ self.green-self.blue NDVI https://www.indexdatabase.de/db/i-single.php?id=186 :return: index """ return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def grndvi(self): """ self.green-self.red NDVI https://www.indexdatabase.de/db/i-single.php?id=185 :return: index """ return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def rbndvi(self): """ self.red-self.blue NDVI https://www.indexdatabase.de/db/i-single.php?id=187 :return: index """ return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def pndvi(self): """ Pan NDVI https://www.indexdatabase.de/db/i-single.php?id=188 :return: index """ return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def atsavi(self, x=0.08, a=1.22, b=0.03): """ Adjusted transformed soil-adjusted VI https://www.indexdatabase.de/db/i-single.php?id=209 :return: index """ return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def bwdrvi(self): """ self.blue-wide dynamic range vegetation index https://www.indexdatabase.de/db/i-single.php?id=136 :return: index """ return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def ci_green(self): """ Chlorophyll Index self.green https://www.indexdatabase.de/db/i-single.php?id=128 :return: index """ return (self.nir / self.green) - 1 def ci_rededge(self): """ Chlorophyll Index self.redEdge https://www.indexdatabase.de/db/i-single.php?id=131 :return: index """ return (self.nir / self.redEdge) - 1 def ci(self): """ Coloration Index https://www.indexdatabase.de/db/i-single.php?id=11 :return: index """ return (self.red - self.blue) / self.red def ctvi(self): """ Corrected Transformed Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=244 :return: index """ ndvi = self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5))) * (abs(ndvi + 0.5) ** (1 / 2)) def gdvi(self): """ Difference self.nir/self.green self.green Difference Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=27 :return: index """ return self.nir - self.green def evi(self): """ Enhanced Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=16 :return: index """ return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def gemi(self): """ Global Environment Monitoring Index https://www.indexdatabase.de/db/i-single.php?id=25 :return: index """ n = (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.25 * n) - (self.red - 0.125) / (1 - self.red) def gosavi(self, y=0.16): """ self.green Optimized Soil Adjusted Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=29 mit Y = 0,16 :return: index """ return (self.nir - self.green) / (self.nir + self.green + y) def gsavi(self, n=0.5): """ self.green Soil Adjusted Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=31 mit N = 0,5 :return: index """ return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def hue(self): """ Hue https://www.indexdatabase.de/db/i-single.php?id=34 :return: index """ return np.arctan( ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) ) def ivi(self, a=None, b=None): """ Ideal vegetation index https://www.indexdatabase.de/db/i-single.php?id=276 b=intercept of vegetation line a=soil line slope :return: index """ return (self.nir - b) / (a * self.red) def ipvi(self): """ Infraself.red percentage vegetation index https://www.indexdatabase.de/db/i-single.php?id=35 :return: index """ return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def i(self): """ Intensity https://www.indexdatabase.de/db/i-single.php?id=36 :return: index """ return (self.red + self.green + self.blue) / 30.5 def rvi(self): """ Ratio-Vegetation-Index http://www.seos-project.eu/modules/remotesensing/remotesensing-c03-s01-p01.html :return: index """ return self.nir / self.red def mrvi(self): """ Modified Normalized Difference Vegetation Index RVI https://www.indexdatabase.de/db/i-single.php?id=275 :return: index """ return (self.rvi() - 1) / (self.rvi() + 1) def m_savi(self): """ Modified Soil Adjusted Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=44 :return: index """ return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def norm_g(self): """ Norm G https://www.indexdatabase.de/db/i-single.php?id=50 :return: index """ return self.green / (self.nir + self.red + self.green) def norm_nir(self): """ Norm self.nir https://www.indexdatabase.de/db/i-single.php?id=51 :return: index """ return self.nir / (self.nir + self.red + self.green) def norm_r(self): """ Norm R https://www.indexdatabase.de/db/i-single.php?id=52 :return: index """ return self.red / (self.nir + self.red + self.green) def ngrdi(self): """ Normalized Difference self.green/self.red Normalized self.green self.red difference index, Visible Atmospherically Resistant Indices self.green (VIself.green) https://www.indexdatabase.de/db/i-single.php?id=390 :return: index """ return (self.green - self.red) / (self.green + self.red) def ri(self): """ Normalized Difference self.red/self.green self.redness Index https://www.indexdatabase.de/db/i-single.php?id=74 :return: index """ return (self.red - self.green) / (self.red + self.green) def s(self): """ Saturation https://www.indexdatabase.de/db/i-single.php?id=77 :return: index """ max_value = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)]) min_value = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)]) return (max_value - min_value) / max_value def _if(self): """ Shape Index https://www.indexdatabase.de/db/i-single.php?id=79 :return: index """ return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def dvi(self): """ Simple Ratio self.nir/self.red Difference Vegetation Index, Vegetation Index Number (VIN) https://www.indexdatabase.de/db/i-single.php?id=12 :return: index """ return self.nir / self.red def tvi(self): """ Transformed Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=98 :return: index """ return (self.ndvi() + 0.5) ** (1 / 2) def ndre(self): return (self.nir - self.redEdge) / (self.nir + self.redEdge) """ # genering a random matrices to test this class red = np.ones((1000,1000, 1),dtype="float64") * 46787 green = np.ones((1000,1000, 1),dtype="float64") * 23487 blue = np.ones((1000,1000, 1),dtype="float64") * 14578 redEdge = np.ones((1000,1000, 1),dtype="float64") * 51045 nir = np.ones((1000,1000, 1),dtype="float64") * 52200 # Examples of how to use the class # instantiating the class cl = IndexCalculation() # instantiating the class with the values #cl = indexCalculation(red=red, green=green, blue=blue, redEdge=redEdge, nir=nir) # how set the values after instantiate the class cl, (for update the data or when don't # instantiating the class with the values) cl.setMatrices(red=red, green=green, blue=blue, redEdge=redEdge, nir=nir) # calculating the indices for the instantiated values in the class # Note: the CCCI index can be changed to any index implemented in the class. indexValue_form1 = cl.calculation("CCCI", red=red, green=green, blue=blue, redEdge=redEdge, nir=nir).astype(np.float64) indexValue_form2 = cl.CCCI() # calculating the index with the values directly -- you can set just the values # preferred note: the *calculation* function performs the function *setMatrices* indexValue_form3 = cl.calculation("CCCI", red=red, green=green, blue=blue, redEdge=redEdge, nir=nir).astype(np.float64) print("Form 1: "+np.array2string(indexValue_form1, precision=20, separator=', ', floatmode='maxprec_equal')) print("Form 2: "+np.array2string(indexValue_form2, precision=20, separator=', ', floatmode='maxprec_equal')) print("Form 3: "+np.array2string(indexValue_form3, precision=20, separator=', ', floatmode='maxprec_equal')) # A list of examples results for different type of data at NDVI # float16 -> 0.31567383 #NDVI (red = 50, nir = 100) # float32 -> 0.31578946 #NDVI (red = 50, nir = 100) # float64 -> 0.3157894736842105 #NDVI (red = 50, nir = 100) # longdouble -> 0.3157894736842105 #NDVI (red = 50, nir = 100) """
# Author: João Gustavo A. Amorim # Author email: [email protected] # Coding date: jan 2019 # python/black: True # Imports import numpy as np # Class implemented to calculus the index class IndexCalculation: """ # Class Summary This algorithm consists in calculating vegetation indices, these indices can be used for precision agriculture for example (or remote sensing). There are functions to define the data and to calculate the implemented indices. # Vegetation index https://en.wikipedia.org/wiki/Vegetation_Index A Vegetation Index (VI) is a spectral transformation of two or more bands designed to enhance the contribution of vegetation properties and allow reliable spatial and temporal inter-comparisons of terrestrial photosynthetic activity and canopy structural variations # Information about channels (Wavelength range for each) * nir - near-infrared https://www.malvernpanalytical.com/br/products/technology/near-infrared-spectroscopy Wavelength Range 700 nm to 2500 nm * Red Edge https://en.wikipedia.org/wiki/Red_edge Wavelength Range 680 nm to 730 nm * red https://en.wikipedia.org/wiki/Color Wavelength Range 635 nm to 700 nm * blue https://en.wikipedia.org/wiki/Color Wavelength Range 450 nm to 490 nm * green https://en.wikipedia.org/wiki/Color Wavelength Range 520 nm to 560 nm # Implemented index list #"abbreviationOfIndexName" -- list of channels used #"ARVI2" -- red, nir #"CCCI" -- red, redEdge, nir #"CVI" -- red, green, nir #"GLI" -- red, green, blue #"NDVI" -- red, nir #"BNDVI" -- blue, nir #"redEdgeNDVI" -- red, redEdge #"GNDVI" -- green, nir #"GBNDVI" -- green, blue, nir #"GRNDVI" -- red, green, nir #"RBNDVI" -- red, blue, nir #"PNDVI" -- red, green, blue, nir #"ATSAVI" -- red, nir #"BWDRVI" -- blue, nir #"CIgreen" -- green, nir #"CIrededge" -- redEdge, nir #"CI" -- red, blue #"CTVI" -- red, nir #"GDVI" -- green, nir #"EVI" -- red, blue, nir #"GEMI" -- red, nir #"GOSAVI" -- green, nir #"GSAVI" -- green, nir #"Hue" -- red, green, blue #"IVI" -- red, nir #"IPVI" -- red, nir #"I" -- red, green, blue #"RVI" -- red, nir #"MRVI" -- red, nir #"MSAVI" -- red, nir #"NormG" -- red, green, nir #"NormNIR" -- red, green, nir #"NormR" -- red, green, nir #"NGRDI" -- red, green #"RI" -- red, green #"S" -- red, green, blue #"IF" -- red, green, blue #"DVI" -- red, nir #"TVI" -- red, nir #"NDRE" -- redEdge, nir #list of all index implemented #allIndex = ["ARVI2", "CCCI", "CVI", "GLI", "NDVI", "BNDVI", "redEdgeNDVI", "GNDVI", "GBNDVI", "GRNDVI", "RBNDVI", "PNDVI", "ATSAVI", "BWDRVI", "CIgreen", "CIrededge", "CI", "CTVI", "GDVI", "EVI", "GEMI", "GOSAVI", "GSAVI", "Hue", "IVI", "IPVI", "I", "RVI", "MRVI", "MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI", "S", "IF", "DVI", "TVI", "NDRE"] #list of index with not blue channel #notBlueIndex = ["ARVI2", "CCCI", "CVI", "NDVI", "redEdgeNDVI", "GNDVI", "GRNDVI", "ATSAVI", "CIgreen", "CIrededge", "CTVI", "GDVI", "GEMI", "GOSAVI", "GSAVI", "IVI", "IPVI", "RVI", "MRVI", "MSAVI", "NormG", "NormNIR", "NormR", "NGRDI", "RI", "DVI", "TVI", "NDRE"] #list of index just with RGB channels #RGBIndex = ["GLI", "CI", "Hue", "I", "NGRDI", "RI", "S", "IF"] """ def __init__(self, red=None, green=None, blue=None, red_edge=None, nir=None): self.set_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir) def set_matricies(self, red=None, green=None, blue=None, red_edge=None, nir=None): if red is not None: self.red = red if green is not None: self.green = green if blue is not None: self.blue = blue if red_edge is not None: self.redEdge = red_edge if nir is not None: self.nir = nir return True def calculation( self, index="", red=None, green=None, blue=None, red_edge=None, nir=None ): """ performs the calculation of the index with the values instantiated in the class :str index: abbreviation of index name to perform """ self.set_matricies(red=red, green=green, blue=blue, red_edge=red_edge, nir=nir) funcs = { "ARVI2": self.arv12, "CCCI": self.ccci, "CVI": self.cvi, "GLI": self.gli, "NDVI": self.ndvi, "BNDVI": self.bndvi, "redEdgeNDVI": self.red_edge_ndvi, "GNDVI": self.gndvi, "GBNDVI": self.gbndvi, "GRNDVI": self.grndvi, "RBNDVI": self.rbndvi, "PNDVI": self.pndvi, "ATSAVI": self.atsavi, "BWDRVI": self.bwdrvi, "CIgreen": self.ci_green, "CIrededge": self.ci_rededge, "CI": self.ci, "CTVI": self.ctvi, "GDVI": self.gdvi, "EVI": self.evi, "GEMI": self.gemi, "GOSAVI": self.gosavi, "GSAVI": self.gsavi, "Hue": self.hue, "IVI": self.ivi, "IPVI": self.ipvi, "I": self.i, "RVI": self.rvi, "MRVI": self.mrvi, "MSAVI": self.m_savi, "NormG": self.norm_g, "NormNIR": self.norm_nir, "NormR": self.norm_r, "NGRDI": self.ngrdi, "RI": self.ri, "S": self.s, "IF": self._if, "DVI": self.dvi, "TVI": self.tvi, "NDRE": self.ndre, } try: return funcs[index]() except KeyError: print("Index not in the list!") return False def arv12(self): """ Atmospherically Resistant Vegetation Index 2 https://www.indexdatabase.de/db/i-single.php?id=396 :return: index −0.18+1.17*(self.nir−self.red)/(self.nir+self.red) """ return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red))) def ccci(self): """ Canopy Chlorophyll Content Index https://www.indexdatabase.de/db/i-single.php?id=224 :return: index """ return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def cvi(self): """ Chlorophyll vegetation index https://www.indexdatabase.de/db/i-single.php?id=391 :return: index """ return self.nir * (self.red / (self.green**2)) def gli(self): """ self.green leaf index https://www.indexdatabase.de/db/i-single.php?id=375 :return: index """ return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def ndvi(self): """ Normalized Difference self.nir/self.red Normalized Difference Vegetation Index, Calibrated NDVI - CDVI https://www.indexdatabase.de/db/i-single.php?id=58 :return: index """ return (self.nir - self.red) / (self.nir + self.red) def bndvi(self): """ Normalized Difference self.nir/self.blue self.blue-normalized difference vegetation index https://www.indexdatabase.de/db/i-single.php?id=135 :return: index """ return (self.nir - self.blue) / (self.nir + self.blue) def red_edge_ndvi(self): """ Normalized Difference self.rededge/self.red https://www.indexdatabase.de/db/i-single.php?id=235 :return: index """ return (self.redEdge - self.red) / (self.redEdge + self.red) def gndvi(self): """ Normalized Difference self.nir/self.green self.green NDVI https://www.indexdatabase.de/db/i-single.php?id=401 :return: index """ return (self.nir - self.green) / (self.nir + self.green) def gbndvi(self): """ self.green-self.blue NDVI https://www.indexdatabase.de/db/i-single.php?id=186 :return: index """ return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def grndvi(self): """ self.green-self.red NDVI https://www.indexdatabase.de/db/i-single.php?id=185 :return: index """ return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def rbndvi(self): """ self.red-self.blue NDVI https://www.indexdatabase.de/db/i-single.php?id=187 :return: index """ return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def pndvi(self): """ Pan NDVI https://www.indexdatabase.de/db/i-single.php?id=188 :return: index """ return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def atsavi(self, x=0.08, a=1.22, b=0.03): """ Adjusted transformed soil-adjusted VI https://www.indexdatabase.de/db/i-single.php?id=209 :return: index """ return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def bwdrvi(self): """ self.blue-wide dynamic range vegetation index https://www.indexdatabase.de/db/i-single.php?id=136 :return: index """ return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def ci_green(self): """ Chlorophyll Index self.green https://www.indexdatabase.de/db/i-single.php?id=128 :return: index """ return (self.nir / self.green) - 1 def ci_rededge(self): """ Chlorophyll Index self.redEdge https://www.indexdatabase.de/db/i-single.php?id=131 :return: index """ return (self.nir / self.redEdge) - 1 def ci(self): """ Coloration Index https://www.indexdatabase.de/db/i-single.php?id=11 :return: index """ return (self.red - self.blue) / self.red def ctvi(self): """ Corrected Transformed Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=244 :return: index """ ndvi = self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5))) * (abs(ndvi + 0.5) ** (1 / 2)) def gdvi(self): """ Difference self.nir/self.green self.green Difference Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=27 :return: index """ return self.nir - self.green def evi(self): """ Enhanced Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=16 :return: index """ return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def gemi(self): """ Global Environment Monitoring Index https://www.indexdatabase.de/db/i-single.php?id=25 :return: index """ n = (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.25 * n) - (self.red - 0.125) / (1 - self.red) def gosavi(self, y=0.16): """ self.green Optimized Soil Adjusted Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=29 mit Y = 0,16 :return: index """ return (self.nir - self.green) / (self.nir + self.green + y) def gsavi(self, n=0.5): """ self.green Soil Adjusted Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=31 mit N = 0,5 :return: index """ return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def hue(self): """ Hue https://www.indexdatabase.de/db/i-single.php?id=34 :return: index """ return np.arctan( ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) ) def ivi(self, a=None, b=None): """ Ideal vegetation index https://www.indexdatabase.de/db/i-single.php?id=276 b=intercept of vegetation line a=soil line slope :return: index """ return (self.nir - b) / (a * self.red) def ipvi(self): """ Infraself.red percentage vegetation index https://www.indexdatabase.de/db/i-single.php?id=35 :return: index """ return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def i(self): """ Intensity https://www.indexdatabase.de/db/i-single.php?id=36 :return: index """ return (self.red + self.green + self.blue) / 30.5 def rvi(self): """ Ratio-Vegetation-Index http://www.seos-project.eu/modules/remotesensing/remotesensing-c03-s01-p01.html :return: index """ return self.nir / self.red def mrvi(self): """ Modified Normalized Difference Vegetation Index RVI https://www.indexdatabase.de/db/i-single.php?id=275 :return: index """ return (self.rvi() - 1) / (self.rvi() + 1) def m_savi(self): """ Modified Soil Adjusted Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=44 :return: index """ return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def norm_g(self): """ Norm G https://www.indexdatabase.de/db/i-single.php?id=50 :return: index """ return self.green / (self.nir + self.red + self.green) def norm_nir(self): """ Norm self.nir https://www.indexdatabase.de/db/i-single.php?id=51 :return: index """ return self.nir / (self.nir + self.red + self.green) def norm_r(self): """ Norm R https://www.indexdatabase.de/db/i-single.php?id=52 :return: index """ return self.red / (self.nir + self.red + self.green) def ngrdi(self): """ Normalized Difference self.green/self.red Normalized self.green self.red difference index, Visible Atmospherically Resistant Indices self.green (VIself.green) https://www.indexdatabase.de/db/i-single.php?id=390 :return: index """ return (self.green - self.red) / (self.green + self.red) def ri(self): """ Normalized Difference self.red/self.green self.redness Index https://www.indexdatabase.de/db/i-single.php?id=74 :return: index """ return (self.red - self.green) / (self.red + self.green) def s(self): """ Saturation https://www.indexdatabase.de/db/i-single.php?id=77 :return: index """ max_value = np.max([np.max(self.red), np.max(self.green), np.max(self.blue)]) min_value = np.min([np.min(self.red), np.min(self.green), np.min(self.blue)]) return (max_value - min_value) / max_value def _if(self): """ Shape Index https://www.indexdatabase.de/db/i-single.php?id=79 :return: index """ return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def dvi(self): """ Simple Ratio self.nir/self.red Difference Vegetation Index, Vegetation Index Number (VIN) https://www.indexdatabase.de/db/i-single.php?id=12 :return: index """ return self.nir / self.red def tvi(self): """ Transformed Vegetation Index https://www.indexdatabase.de/db/i-single.php?id=98 :return: index """ return (self.ndvi() + 0.5) ** (1 / 2) def ndre(self): return (self.nir - self.redEdge) / (self.nir + self.redEdge) """ # genering a random matrices to test this class red = np.ones((1000,1000, 1),dtype="float64") * 46787 green = np.ones((1000,1000, 1),dtype="float64") * 23487 blue = np.ones((1000,1000, 1),dtype="float64") * 14578 redEdge = np.ones((1000,1000, 1),dtype="float64") * 51045 nir = np.ones((1000,1000, 1),dtype="float64") * 52200 # Examples of how to use the class # instantiating the class cl = IndexCalculation() # instantiating the class with the values #cl = indexCalculation(red=red, green=green, blue=blue, redEdge=redEdge, nir=nir) # how set the values after instantiate the class cl, (for update the data or when don't # instantiating the class with the values) cl.setMatrices(red=red, green=green, blue=blue, redEdge=redEdge, nir=nir) # calculating the indices for the instantiated values in the class # Note: the CCCI index can be changed to any index implemented in the class. indexValue_form1 = cl.calculation("CCCI", red=red, green=green, blue=blue, redEdge=redEdge, nir=nir).astype(np.float64) indexValue_form2 = cl.CCCI() # calculating the index with the values directly -- you can set just the values # preferred note: the *calculation* function performs the function *setMatrices* indexValue_form3 = cl.calculation("CCCI", red=red, green=green, blue=blue, redEdge=redEdge, nir=nir).astype(np.float64) print("Form 1: "+np.array2string(indexValue_form1, precision=20, separator=', ', floatmode='maxprec_equal')) print("Form 2: "+np.array2string(indexValue_form2, precision=20, separator=', ', floatmode='maxprec_equal')) print("Form 3: "+np.array2string(indexValue_form3, precision=20, separator=', ', floatmode='maxprec_equal')) # A list of examples results for different type of data at NDVI # float16 -> 0.31567383 #NDVI (red = 50, nir = 100) # float32 -> 0.31578946 #NDVI (red = 50, nir = 100) # float64 -> 0.3157894736842105 #NDVI (red = 50, nir = 100) # longdouble -> 0.3157894736842105 #NDVI (red = 50, nir = 100) """
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" author: Christian Bender date: 21.12.2017 class: XORCipher This class implements the XOR-cipher algorithm and provides some useful methods for encrypting and decrypting strings and files. Overview about methods - encrypt : list of char - decrypt : list of char - encrypt_string : str - decrypt_string : str - encrypt_file : boolean - decrypt_file : boolean """ from __future__ import annotations class XORCipher: def __init__(self, key: int = 0): """ simple constructor that receives a key or uses default key = 0 """ # private field self.__key = key def encrypt(self, content: str, key: int) -> list[str]: """ input: 'content' of type string and 'key' of type int output: encrypted string 'content' as a list of chars if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(ch) ^ key) for ch in content] def decrypt(self, content: str, key: int) -> list[str]: """ input: 'content' of type list and 'key' of type int output: decrypted string 'content' as a list of chars if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(key, int) and isinstance(content, list) key = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(ch) ^ key) for ch in content] def encrypt_string(self, content: str, key: int = 0) -> str: """ input: 'content' of type string and 'key' of type int output: encrypted string 'content' if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned ans = "" for ch in content: ans += chr(ord(ch) ^ key) return ans def decrypt_string(self, content: str, key: int = 0) -> str: """ input: 'content' of type string and 'key' of type int output: decrypted string 'content' if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned ans = "" for ch in content: ans += chr(ord(ch) ^ key) return ans def encrypt_file(self, file: str, key: int = 0) -> bool: """ input: filename (str) and a key (int) output: returns true if encrypt process was successful otherwise false if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(file, str) and isinstance(key, int) try: with open(file) as fin, open("encrypt.out", "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(line, key)) except OSError: return False return True def decrypt_file(self, file: str, key: int) -> bool: """ input: filename (str) and a key (int) output: returns true if decrypt process was successful otherwise false if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(file, str) and isinstance(key, int) try: with open(file) as fin, open("decrypt.out", "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(line, key)) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
""" author: Christian Bender date: 21.12.2017 class: XORCipher This class implements the XOR-cipher algorithm and provides some useful methods for encrypting and decrypting strings and files. Overview about methods - encrypt : list of char - decrypt : list of char - encrypt_string : str - decrypt_string : str - encrypt_file : boolean - decrypt_file : boolean """ from __future__ import annotations class XORCipher: def __init__(self, key: int = 0): """ simple constructor that receives a key or uses default key = 0 """ # private field self.__key = key def encrypt(self, content: str, key: int) -> list[str]: """ input: 'content' of type string and 'key' of type int output: encrypted string 'content' as a list of chars if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(ch) ^ key) for ch in content] def decrypt(self, content: str, key: int) -> list[str]: """ input: 'content' of type list and 'key' of type int output: decrypted string 'content' as a list of chars if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(key, int) and isinstance(content, list) key = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(ch) ^ key) for ch in content] def encrypt_string(self, content: str, key: int = 0) -> str: """ input: 'content' of type string and 'key' of type int output: encrypted string 'content' if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned ans = "" for ch in content: ans += chr(ord(ch) ^ key) return ans def decrypt_string(self, content: str, key: int = 0) -> str: """ input: 'content' of type string and 'key' of type int output: decrypted string 'content' if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(key, int) and isinstance(content, str) key = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned ans = "" for ch in content: ans += chr(ord(ch) ^ key) return ans def encrypt_file(self, file: str, key: int = 0) -> bool: """ input: filename (str) and a key (int) output: returns true if encrypt process was successful otherwise false if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(file, str) and isinstance(key, int) try: with open(file) as fin, open("encrypt.out", "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(line, key)) except OSError: return False return True def decrypt_file(self, file: str, key: int) -> bool: """ input: filename (str) and a key (int) output: returns true if decrypt process was successful otherwise false if key not passed the method uses the key by the constructor. otherwise key = 1 """ # precondition assert isinstance(file, str) and isinstance(key, int) try: with open(file) as fin, open("decrypt.out", "w+") as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(line, key)) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 4: https://projecteuler.net/problem=4 Largest palindrome product A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. References: - https://en.wikipedia.org/wiki/Palindromic_number """ def solution(n: int = 998001) -> int: """ Returns the largest palindrome made from the product of two 3-digit numbers which is less than n. >>> solution(20000) 19591 >>> solution(30000) 29992 >>> solution(40000) 39893 >>> solution(10000) Traceback (most recent call last): ... ValueError: That number is larger than our acceptable range. """ # fetches the next number for number in range(n - 1, 9999, -1): str_number = str(number) # checks whether 'str_number' is a palindrome. if str_number == str_number[::-1]: divisor = 999 # if 'number' is a product of two 3-digit numbers # then number is the answer otherwise fetch next number. while divisor != 99: if (number % divisor == 0) and (len(str(number // divisor)) == 3.0): return number divisor -= 1 raise ValueError("That number is larger than our acceptable range.") if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 4: https://projecteuler.net/problem=4 Largest palindrome product A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers. References: - https://en.wikipedia.org/wiki/Palindromic_number """ def solution(n: int = 998001) -> int: """ Returns the largest palindrome made from the product of two 3-digit numbers which is less than n. >>> solution(20000) 19591 >>> solution(30000) 29992 >>> solution(40000) 39893 >>> solution(10000) Traceback (most recent call last): ... ValueError: That number is larger than our acceptable range. """ # fetches the next number for number in range(n - 1, 9999, -1): str_number = str(number) # checks whether 'str_number' is a palindrome. if str_number == str_number[::-1]: divisor = 999 # if 'number' is a product of two 3-digit numbers # then number is the answer otherwise fetch next number. while divisor != 99: if (number % divisor == 0) and (len(str(number // divisor)) == 3.0): return number divisor -= 1 raise ValueError("That number is larger than our acceptable range.") if __name__ == "__main__": print(f"{solution() = }")
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
alphabets = [chr(i) for i in range(32, 126)] gear_one = list(range(len(alphabets))) gear_two = list(range(len(alphabets))) gear_three = list(range(len(alphabets))) reflector = list(reversed(range(len(alphabets)))) code = [] gear_one_pos = gear_two_pos = gear_three_pos = 0 def rotator(): global gear_one_pos global gear_two_pos global gear_three_pos i = gear_one[0] gear_one.append(i) del gear_one[0] gear_one_pos += 1 if gear_one_pos % int(len(alphabets)) == 0: i = gear_two[0] gear_two.append(i) del gear_two[0] gear_two_pos += 1 if gear_two_pos % int(len(alphabets)) == 0: i = gear_three[0] gear_three.append(i) del gear_three[0] gear_three_pos += 1 def engine(input_character): target = alphabets.index(input_character) target = gear_one[target] target = gear_two[target] target = gear_three[target] target = reflector[target] target = gear_three.index(target) target = gear_two.index(target) target = gear_one.index(target) code.append(alphabets[target]) rotator() if __name__ == "__main__": decode = list(input("Type your message:\n")) while True: try: token = int(input("Please set token:(must be only digits)\n")) break except Exception as error: print(error) for _ in range(token): rotator() for j in decode: engine(j) print("\n" + "".join(code)) print( f"\nYour Token is {token} please write it down.\nIf you want to decode " "this message again you should input same digits as token!" )
alphabets = [chr(i) for i in range(32, 126)] gear_one = list(range(len(alphabets))) gear_two = list(range(len(alphabets))) gear_three = list(range(len(alphabets))) reflector = list(reversed(range(len(alphabets)))) code = [] gear_one_pos = gear_two_pos = gear_three_pos = 0 def rotator(): global gear_one_pos global gear_two_pos global gear_three_pos i = gear_one[0] gear_one.append(i) del gear_one[0] gear_one_pos += 1 if gear_one_pos % int(len(alphabets)) == 0: i = gear_two[0] gear_two.append(i) del gear_two[0] gear_two_pos += 1 if gear_two_pos % int(len(alphabets)) == 0: i = gear_three[0] gear_three.append(i) del gear_three[0] gear_three_pos += 1 def engine(input_character): target = alphabets.index(input_character) target = gear_one[target] target = gear_two[target] target = gear_three[target] target = reflector[target] target = gear_three.index(target) target = gear_two.index(target) target = gear_one.index(target) code.append(alphabets[target]) rotator() if __name__ == "__main__": decode = list(input("Type your message:\n")) while True: try: token = int(input("Please set token:(must be only digits)\n")) break except Exception as error: print(error) for _ in range(token): rotator() for j in decode: engine(j) print("\n" + "".join(code)) print( f"\nYour Token is {token} please write it down.\nIf you want to decode " "this message again you should input same digits as token!" )
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
"""Implementation of Basic Math in Python.""" import math def prime_factors(n: int) -> list: """Find Prime Factors. >>> prime_factors(100) [2, 2, 5, 5] >>> prime_factors(0) Traceback (most recent call last): ... ValueError: Only positive integers have prime factors >>> prime_factors(-10) Traceback (most recent call last): ... ValueError: Only positive integers have prime factors """ if n <= 0: raise ValueError("Only positive integers have prime factors") pf = [] while n % 2 == 0: pf.append(2) n = int(n / 2) for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: pf.append(i) n = int(n / i) if n > 2: pf.append(n) return pf def number_of_divisors(n: int) -> int: """Calculate Number of Divisors of an Integer. >>> number_of_divisors(100) 9 >>> number_of_divisors(0) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted >>> number_of_divisors(-10) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted """ if n <= 0: raise ValueError("Only positive numbers are accepted") div = 1 temp = 1 while n % 2 == 0: temp += 1 n = int(n / 2) div *= temp for i in range(3, int(math.sqrt(n)) + 1, 2): temp = 1 while n % i == 0: temp += 1 n = int(n / i) div *= temp if n > 1: div *= 2 return div def sum_of_divisors(n: int) -> int: """Calculate Sum of Divisors. >>> sum_of_divisors(100) 217 >>> sum_of_divisors(0) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted >>> sum_of_divisors(-10) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted """ if n <= 0: raise ValueError("Only positive numbers are accepted") s = 1 temp = 1 while n % 2 == 0: temp += 1 n = int(n / 2) if temp > 1: s *= (2**temp - 1) / (2 - 1) for i in range(3, int(math.sqrt(n)) + 1, 2): temp = 1 while n % i == 0: temp += 1 n = int(n / i) if temp > 1: s *= (i**temp - 1) / (i - 1) return int(s) def euler_phi(n: int) -> int: """Calculate Euler's Phi Function. >>> euler_phi(100) 40 """ s = n for x in set(prime_factors(n)): s *= (x - 1) / x return int(s) if __name__ == "__main__": import doctest doctest.testmod()
"""Implementation of Basic Math in Python.""" import math def prime_factors(n: int) -> list: """Find Prime Factors. >>> prime_factors(100) [2, 2, 5, 5] >>> prime_factors(0) Traceback (most recent call last): ... ValueError: Only positive integers have prime factors >>> prime_factors(-10) Traceback (most recent call last): ... ValueError: Only positive integers have prime factors """ if n <= 0: raise ValueError("Only positive integers have prime factors") pf = [] while n % 2 == 0: pf.append(2) n = int(n / 2) for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: pf.append(i) n = int(n / i) if n > 2: pf.append(n) return pf def number_of_divisors(n: int) -> int: """Calculate Number of Divisors of an Integer. >>> number_of_divisors(100) 9 >>> number_of_divisors(0) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted >>> number_of_divisors(-10) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted """ if n <= 0: raise ValueError("Only positive numbers are accepted") div = 1 temp = 1 while n % 2 == 0: temp += 1 n = int(n / 2) div *= temp for i in range(3, int(math.sqrt(n)) + 1, 2): temp = 1 while n % i == 0: temp += 1 n = int(n / i) div *= temp if n > 1: div *= 2 return div def sum_of_divisors(n: int) -> int: """Calculate Sum of Divisors. >>> sum_of_divisors(100) 217 >>> sum_of_divisors(0) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted >>> sum_of_divisors(-10) Traceback (most recent call last): ... ValueError: Only positive numbers are accepted """ if n <= 0: raise ValueError("Only positive numbers are accepted") s = 1 temp = 1 while n % 2 == 0: temp += 1 n = int(n / 2) if temp > 1: s *= (2**temp - 1) / (2 - 1) for i in range(3, int(math.sqrt(n)) + 1, 2): temp = 1 while n % i == 0: temp += 1 n = int(n / i) if temp > 1: s *= (i**temp - 1) / (i - 1) return int(s) def euler_phi(n: int) -> int: """Calculate Euler's Phi Function. >>> euler_phi(100) 40 """ s = n for x in set(prime_factors(n)): s *= (x - 1) / x return int(s) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Number letter counts Problem 17: https://projecteuler.net/problem=17 If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance withBritish usage. """ def solution(n: int = 1000) -> int: """Returns the number of letters used to write all numbers from 1 to n. where n is lower or equals to 1000. >>> solution(1000) 21124 >>> solution(5) 19 """ # number of letters in zero, one, two, ..., nineteen (0 for zero since it's # never said aloud) ones_counts = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8] # number of letters in twenty, thirty, ..., ninety (0 for numbers less than # 20 due to inconsistency in teens) tens_counts = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6] count = 0 for i in range(1, n + 1): if i < 1000: if i >= 100: # add number of letters for "n hundred" count += ones_counts[i // 100] + 7 if i % 100 != 0: # add number of letters for "and" if number is not multiple # of 100 count += 3 if 0 < i % 100 < 20: # add number of letters for one, two, three, ..., nineteen # (could be combined with below if not for inconsistency in # teens) count += ones_counts[i % 100] else: # add number of letters for twenty, twenty one, ..., ninety # nine count += ones_counts[i % 10] count += tens_counts[(i % 100 - i % 10) // 10] else: count += ones_counts[i // 1000] + 8 return count if __name__ == "__main__": print(solution(int(input().strip())))
""" Number letter counts Problem 17: https://projecteuler.net/problem=17 If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance withBritish usage. """ def solution(n: int = 1000) -> int: """Returns the number of letters used to write all numbers from 1 to n. where n is lower or equals to 1000. >>> solution(1000) 21124 >>> solution(5) 19 """ # number of letters in zero, one, two, ..., nineteen (0 for zero since it's # never said aloud) ones_counts = [0, 3, 3, 5, 4, 4, 3, 5, 5, 4, 3, 6, 6, 8, 8, 7, 7, 9, 8, 8] # number of letters in twenty, thirty, ..., ninety (0 for numbers less than # 20 due to inconsistency in teens) tens_counts = [0, 0, 6, 6, 5, 5, 5, 7, 6, 6] count = 0 for i in range(1, n + 1): if i < 1000: if i >= 100: # add number of letters for "n hundred" count += ones_counts[i // 100] + 7 if i % 100 != 0: # add number of letters for "and" if number is not multiple # of 100 count += 3 if 0 < i % 100 < 20: # add number of letters for one, two, three, ..., nineteen # (could be combined with below if not for inconsistency in # teens) count += ones_counts[i % 100] else: # add number of letters for twenty, twenty one, ..., ninety # nine count += ones_counts[i % 10] count += tens_counts[(i % 100 - i % 10) // 10] else: count += ones_counts[i // 1000] + 8 return count if __name__ == "__main__": print(solution(int(input().strip())))
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 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
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
class BinaryHeap: """ A max-heap implementation in Python >>> binary_heap = BinaryHeap() >>> binary_heap.insert(6) >>> binary_heap.insert(10) >>> binary_heap.insert(15) >>> binary_heap.insert(12) >>> binary_heap.pop() 15 >>> binary_heap.pop() 12 >>> binary_heap.get_list [10, 6] >>> len(binary_heap) 2 """ def __init__(self): self.__heap = [0] self.__size = 0 def __swap_up(self, i: int) -> None: """Swap the element up""" temporary = self.__heap[i] while i // 2 > 0: if self.__heap[i] > self.__heap[i // 2]: self.__heap[i] = self.__heap[i // 2] self.__heap[i // 2] = temporary i //= 2 def insert(self, value: int) -> None: """Insert new element""" self.__heap.append(value) self.__size += 1 self.__swap_up(self.__size) def __swap_down(self, i: int) -> None: """Swap the element down""" while self.__size >= 2 * i: if 2 * i + 1 > self.__size: bigger_child = 2 * i else: if self.__heap[2 * i] > self.__heap[2 * i + 1]: bigger_child = 2 * i else: bigger_child = 2 * i + 1 temporary = self.__heap[i] if self.__heap[i] < self.__heap[bigger_child]: self.__heap[i] = self.__heap[bigger_child] self.__heap[bigger_child] = temporary i = bigger_child def pop(self) -> int: """Pop the root element""" max_value = self.__heap[1] self.__heap[1] = self.__heap[self.__size] self.__size -= 1 self.__heap.pop() self.__swap_down(1) return max_value @property def get_list(self): return self.__heap[1:] def __len__(self): """Length of the array""" return self.__size if __name__ == "__main__": import doctest doctest.testmod() # create an instance of BinaryHeap binary_heap = BinaryHeap() binary_heap.insert(6) binary_heap.insert(10) binary_heap.insert(15) binary_heap.insert(12) # pop root(max-values because it is max heap) print(binary_heap.pop()) # 15 print(binary_heap.pop()) # 12 # get the list and size after operations print(binary_heap.get_list) print(len(binary_heap))
class BinaryHeap: """ A max-heap implementation in Python >>> binary_heap = BinaryHeap() >>> binary_heap.insert(6) >>> binary_heap.insert(10) >>> binary_heap.insert(15) >>> binary_heap.insert(12) >>> binary_heap.pop() 15 >>> binary_heap.pop() 12 >>> binary_heap.get_list [10, 6] >>> len(binary_heap) 2 """ def __init__(self): self.__heap = [0] self.__size = 0 def __swap_up(self, i: int) -> None: """Swap the element up""" temporary = self.__heap[i] while i // 2 > 0: if self.__heap[i] > self.__heap[i // 2]: self.__heap[i] = self.__heap[i // 2] self.__heap[i // 2] = temporary i //= 2 def insert(self, value: int) -> None: """Insert new element""" self.__heap.append(value) self.__size += 1 self.__swap_up(self.__size) def __swap_down(self, i: int) -> None: """Swap the element down""" while self.__size >= 2 * i: if 2 * i + 1 > self.__size: bigger_child = 2 * i else: if self.__heap[2 * i] > self.__heap[2 * i + 1]: bigger_child = 2 * i else: bigger_child = 2 * i + 1 temporary = self.__heap[i] if self.__heap[i] < self.__heap[bigger_child]: self.__heap[i] = self.__heap[bigger_child] self.__heap[bigger_child] = temporary i = bigger_child def pop(self) -> int: """Pop the root element""" max_value = self.__heap[1] self.__heap[1] = self.__heap[self.__size] self.__size -= 1 self.__heap.pop() self.__swap_down(1) return max_value @property def get_list(self): return self.__heap[1:] def __len__(self): """Length of the array""" return self.__size if __name__ == "__main__": import doctest doctest.testmod() # create an instance of BinaryHeap binary_heap = BinaryHeap() binary_heap.insert(6) binary_heap.insert(10) binary_heap.insert(15) binary_heap.insert(12) # pop root(max-values because it is max heap) print(binary_heap.pop()) # 15 print(binary_heap.pop()) # 12 # get the list and size after operations print(binary_heap.get_list) print(len(binary_heap))
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" A naive recursive implementation of 0-1 Knapsack Problem https://en.wikipedia.org/wiki/Knapsack_problem """ from __future__ import annotations def knapsack(capacity: int, weights: list[int], values: list[int], counter: int) -> int: """ Returns the maximum value that can be put in a knapsack of a capacity cap, whereby each weight w has a specific value val. >>> cap = 50 >>> val = [60, 100, 120] >>> w = [10, 20, 30] >>> c = len(val) >>> knapsack(cap, w, val, c) 220 The result is 220 cause the values of 100 and 120 got the weight of 50 which is the limit of the capacity. """ # Base Case if counter == 0 or capacity == 0: return 0 # If weight of the nth item is more than Knapsack of capacity, # then this item cannot be included in the optimal solution, # else return the maximum of two cases: # (1) nth item included # (2) not included if weights[counter - 1] > capacity: return knapsack(capacity, weights, values, counter - 1) else: left_capacity = capacity - weights[counter - 1] new_value_included = values[counter - 1] + knapsack( left_capacity, weights, values, counter - 1 ) without_new_value = knapsack(capacity, weights, values, counter - 1) return max(new_value_included, without_new_value) if __name__ == "__main__": import doctest doctest.testmod()
""" A naive recursive implementation of 0-1 Knapsack Problem https://en.wikipedia.org/wiki/Knapsack_problem """ from __future__ import annotations def knapsack(capacity: int, weights: list[int], values: list[int], counter: int) -> int: """ Returns the maximum value that can be put in a knapsack of a capacity cap, whereby each weight w has a specific value val. >>> cap = 50 >>> val = [60, 100, 120] >>> w = [10, 20, 30] >>> c = len(val) >>> knapsack(cap, w, val, c) 220 The result is 220 cause the values of 100 and 120 got the weight of 50 which is the limit of the capacity. """ # Base Case if counter == 0 or capacity == 0: return 0 # If weight of the nth item is more than Knapsack of capacity, # then this item cannot be included in the optimal solution, # else return the maximum of two cases: # (1) nth item included # (2) not included if weights[counter - 1] > capacity: return knapsack(capacity, weights, values, counter - 1) else: left_capacity = capacity - weights[counter - 1] new_value_included = values[counter - 1] + knapsack( left_capacity, weights, values, counter - 1 ) without_new_value = knapsack(capacity, weights, values, counter - 1) return max(new_value_included, without_new_value) if __name__ == "__main__": import doctest doctest.testmod()
-1
TheAlgorithms/Python
8,892
Fix ruff rules ISC flake8-implicit-str-concat
### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
cclauss
"2023-07-26T06:58:55Z"
"2023-07-28T16:53:09Z"
b77e6adf3abba674eb83ab7c0182bd6c89c08891
dbaff345724040b270b3097cb02759f36ce0ef46
Fix ruff rules ISC flake8-implicit-str-concat. ### Describe your change: * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [x] This pull request is all my own work -- I have not plagiarized. * [x] I know pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# git ls-files --others --exclude-from=.git/info/exclude # Lines that start with '#' are comments. # For a project mostly in C, the following would be a good set of # exclude patterns (uncomment them if you want to use them): # *.[oa] # *~
# git ls-files --others --exclude-from=.git/info/exclude # Lines that start with '#' are comments. # For a project mostly in C, the following would be a good set of # exclude patterns (uncomment them if you want to use them): # *.[oa] # *~
-1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: check-executables-have-shebangs - id: check-toml - id: check-yaml - id: end-of-file-fixer types: [python] - id: trailing-whitespace - id: requirements-txt-fixer - repo: https://github.com/MarcoGorelli/auto-walrus rev: v0.2.2 hooks: - id: auto-walrus - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.0.278 hooks: - id: ruff - repo: https://github.com/psf/black rev: 23.7.0 hooks: - id: black - repo: https://github.com/codespell-project/codespell rev: v2.2.5 hooks: - id: codespell additional_dependencies: - tomli - repo: https://github.com/tox-dev/pyproject-fmt rev: "0.13.0" hooks: - id: pyproject-fmt - repo: local hooks: - id: validate-filenames name: Validate filenames entry: ./scripts/validate_filenames.py language: script pass_filenames: false - repo: https://github.com/abravalheri/validate-pyproject rev: v0.13 hooks: - id: validate-pyproject - repo: https://github.com/pre-commit/mirrors-mypy rev: v1.4.1 hooks: - id: mypy args: - --ignore-missing-imports - --install-types # See mirrors-mypy README.md - --non-interactive additional_dependencies: [types-requests]
repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: check-executables-have-shebangs - id: check-toml - id: check-yaml - id: end-of-file-fixer types: [python] - id: trailing-whitespace - id: requirements-txt-fixer - repo: https://github.com/MarcoGorelli/auto-walrus rev: v0.2.2 hooks: - id: auto-walrus - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.0.280 hooks: - id: ruff - repo: https://github.com/psf/black rev: 23.7.0 hooks: - id: black - repo: https://github.com/codespell-project/codespell rev: v2.2.5 hooks: - id: codespell additional_dependencies: - tomli - repo: https://github.com/tox-dev/pyproject-fmt rev: "0.13.0" hooks: - id: pyproject-fmt - repo: local hooks: - id: validate-filenames name: Validate filenames entry: ./scripts/validate_filenames.py language: script pass_filenames: false - repo: https://github.com/abravalheri/validate-pyproject rev: v0.13 hooks: - id: validate-pyproject - repo: https://github.com/pre-commit/mirrors-mypy rev: v1.4.1 hooks: - id: mypy args: - --ignore-missing-imports - --install-types # See mirrors-mypy README.md - --non-interactive additional_dependencies: [types-requests]
1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
"""Conway's Game Of Life, Author Anurag Kumar(mailto:[email protected]) Requirements: - numpy - random - time - matplotlib Python: - 3.5 Usage: - $python3 game_o_life <canvas_size:int> Game-Of-Life Rules: 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by over-population. 4. Any dead cell with exactly three live neighbours be- comes a live cell, as if by reproduction. """ import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap usage_doc = "Usage of script: script_name <size_of_canvas:int>" choice = [0] * 100 + [1] * 10 random.shuffle(choice) def create_canvas(size: int) -> list[list[bool]]: canvas = [[False for i in range(size)] for j in range(size)] return canvas def seed(canvas: list[list[bool]]) -> None: for i, row in enumerate(canvas): for j, _ in enumerate(row): canvas[i][j] = bool(random.getrandbits(1)) def run(canvas: list[list[bool]]) -> list[list[bool]]: """This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- canvas : canvas of population to run the rules on. @returns: -- None """ current_canvas = np.array(canvas) next_gen_canvas = np.array(create_canvas(current_canvas.shape[0])) for r, row in enumerate(current_canvas): for c, pt in enumerate(row): next_gen_canvas[r][c] = __judge_point( pt, current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) current_canvas = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. return_canvas: list[list[bool]] = current_canvas.tolist() return return_canvas def __judge_point(pt: bool, neighbours: list[list[bool]]) -> bool: dead = 0 alive = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. state = pt if pt: if alive < 2: state = False elif alive == 2 or alive == 3: state = True elif alive > 3: state = False else: if alive == 3: state = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) canvas_size = int(sys.argv[1]) # main working structure of this module. c = create_canvas(canvas_size) seed(c) fig, ax = plt.subplots() fig.show() cmap = ListedColormap(["w", "k"]) try: while True: c = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
"""Conway's Game Of Life, Author Anurag Kumar(mailto:[email protected]) Requirements: - numpy - random - time - matplotlib Python: - 3.5 Usage: - $python3 game_o_life <canvas_size:int> Game-Of-Life Rules: 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by over-population. 4. Any dead cell with exactly three live neighbours be- comes a live cell, as if by reproduction. """ import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap usage_doc = "Usage of script: script_name <size_of_canvas:int>" choice = [0] * 100 + [1] * 10 random.shuffle(choice) def create_canvas(size: int) -> list[list[bool]]: canvas = [[False for i in range(size)] for j in range(size)] return canvas def seed(canvas: list[list[bool]]) -> None: for i, row in enumerate(canvas): for j, _ in enumerate(row): canvas[i][j] = bool(random.getrandbits(1)) def run(canvas: list[list[bool]]) -> list[list[bool]]: """This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- canvas : canvas of population to run the rules on. @returns: -- None """ current_canvas = np.array(canvas) next_gen_canvas = np.array(create_canvas(current_canvas.shape[0])) for r, row in enumerate(current_canvas): for c, pt in enumerate(row): next_gen_canvas[r][c] = __judge_point( pt, current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) current_canvas = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. return_canvas: list[list[bool]] = current_canvas.tolist() return return_canvas def __judge_point(pt: bool, neighbours: list[list[bool]]) -> bool: dead = 0 alive = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. state = pt if pt: if alive < 2: state = False elif alive in {2, 3}: state = True elif alive > 3: state = False else: if alive == 3: state = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) canvas_size = int(sys.argv[1]) # main working structure of this module. c = create_canvas(canvas_size) seed(c) fig, ax = plt.subplots() fig.show() cmap = ListedColormap(["w", "k"]) try: while True: c = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" psf/black : true ruff : passed """ from __future__ import annotations from collections.abc import Iterator class RedBlackTree: """ A Red-Black tree, which is a self-balancing BST (binary search tree). This tree has similar performance to AVL trees, but the balancing is less strict, so it will perform faster for writing/deleting nodes and slower for reading in the average case, though, because they're both balanced binary search trees, both will get the same asymptotic performance. To read more about them, https://en.wikipedia.org/wiki/Red–black_tree Unless otherwise specified, all asymptotic runtimes are specified in terms of the size of the tree. """ def __init__( self, label: int | None = None, color: int = 0, parent: RedBlackTree | None = None, left: RedBlackTree | None = None, right: RedBlackTree | None = None, ) -> None: """Initialize a new Red-Black Tree node with the given values: label: The value associated with this node color: 0 if black, 1 if red parent: The parent to this node left: This node's left child right: This node's right child """ self.label = label self.parent = parent self.left = left self.right = right self.color = color # Here are functions which are specific to red-black trees def rotate_left(self) -> RedBlackTree: """Rotate the subtree rooted at this node to the left and returns the new root to this subtree. Performing one rotation can be done in O(1). """ parent = self.parent right = self.right if right is None: return self self.right = right.left if self.right: self.right.parent = self self.parent = right right.left = self if parent is not None: if parent.left == self: parent.left = right else: parent.right = right right.parent = parent return right def rotate_right(self) -> RedBlackTree: """Rotate the subtree rooted at this node to the right and returns the new root to this subtree. Performing one rotation can be done in O(1). """ if self.left is None: return self parent = self.parent left = self.left self.left = left.right if self.left: self.left.parent = self self.parent = left left.right = self if parent is not None: if parent.right is self: parent.right = left else: parent.left = left left.parent = parent return left def insert(self, label: int) -> RedBlackTree: """Inserts label into the subtree rooted at self, performs any rotations necessary to maintain balance, and then returns the new root to this subtree (likely self). This is guaranteed to run in O(log(n)) time. """ if self.label is None: # Only possible with an empty tree self.label = label return self if self.label == label: return self elif self.label > label: if self.left: self.left.insert(label) else: self.left = RedBlackTree(label, 1, self) self.left._insert_repair() else: if self.right: self.right.insert(label) else: self.right = RedBlackTree(label, 1, self) self.right._insert_repair() return self.parent or self def _insert_repair(self) -> None: """Repair the coloring from inserting into a tree.""" if self.parent is None: # This node is the root, so it just needs to be black self.color = 0 elif color(self.parent) == 0: # If the parent is black, then it just needs to be red self.color = 1 else: uncle = self.parent.sibling if color(uncle) == 0: if self.is_left() and self.parent.is_right(): self.parent.rotate_right() if self.right: self.right._insert_repair() elif self.is_right() and self.parent.is_left(): self.parent.rotate_left() if self.left: self.left._insert_repair() elif self.is_left(): if self.grandparent: self.grandparent.rotate_right() self.parent.color = 0 if self.parent.right: self.parent.right.color = 1 else: if self.grandparent: self.grandparent.rotate_left() self.parent.color = 0 if self.parent.left: self.parent.left.color = 1 else: self.parent.color = 0 if uncle and self.grandparent: uncle.color = 0 self.grandparent.color = 1 self.grandparent._insert_repair() def remove(self, label: int) -> RedBlackTree: """Remove label from this tree.""" if self.label == label: if self.left and self.right: # It's easier to balance a node with at most one child, # so we replace this node with the greatest one less than # it and remove that. value = self.left.get_max() if value is not None: self.label = value self.left.remove(value) else: # This node has at most one non-None child, so we don't # need to replace child = self.left or self.right if self.color == 1: # This node is red, and its child is black # The only way this happens to a node with one child # is if both children are None leaves. # We can just remove this node and call it a day. if self.parent: if self.is_left(): self.parent.left = None else: self.parent.right = None else: # The node is black if child is None: # This node and its child are black if self.parent is None: # The tree is now empty return RedBlackTree(None) else: self._remove_repair() if self.is_left(): self.parent.left = None else: self.parent.right = None self.parent = None else: # This node is black and its child is red # Move the child node here and make it black self.label = child.label self.left = child.left self.right = child.right if self.left: self.left.parent = self if self.right: self.right.parent = self elif self.label is not None and self.label > label: if self.left: self.left.remove(label) else: if self.right: self.right.remove(label) return self.parent or self def _remove_repair(self) -> None: """Repair the coloring of the tree that may have been messed up.""" if ( self.parent is None or self.sibling is None or self.parent.sibling is None or self.grandparent is None ): return if color(self.sibling) == 1: self.sibling.color = 0 self.parent.color = 1 if self.is_left(): self.parent.rotate_left() else: self.parent.rotate_right() if ( color(self.parent) == 0 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent._remove_repair() return if ( color(self.parent) == 1 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent.color = 0 return if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 0 and color(self.sibling.left) == 1 ): self.sibling.rotate_right() self.sibling.color = 0 if self.sibling.right: self.sibling.right.color = 1 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.right) == 1 and color(self.sibling.left) == 0 ): self.sibling.rotate_left() self.sibling.color = 0 if self.sibling.left: self.sibling.left.color = 1 if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 1 ): self.parent.rotate_left() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.left) == 1 ): self.parent.rotate_right() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 def check_color_properties(self) -> bool: """Check the coloring of the tree, and return True iff the tree is colored in a way which matches these five properties: (wording stolen from wikipedia article) 1. Each node is either red or black. 2. The root node is black. 3. All leaves are black. 4. If a node is red, then both its children are black. 5. Every path from any node to all of its descendent NIL nodes has the same number of black nodes. This function runs in O(n) time, because properties 4 and 5 take that long to check. """ # I assume property 1 to hold because there is nothing that can # make the color be anything other than 0 or 1. # Property 2 if self.color: # The root was red print("Property 2") return False # Property 3 does not need to be checked, because None is assumed # to be black and is all the leaves. # Property 4 if not self.check_coloring(): print("Property 4") return False # Property 5 if self.black_height() is None: print("Property 5") return False # All properties were met return True def check_coloring(self) -> bool: """A helper function to recursively check Property 4 of a Red-Black Tree. See check_color_properties for more info. """ if self.color == 1 and 1 in (color(self.left), color(self.right)): return False if self.left and not self.left.check_coloring(): return False if self.right and not self.right.check_coloring(): return False return True def black_height(self) -> int | None: """Returns the number of black nodes from this node to the leaves of the tree, or None if there isn't one such value (the tree is color incorrectly). """ if self is None or self.left is None or self.right is None: # If we're already at a leaf, there is no path return 1 left = RedBlackTree.black_height(self.left) right = RedBlackTree.black_height(self.right) if left is None or right is None: # There are issues with coloring below children nodes return None if left != right: # The two children have unequal depths return None # Return the black depth of children, plus one if this node is # black return left + (1 - self.color) # Here are functions which are general to all binary search trees def __contains__(self, label: int) -> bool: """Search through the tree for label, returning True iff it is found somewhere in the tree. Guaranteed to run in O(log(n)) time. """ return self.search(label) is not None def search(self, label: int) -> RedBlackTree | None: """Search through the tree for label, returning its node if it's found, and None otherwise. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self elif self.label is not None and label > self.label: if self.right is None: return None else: return self.right.search(label) else: if self.left is None: return None else: return self.left.search(label) def floor(self, label: int) -> int | None: """Returns the largest element in this tree which is at most label. This method is guaranteed to run in O(log(n)) time.""" if self.label == label: return self.label elif self.label is not None and self.label > label: if self.left: return self.left.floor(label) else: return None else: if self.right: attempt = self.right.floor(label) if attempt is not None: return attempt return self.label def ceil(self, label: int) -> int | None: """Returns the smallest element in this tree which is at least label. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self.label elif self.label is not None and self.label < label: if self.right: return self.right.ceil(label) else: return None else: if self.left: attempt = self.left.ceil(label) if attempt is not None: return attempt return self.label def get_max(self) -> int | None: """Returns the largest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.right: # Go as far right as possible return self.right.get_max() else: return self.label def get_min(self) -> int | None: """Returns the smallest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.left: # Go as far left as possible return self.left.get_min() else: return self.label @property def grandparent(self) -> RedBlackTree | None: """Get the current node's grandparent, or None if it doesn't exist.""" if self.parent is None: return None else: return self.parent.parent @property def sibling(self) -> RedBlackTree | None: """Get the current node's sibling, or None if it doesn't exist.""" if self.parent is None: return None elif self.parent.left is self: return self.parent.right else: return self.parent.left def is_left(self) -> bool: """Returns true iff this node is the left child of its parent.""" if self.parent is None: return False return self.parent.left is self.parent.left is self def is_right(self) -> bool: """Returns true iff this node is the right child of its parent.""" if self.parent is None: return False return self.parent.right is self def __bool__(self) -> bool: return True def __len__(self) -> int: """ Return the number of nodes in this tree. """ ln = 1 if self.left: ln += len(self.left) if self.right: ln += len(self.right) return ln def preorder_traverse(self) -> Iterator[int | None]: yield self.label if self.left: yield from self.left.preorder_traverse() if self.right: yield from self.right.preorder_traverse() def inorder_traverse(self) -> Iterator[int | None]: if self.left: yield from self.left.inorder_traverse() yield self.label if self.right: yield from self.right.inorder_traverse() def postorder_traverse(self) -> Iterator[int | None]: if self.left: yield from self.left.postorder_traverse() if self.right: yield from self.right.postorder_traverse() yield self.label def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return f"'{self.label} {(self.color and 'red') or 'blk'}'" return pformat( { f"{self.label} {(self.color and 'red') or 'blk'}": ( self.left, self.right, ) }, indent=1, ) def __eq__(self, other: object) -> bool: """Test if two trees are equal.""" if not isinstance(other, RedBlackTree): return NotImplemented if self.label == other.label: return self.left == other.left and self.right == other.right else: return False def color(node: RedBlackTree | None) -> int: """Returns the color of a node, allowing for None leaves.""" if node is None: return 0 else: return node.color """ Code for testing the various functions of the red-black tree. """ def test_rotations() -> bool: """Test that the rotate_left and rotate_right functions work.""" # Make a tree to test on tree = RedBlackTree(0) tree.left = RedBlackTree(-10, parent=tree) tree.right = RedBlackTree(10, parent=tree) tree.left.left = RedBlackTree(-20, parent=tree.left) tree.left.right = RedBlackTree(-5, parent=tree.left) tree.right.left = RedBlackTree(5, parent=tree.right) tree.right.right = RedBlackTree(20, parent=tree.right) # Make the right rotation left_rot = RedBlackTree(10) left_rot.left = RedBlackTree(0, parent=left_rot) left_rot.left.left = RedBlackTree(-10, parent=left_rot.left) left_rot.left.right = RedBlackTree(5, parent=left_rot.left) left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left) left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left) left_rot.right = RedBlackTree(20, parent=left_rot) tree = tree.rotate_left() if tree != left_rot: return False tree = tree.rotate_right() tree = tree.rotate_right() # Make the left rotation right_rot = RedBlackTree(-10) right_rot.left = RedBlackTree(-20, parent=right_rot) right_rot.right = RedBlackTree(0, parent=right_rot) right_rot.right.left = RedBlackTree(-5, parent=right_rot.right) right_rot.right.right = RedBlackTree(10, parent=right_rot.right) right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right) right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right) if tree != right_rot: return False return True def test_insertion_speed() -> bool: """Test that the tree balances inserts to O(log(n)) by doing a lot of them. """ tree = RedBlackTree(-1) for i in range(300000): tree = tree.insert(i) return True def test_insert() -> bool: """Test the insert() method of the tree correctly balances, colors, and inserts. """ tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) ans = RedBlackTree(0, 0) ans.left = RedBlackTree(-8, 0, ans) ans.right = RedBlackTree(8, 1, ans) ans.right.left = RedBlackTree(4, 0, ans.right) ans.right.right = RedBlackTree(11, 0, ans.right) ans.right.right.left = RedBlackTree(10, 1, ans.right.right) ans.right.right.right = RedBlackTree(12, 1, ans.right.right) return tree == ans def test_insert_and_search() -> bool: """Tests searching through the tree for values.""" tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) if 5 in tree or -6 in tree or -10 in tree or 13 in tree: # Found something not in there return False if not (11 in tree and 12 in tree and -8 in tree and 0 in tree): # Didn't find something in there return False return True def test_insert_delete() -> bool: """Test the insert() and delete() method of the tree, verifying the insertion and removal of elements, and the balancing of the tree. """ tree = RedBlackTree(0) tree = tree.insert(-12) tree = tree.insert(8) tree = tree.insert(-8) tree = tree.insert(15) tree = tree.insert(4) tree = tree.insert(12) tree = tree.insert(10) tree = tree.insert(9) tree = tree.insert(11) tree = tree.remove(15) tree = tree.remove(-12) tree = tree.remove(9) if not tree.check_color_properties(): return False if list(tree.inorder_traverse()) != [-8, 0, 4, 8, 10, 11, 12]: return False return True def test_floor_ceil() -> bool: """Tests the floor and ceiling functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)] for val, floor, ceil in tuples: if tree.floor(val) != floor or tree.ceil(val) != ceil: return False return True def test_min_max() -> bool: """Tests the min and max functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if tree.get_max() != 22 or tree.get_min() != -16: return False return True def test_tree_traversal() -> bool: """Tests the three different tree traversal functions.""" tree = RedBlackTree(0) tree = tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def test_tree_chaining() -> bool: """Tests the three different tree chaining functions.""" tree = RedBlackTree(0) tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_rotations() assert test_insert() assert test_insert_and_search() assert test_insert_delete() assert test_floor_ceil() assert test_tree_traversal() assert test_tree_chaining() def main() -> None: """ >>> pytests() """ print_results("Rotating right and left", test_rotations()) print_results("Inserting", test_insert()) print_results("Searching", test_insert_and_search()) print_results("Deleting", test_insert_delete()) print_results("Floor and ceil", test_floor_ceil()) print_results("Tree traversal", test_tree_traversal()) print_results("Tree traversal", test_tree_chaining()) print("Testing tree balancing...") print("This should only be a few seconds.") test_insertion_speed() print("Done!") if __name__ == "__main__": main()
""" psf/black : true ruff : passed """ from __future__ import annotations from collections.abc import Iterator class RedBlackTree: """ A Red-Black tree, which is a self-balancing BST (binary search tree). This tree has similar performance to AVL trees, but the balancing is less strict, so it will perform faster for writing/deleting nodes and slower for reading in the average case, though, because they're both balanced binary search trees, both will get the same asymptotic performance. To read more about them, https://en.wikipedia.org/wiki/Red–black_tree Unless otherwise specified, all asymptotic runtimes are specified in terms of the size of the tree. """ def __init__( self, label: int | None = None, color: int = 0, parent: RedBlackTree | None = None, left: RedBlackTree | None = None, right: RedBlackTree | None = None, ) -> None: """Initialize a new Red-Black Tree node with the given values: label: The value associated with this node color: 0 if black, 1 if red parent: The parent to this node left: This node's left child right: This node's right child """ self.label = label self.parent = parent self.left = left self.right = right self.color = color # Here are functions which are specific to red-black trees def rotate_left(self) -> RedBlackTree: """Rotate the subtree rooted at this node to the left and returns the new root to this subtree. Performing one rotation can be done in O(1). """ parent = self.parent right = self.right if right is None: return self self.right = right.left if self.right: self.right.parent = self self.parent = right right.left = self if parent is not None: if parent.left == self: parent.left = right else: parent.right = right right.parent = parent return right def rotate_right(self) -> RedBlackTree: """Rotate the subtree rooted at this node to the right and returns the new root to this subtree. Performing one rotation can be done in O(1). """ if self.left is None: return self parent = self.parent left = self.left self.left = left.right if self.left: self.left.parent = self self.parent = left left.right = self if parent is not None: if parent.right is self: parent.right = left else: parent.left = left left.parent = parent return left def insert(self, label: int) -> RedBlackTree: """Inserts label into the subtree rooted at self, performs any rotations necessary to maintain balance, and then returns the new root to this subtree (likely self). This is guaranteed to run in O(log(n)) time. """ if self.label is None: # Only possible with an empty tree self.label = label return self if self.label == label: return self elif self.label > label: if self.left: self.left.insert(label) else: self.left = RedBlackTree(label, 1, self) self.left._insert_repair() else: if self.right: self.right.insert(label) else: self.right = RedBlackTree(label, 1, self) self.right._insert_repair() return self.parent or self def _insert_repair(self) -> None: """Repair the coloring from inserting into a tree.""" if self.parent is None: # This node is the root, so it just needs to be black self.color = 0 elif color(self.parent) == 0: # If the parent is black, then it just needs to be red self.color = 1 else: uncle = self.parent.sibling if color(uncle) == 0: if self.is_left() and self.parent.is_right(): self.parent.rotate_right() if self.right: self.right._insert_repair() elif self.is_right() and self.parent.is_left(): self.parent.rotate_left() if self.left: self.left._insert_repair() elif self.is_left(): if self.grandparent: self.grandparent.rotate_right() self.parent.color = 0 if self.parent.right: self.parent.right.color = 1 else: if self.grandparent: self.grandparent.rotate_left() self.parent.color = 0 if self.parent.left: self.parent.left.color = 1 else: self.parent.color = 0 if uncle and self.grandparent: uncle.color = 0 self.grandparent.color = 1 self.grandparent._insert_repair() def remove(self, label: int) -> RedBlackTree: # noqa: PLR0912 """Remove label from this tree.""" if self.label == label: if self.left and self.right: # It's easier to balance a node with at most one child, # so we replace this node with the greatest one less than # it and remove that. value = self.left.get_max() if value is not None: self.label = value self.left.remove(value) else: # This node has at most one non-None child, so we don't # need to replace child = self.left or self.right if self.color == 1: # This node is red, and its child is black # The only way this happens to a node with one child # is if both children are None leaves. # We can just remove this node and call it a day. if self.parent: if self.is_left(): self.parent.left = None else: self.parent.right = None else: # The node is black if child is None: # This node and its child are black if self.parent is None: # The tree is now empty return RedBlackTree(None) else: self._remove_repair() if self.is_left(): self.parent.left = None else: self.parent.right = None self.parent = None else: # This node is black and its child is red # Move the child node here and make it black self.label = child.label self.left = child.left self.right = child.right if self.left: self.left.parent = self if self.right: self.right.parent = self elif self.label is not None and self.label > label: if self.left: self.left.remove(label) else: if self.right: self.right.remove(label) return self.parent or self def _remove_repair(self) -> None: """Repair the coloring of the tree that may have been messed up.""" if ( self.parent is None or self.sibling is None or self.parent.sibling is None or self.grandparent is None ): return if color(self.sibling) == 1: self.sibling.color = 0 self.parent.color = 1 if self.is_left(): self.parent.rotate_left() else: self.parent.rotate_right() if ( color(self.parent) == 0 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent._remove_repair() return if ( color(self.parent) == 1 and color(self.sibling) == 0 and color(self.sibling.left) == 0 and color(self.sibling.right) == 0 ): self.sibling.color = 1 self.parent.color = 0 return if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 0 and color(self.sibling.left) == 1 ): self.sibling.rotate_right() self.sibling.color = 0 if self.sibling.right: self.sibling.right.color = 1 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.right) == 1 and color(self.sibling.left) == 0 ): self.sibling.rotate_left() self.sibling.color = 0 if self.sibling.left: self.sibling.left.color = 1 if ( self.is_left() and color(self.sibling) == 0 and color(self.sibling.right) == 1 ): self.parent.rotate_left() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 if ( self.is_right() and color(self.sibling) == 0 and color(self.sibling.left) == 1 ): self.parent.rotate_right() self.grandparent.color = self.parent.color self.parent.color = 0 self.parent.sibling.color = 0 def check_color_properties(self) -> bool: """Check the coloring of the tree, and return True iff the tree is colored in a way which matches these five properties: (wording stolen from wikipedia article) 1. Each node is either red or black. 2. The root node is black. 3. All leaves are black. 4. If a node is red, then both its children are black. 5. Every path from any node to all of its descendent NIL nodes has the same number of black nodes. This function runs in O(n) time, because properties 4 and 5 take that long to check. """ # I assume property 1 to hold because there is nothing that can # make the color be anything other than 0 or 1. # Property 2 if self.color: # The root was red print("Property 2") return False # Property 3 does not need to be checked, because None is assumed # to be black and is all the leaves. # Property 4 if not self.check_coloring(): print("Property 4") return False # Property 5 if self.black_height() is None: print("Property 5") return False # All properties were met return True def check_coloring(self) -> bool: """A helper function to recursively check Property 4 of a Red-Black Tree. See check_color_properties for more info. """ if self.color == 1 and 1 in (color(self.left), color(self.right)): return False if self.left and not self.left.check_coloring(): return False if self.right and not self.right.check_coloring(): return False return True def black_height(self) -> int | None: """Returns the number of black nodes from this node to the leaves of the tree, or None if there isn't one such value (the tree is color incorrectly). """ if self is None or self.left is None or self.right is None: # If we're already at a leaf, there is no path return 1 left = RedBlackTree.black_height(self.left) right = RedBlackTree.black_height(self.right) if left is None or right is None: # There are issues with coloring below children nodes return None if left != right: # The two children have unequal depths return None # Return the black depth of children, plus one if this node is # black return left + (1 - self.color) # Here are functions which are general to all binary search trees def __contains__(self, label: int) -> bool: """Search through the tree for label, returning True iff it is found somewhere in the tree. Guaranteed to run in O(log(n)) time. """ return self.search(label) is not None def search(self, label: int) -> RedBlackTree | None: """Search through the tree for label, returning its node if it's found, and None otherwise. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self elif self.label is not None and label > self.label: if self.right is None: return None else: return self.right.search(label) else: if self.left is None: return None else: return self.left.search(label) def floor(self, label: int) -> int | None: """Returns the largest element in this tree which is at most label. This method is guaranteed to run in O(log(n)) time.""" if self.label == label: return self.label elif self.label is not None and self.label > label: if self.left: return self.left.floor(label) else: return None else: if self.right: attempt = self.right.floor(label) if attempt is not None: return attempt return self.label def ceil(self, label: int) -> int | None: """Returns the smallest element in this tree which is at least label. This method is guaranteed to run in O(log(n)) time. """ if self.label == label: return self.label elif self.label is not None and self.label < label: if self.right: return self.right.ceil(label) else: return None else: if self.left: attempt = self.left.ceil(label) if attempt is not None: return attempt return self.label def get_max(self) -> int | None: """Returns the largest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.right: # Go as far right as possible return self.right.get_max() else: return self.label def get_min(self) -> int | None: """Returns the smallest element in this tree. This method is guaranteed to run in O(log(n)) time. """ if self.left: # Go as far left as possible return self.left.get_min() else: return self.label @property def grandparent(self) -> RedBlackTree | None: """Get the current node's grandparent, or None if it doesn't exist.""" if self.parent is None: return None else: return self.parent.parent @property def sibling(self) -> RedBlackTree | None: """Get the current node's sibling, or None if it doesn't exist.""" if self.parent is None: return None elif self.parent.left is self: return self.parent.right else: return self.parent.left def is_left(self) -> bool: """Returns true iff this node is the left child of its parent.""" if self.parent is None: return False return self.parent.left is self.parent.left is self def is_right(self) -> bool: """Returns true iff this node is the right child of its parent.""" if self.parent is None: return False return self.parent.right is self def __bool__(self) -> bool: return True def __len__(self) -> int: """ Return the number of nodes in this tree. """ ln = 1 if self.left: ln += len(self.left) if self.right: ln += len(self.right) return ln def preorder_traverse(self) -> Iterator[int | None]: yield self.label if self.left: yield from self.left.preorder_traverse() if self.right: yield from self.right.preorder_traverse() def inorder_traverse(self) -> Iterator[int | None]: if self.left: yield from self.left.inorder_traverse() yield self.label if self.right: yield from self.right.inorder_traverse() def postorder_traverse(self) -> Iterator[int | None]: if self.left: yield from self.left.postorder_traverse() if self.right: yield from self.right.postorder_traverse() yield self.label def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return f"'{self.label} {(self.color and 'red') or 'blk'}'" return pformat( { f"{self.label} {(self.color and 'red') or 'blk'}": ( self.left, self.right, ) }, indent=1, ) def __eq__(self, other: object) -> bool: """Test if two trees are equal.""" if not isinstance(other, RedBlackTree): return NotImplemented if self.label == other.label: return self.left == other.left and self.right == other.right else: return False def color(node: RedBlackTree | None) -> int: """Returns the color of a node, allowing for None leaves.""" if node is None: return 0 else: return node.color """ Code for testing the various functions of the red-black tree. """ def test_rotations() -> bool: """Test that the rotate_left and rotate_right functions work.""" # Make a tree to test on tree = RedBlackTree(0) tree.left = RedBlackTree(-10, parent=tree) tree.right = RedBlackTree(10, parent=tree) tree.left.left = RedBlackTree(-20, parent=tree.left) tree.left.right = RedBlackTree(-5, parent=tree.left) tree.right.left = RedBlackTree(5, parent=tree.right) tree.right.right = RedBlackTree(20, parent=tree.right) # Make the right rotation left_rot = RedBlackTree(10) left_rot.left = RedBlackTree(0, parent=left_rot) left_rot.left.left = RedBlackTree(-10, parent=left_rot.left) left_rot.left.right = RedBlackTree(5, parent=left_rot.left) left_rot.left.left.left = RedBlackTree(-20, parent=left_rot.left.left) left_rot.left.left.right = RedBlackTree(-5, parent=left_rot.left.left) left_rot.right = RedBlackTree(20, parent=left_rot) tree = tree.rotate_left() if tree != left_rot: return False tree = tree.rotate_right() tree = tree.rotate_right() # Make the left rotation right_rot = RedBlackTree(-10) right_rot.left = RedBlackTree(-20, parent=right_rot) right_rot.right = RedBlackTree(0, parent=right_rot) right_rot.right.left = RedBlackTree(-5, parent=right_rot.right) right_rot.right.right = RedBlackTree(10, parent=right_rot.right) right_rot.right.right.left = RedBlackTree(5, parent=right_rot.right.right) right_rot.right.right.right = RedBlackTree(20, parent=right_rot.right.right) if tree != right_rot: return False return True def test_insertion_speed() -> bool: """Test that the tree balances inserts to O(log(n)) by doing a lot of them. """ tree = RedBlackTree(-1) for i in range(300000): tree = tree.insert(i) return True def test_insert() -> bool: """Test the insert() method of the tree correctly balances, colors, and inserts. """ tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) ans = RedBlackTree(0, 0) ans.left = RedBlackTree(-8, 0, ans) ans.right = RedBlackTree(8, 1, ans) ans.right.left = RedBlackTree(4, 0, ans.right) ans.right.right = RedBlackTree(11, 0, ans.right) ans.right.right.left = RedBlackTree(10, 1, ans.right.right) ans.right.right.right = RedBlackTree(12, 1, ans.right.right) return tree == ans def test_insert_and_search() -> bool: """Tests searching through the tree for values.""" tree = RedBlackTree(0) tree.insert(8) tree.insert(-8) tree.insert(4) tree.insert(12) tree.insert(10) tree.insert(11) if 5 in tree or -6 in tree or -10 in tree or 13 in tree: # Found something not in there return False if not (11 in tree and 12 in tree and -8 in tree and 0 in tree): # Didn't find something in there return False return True def test_insert_delete() -> bool: """Test the insert() and delete() method of the tree, verifying the insertion and removal of elements, and the balancing of the tree. """ tree = RedBlackTree(0) tree = tree.insert(-12) tree = tree.insert(8) tree = tree.insert(-8) tree = tree.insert(15) tree = tree.insert(4) tree = tree.insert(12) tree = tree.insert(10) tree = tree.insert(9) tree = tree.insert(11) tree = tree.remove(15) tree = tree.remove(-12) tree = tree.remove(9) if not tree.check_color_properties(): return False if list(tree.inorder_traverse()) != [-8, 0, 4, 8, 10, 11, 12]: return False return True def test_floor_ceil() -> bool: """Tests the floor and ceiling functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) tuples = [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)] for val, floor, ceil in tuples: if tree.floor(val) != floor or tree.ceil(val) != ceil: return False return True def test_min_max() -> bool: """Tests the min and max functions in the tree.""" tree = RedBlackTree(0) tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if tree.get_max() != 22 or tree.get_min() != -16: return False return True def test_tree_traversal() -> bool: """Tests the three different tree traversal functions.""" tree = RedBlackTree(0) tree = tree.insert(-16) tree.insert(16) tree.insert(8) tree.insert(24) tree.insert(20) tree.insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def test_tree_chaining() -> bool: """Tests the three different tree chaining functions.""" tree = RedBlackTree(0) tree = tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22) if list(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]: return False if list(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]: return False if list(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]: return False return True def print_results(msg: str, passes: bool) -> None: print(str(msg), "works!" if passes else "doesn't work :(") def pytests() -> None: assert test_rotations() assert test_insert() assert test_insert_and_search() assert test_insert_delete() assert test_floor_ceil() assert test_tree_traversal() assert test_tree_chaining() def main() -> None: """ >>> pytests() """ print_results("Rotating right and left", test_rotations()) print_results("Inserting", test_insert()) print_results("Searching", test_insert_and_search()) print_results("Deleting", test_insert_delete()) print_results("Floor and ceil", test_floor_ceil()) print_results("Tree traversal", test_tree_traversal()) print_results("Tree traversal", test_tree_chaining()) print("Testing tree balancing...") print("This should only be a few seconds.") test_insertion_speed() print("Done!") if __name__ == "__main__": main()
1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" A Radix Tree is a data structure that represents a space-optimized trie (prefix tree) in whicheach node that is the only child is merged with its parent [https://en.wikipedia.org/wiki/Radix_tree] """ class RadixNode: def __init__(self, prefix: str = "", is_leaf: bool = False) -> None: # Mapping from the first character of the prefix of the node self.nodes: dict[str, RadixNode] = {} # A node will be a leaf if the tree contains its word self.is_leaf = is_leaf self.prefix = prefix def match(self, word: str) -> tuple[str, str, str]: """Compute the common substring of the prefix of the node and a word Args: word (str): word to compare Returns: (str, str, str): common substring, remaining prefix, remaining word >>> RadixNode("myprefix").match("mystring") ('my', 'prefix', 'string') """ x = 0 for q, w in zip(self.prefix, word): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:] def insert_many(self, words: list[str]) -> None: """Insert many words in the tree Args: words (list[str]): list of words >>> RadixNode("myprefix").insert_many(["mystring", "hello"]) """ for word in words: self.insert(word) def insert(self, word: str) -> None: """Insert a word into the tree Args: word (str): word to insert >>> RadixNode("myprefix").insert("mystring") """ # Case 1: If the word is the prefix of the node # Solution: We set the current node as leaf if self.prefix == word: self.is_leaf = True # Case 2: The node has no edges that have a prefix to the word # Solution: We create an edge from the current node to a new one # containing the word elif word[0] not in self.nodes: self.nodes[word[0]] = RadixNode(prefix=word, is_leaf=True) else: incoming_node = self.nodes[word[0]] matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) # Case 3: The node prefix is equal to the matching # Solution: We insert remaining word on the next node if remaining_prefix == "": self.nodes[matching_string[0]].insert(remaining_word) # Case 4: The word is greater equal to the matching # Solution: Create a node in between both nodes, change # prefixes and add the new node for the remaining word else: incoming_node.prefix = remaining_prefix aux_node = self.nodes[matching_string[0]] self.nodes[matching_string[0]] = RadixNode(matching_string, False) self.nodes[matching_string[0]].nodes[remaining_prefix[0]] = aux_node if remaining_word == "": self.nodes[matching_string[0]].is_leaf = True else: self.nodes[matching_string[0]].insert(remaining_word) def find(self, word: str) -> bool: """Returns if the word is on the tree Args: word (str): word to check Returns: bool: True if the word appears on the tree >>> RadixNode("myprefix").find("mystring") False """ incoming_node = self.nodes.get(word[0], None) if not incoming_node: return False else: matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # This applies when the word and the prefix are equal elif remaining_word == "": return incoming_node.is_leaf # We have word remaining so we check the next node else: return incoming_node.find(remaining_word) def delete(self, word: str) -> bool: """Deletes a word from the tree if it exists Args: word (str): word to be deleted Returns: bool: True if the word was found and deleted. False if word is not found >>> RadixNode("myprefix").delete("mystring") False """ incoming_node = self.nodes.get(word[0], None) if not incoming_node: return False else: matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # We have word remaining so we check the next node elif remaining_word != "": return incoming_node.delete(remaining_word) else: # If it is not a leaf, we don't have to delete if not incoming_node.is_leaf: return False else: # We delete the nodes if no edges go from it if len(incoming_node.nodes) == 0: del self.nodes[word[0]] # We merge the current node with its only child if len(self.nodes) == 1 and not self.is_leaf: merging_node = list(self.nodes.values())[0] self.is_leaf = merging_node.is_leaf self.prefix += merging_node.prefix self.nodes = merging_node.nodes # If there is more than 1 edge, we just mark it as non-leaf elif len(incoming_node.nodes) > 1: incoming_node.is_leaf = False # If there is 1 edge, we merge it with its child else: merging_node = list(incoming_node.nodes.values())[0] incoming_node.is_leaf = merging_node.is_leaf incoming_node.prefix += merging_node.prefix incoming_node.nodes = merging_node.nodes return True def print_tree(self, height: int = 0) -> None: """Print the tree Args: height (int, optional): Height of the printed node """ if self.prefix != "": print("-" * height, self.prefix, " (leaf)" if self.is_leaf else "") for value in self.nodes.values(): value.print_tree(height + 1) def test_trie() -> bool: words = "banana bananas bandana band apple all beast".split() root = RadixNode() root.insert_many(words) assert all(root.find(word) for word in words) assert not root.find("bandanas") assert not root.find("apps") root.delete("all") assert not root.find("all") root.delete("banana") assert not root.find("banana") assert root.find("bananas") return True def pytests() -> None: assert test_trie() def main() -> None: """ >>> pytests() """ root = RadixNode() words = "banana bananas bandanas bandana band apple all beast".split() root.insert_many(words) print("Words:", words) print("Tree:") root.print_tree() if __name__ == "__main__": main()
""" A Radix Tree is a data structure that represents a space-optimized trie (prefix tree) in whicheach node that is the only child is merged with its parent [https://en.wikipedia.org/wiki/Radix_tree] """ class RadixNode: def __init__(self, prefix: str = "", is_leaf: bool = False) -> None: # Mapping from the first character of the prefix of the node self.nodes: dict[str, RadixNode] = {} # A node will be a leaf if the tree contains its word self.is_leaf = is_leaf self.prefix = prefix def match(self, word: str) -> tuple[str, str, str]: """Compute the common substring of the prefix of the node and a word Args: word (str): word to compare Returns: (str, str, str): common substring, remaining prefix, remaining word >>> RadixNode("myprefix").match("mystring") ('my', 'prefix', 'string') """ x = 0 for q, w in zip(self.prefix, word): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:] def insert_many(self, words: list[str]) -> None: """Insert many words in the tree Args: words (list[str]): list of words >>> RadixNode("myprefix").insert_many(["mystring", "hello"]) """ for word in words: self.insert(word) def insert(self, word: str) -> None: """Insert a word into the tree Args: word (str): word to insert >>> RadixNode("myprefix").insert("mystring") """ # Case 1: If the word is the prefix of the node # Solution: We set the current node as leaf if self.prefix == word: self.is_leaf = True # Case 2: The node has no edges that have a prefix to the word # Solution: We create an edge from the current node to a new one # containing the word elif word[0] not in self.nodes: self.nodes[word[0]] = RadixNode(prefix=word, is_leaf=True) else: incoming_node = self.nodes[word[0]] matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) # Case 3: The node prefix is equal to the matching # Solution: We insert remaining word on the next node if remaining_prefix == "": self.nodes[matching_string[0]].insert(remaining_word) # Case 4: The word is greater equal to the matching # Solution: Create a node in between both nodes, change # prefixes and add the new node for the remaining word else: incoming_node.prefix = remaining_prefix aux_node = self.nodes[matching_string[0]] self.nodes[matching_string[0]] = RadixNode(matching_string, False) self.nodes[matching_string[0]].nodes[remaining_prefix[0]] = aux_node if remaining_word == "": self.nodes[matching_string[0]].is_leaf = True else: self.nodes[matching_string[0]].insert(remaining_word) def find(self, word: str) -> bool: """Returns if the word is on the tree Args: word (str): word to check Returns: bool: True if the word appears on the tree >>> RadixNode("myprefix").find("mystring") False """ incoming_node = self.nodes.get(word[0], None) if not incoming_node: return False else: matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # This applies when the word and the prefix are equal elif remaining_word == "": return incoming_node.is_leaf # We have word remaining so we check the next node else: return incoming_node.find(remaining_word) def delete(self, word: str) -> bool: """Deletes a word from the tree if it exists Args: word (str): word to be deleted Returns: bool: True if the word was found and deleted. False if word is not found >>> RadixNode("myprefix").delete("mystring") False """ incoming_node = self.nodes.get(word[0], None) if not incoming_node: return False else: matching_string, remaining_prefix, remaining_word = incoming_node.match( word ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # We have word remaining so we check the next node elif remaining_word != "": return incoming_node.delete(remaining_word) else: # If it is not a leaf, we don't have to delete if not incoming_node.is_leaf: return False else: # We delete the nodes if no edges go from it if len(incoming_node.nodes) == 0: del self.nodes[word[0]] # We merge the current node with its only child if len(self.nodes) == 1 and not self.is_leaf: merging_node = next(iter(self.nodes.values())) self.is_leaf = merging_node.is_leaf self.prefix += merging_node.prefix self.nodes = merging_node.nodes # If there is more than 1 edge, we just mark it as non-leaf elif len(incoming_node.nodes) > 1: incoming_node.is_leaf = False # If there is 1 edge, we merge it with its child else: merging_node = next(iter(incoming_node.nodes.values())) incoming_node.is_leaf = merging_node.is_leaf incoming_node.prefix += merging_node.prefix incoming_node.nodes = merging_node.nodes return True def print_tree(self, height: int = 0) -> None: """Print the tree Args: height (int, optional): Height of the printed node """ if self.prefix != "": print("-" * height, self.prefix, " (leaf)" if self.is_leaf else "") for value in self.nodes.values(): value.print_tree(height + 1) def test_trie() -> bool: words = "banana bananas bandana band apple all beast".split() root = RadixNode() root.insert_many(words) assert all(root.find(word) for word in words) assert not root.find("bandanas") assert not root.find("apps") root.delete("all") assert not root.find("all") root.delete("banana") assert not root.find("banana") assert root.find("bananas") return True def pytests() -> None: assert test_trie() def main() -> None: """ >>> pytests() """ root = RadixNode() words = "banana bananas bandanas bandana band apple all beast".split() root.insert_many(words) print("Words:", words) print("Tree:") root.print_tree() if __name__ == "__main__": main()
1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" The convex hull problem is problem of finding all the vertices of convex polygon, P of a set of points in a plane such that all the points are either on the vertices of P or inside P. TH convex hull problem has several applications in geometrical problems, computer graphics and game development. Two algorithms have been implemented for the convex hull problem here. 1. A brute-force algorithm which runs in O(n^3) 2. A divide-and-conquer algorithm which runs in O(n log(n)) There are other several other algorithms for the convex hull problem which have not been implemented here, yet. """ from __future__ import annotations from collections.abc import Iterable class Point: """ Defines a 2-d point for use by all convex-hull algorithms. Parameters ---------- x: an int or a float, the x-coordinate of the 2-d point y: an int or a float, the y-coordinate of the 2-d point Examples -------- >>> Point(1, 2) (1.0, 2.0) >>> Point("1", "2") (1.0, 2.0) >>> Point(1, 2) > Point(0, 1) True >>> Point(1, 1) == Point(1, 1) True >>> Point(-0.5, 1) == Point(0.5, 1) False >>> Point("pi", "e") Traceback (most recent call last): ... ValueError: could not convert string to float: 'pi' """ def __init__(self, x, y): self.x, self.y = float(x), float(y) def __eq__(self, other): return self.x == other.x and self.y == other.y def __ne__(self, other): return not self == other def __gt__(self, other): if self.x > other.x: return True elif self.x == other.x: return self.y > other.y return False def __lt__(self, other): return not self > other def __ge__(self, other): if self.x > other.x: return True elif self.x == other.x: return self.y >= other.y return False def __le__(self, other): if self.x < other.x: return True elif self.x == other.x: return self.y <= other.y return False def __repr__(self): return f"({self.x}, {self.y})" def __hash__(self): return hash(self.x) def _construct_points( list_of_tuples: list[Point] | list[list[float]] | Iterable[list[float]], ) -> list[Point]: """ constructs a list of points from an array-like object of numbers Arguments --------- list_of_tuples: array-like object of type numbers. Acceptable types so far are lists, tuples and sets. Returns -------- points: a list where each item is of type Point. This contains only objects which can be converted into a Point. Examples ------- >>> _construct_points([[1, 1], [2, -1], [0.3, 4]]) [(1.0, 1.0), (2.0, -1.0), (0.3, 4.0)] >>> _construct_points([1, 2]) Ignoring deformed point 1. All points must have at least 2 coordinates. Ignoring deformed point 2. All points must have at least 2 coordinates. [] >>> _construct_points([]) [] >>> _construct_points(None) [] """ points: list[Point] = [] if list_of_tuples: for p in list_of_tuples: if isinstance(p, Point): points.append(p) else: try: points.append(Point(p[0], p[1])) except (IndexError, TypeError): print( f"Ignoring deformed point {p}. All points" " must have at least 2 coordinates." ) return points def _validate_input(points: list[Point] | list[list[float]]) -> list[Point]: """ validates an input instance before a convex-hull algorithms uses it Parameters --------- points: array-like, the 2d points to validate before using with a convex-hull algorithm. The elements of points must be either lists, tuples or Points. Returns ------- points: array_like, an iterable of all well-defined Points constructed passed in. Exception --------- ValueError: if points is empty or None, or if a wrong data structure like a scalar is passed TypeError: if an iterable but non-indexable object (eg. dictionary) is passed. The exception to this a set which we'll convert to a list before using Examples ------- >>> _validate_input([[1, 2]]) [(1.0, 2.0)] >>> _validate_input([(1, 2)]) [(1.0, 2.0)] >>> _validate_input([Point(2, 1), Point(-1, 2)]) [(2.0, 1.0), (-1.0, 2.0)] >>> _validate_input([]) Traceback (most recent call last): ... ValueError: Expecting a list of points but got [] >>> _validate_input(1) Traceback (most recent call last): ... ValueError: Expecting an iterable object but got an non-iterable type 1 """ if not hasattr(points, "__iter__"): msg = f"Expecting an iterable object but got an non-iterable type {points}" raise ValueError(msg) if not points: msg = f"Expecting a list of points but got {points}" raise ValueError(msg) return _construct_points(points) def _det(a: Point, b: Point, c: Point) -> float: """ Computes the sign perpendicular distance of a 2d point c from a line segment ab. The sign indicates the direction of c relative to ab. A Positive value means c is above ab (to the left), while a negative value means c is below ab (to the right). 0 means all three points are on a straight line. As a side note, 0.5 * abs|det| is the area of triangle abc Parameters ---------- a: point, the point on the left end of line segment ab b: point, the point on the right end of line segment ab c: point, the point for which the direction and location is desired. Returns -------- det: float, abs(det) is the distance of c from ab. The sign indicates which side of line segment ab c is. det is computed as (a_xb_y + c_xa_y + b_xc_y) - (a_yb_x + c_ya_x + b_yc_x) Examples ---------- >>> _det(Point(1, 1), Point(1, 2), Point(1, 5)) 0.0 >>> _det(Point(0, 0), Point(10, 0), Point(0, 10)) 100.0 >>> _det(Point(0, 0), Point(10, 0), Point(0, -10)) -100.0 """ det = (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x) return det def convex_hull_bf(points: list[Point]) -> list[Point]: """ Constructs the convex hull of a set of 2D points using a brute force algorithm. The algorithm basically considers all combinations of points (i, j) and uses the definition of convexity to determine whether (i, j) is part of the convex hull or not. (i, j) is part of the convex hull if and only iff there are no points on both sides of the line segment connecting the ij, and there is no point k such that k is on either end of the ij. Runtime: O(n^3) - definitely horrible Parameters --------- points: array-like of object of Points, lists or tuples. The set of 2d points for which the convex-hull is needed Returns ------ convex_set: list, the convex-hull of points sorted in non-decreasing order. See Also -------- convex_hull_recursive, Examples --------- >>> convex_hull_bf([[0, 0], [1, 0], [10, 1]]) [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] >>> convex_hull_bf([[0, 0], [1, 0], [10, 0]]) [(0.0, 0.0), (10.0, 0.0)] >>> convex_hull_bf([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], ... [-0.75, 1]]) [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] >>> convex_hull_bf([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), ... (2, -1), (2, -4), (1, -3)]) [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] """ points = sorted(_validate_input(points)) n = len(points) convex_set = set() for i in range(n - 1): for j in range(i + 1, n): points_left_of_ij = points_right_of_ij = False ij_part_of_convex_hull = True for k in range(n): if k != i and k != j: det_k = _det(points[i], points[j], points[k]) if det_k > 0: points_left_of_ij = True elif det_k < 0: points_right_of_ij = True else: # point[i], point[j], point[k] all lie on a straight line # if point[k] is to the left of point[i] or it's to the # right of point[j], then point[i], point[j] cannot be # part of the convex hull of A if points[k] < points[i] or points[k] > points[j]: ij_part_of_convex_hull = False break if points_left_of_ij and points_right_of_ij: ij_part_of_convex_hull = False break if ij_part_of_convex_hull: convex_set.update([points[i], points[j]]) return sorted(convex_set) def convex_hull_recursive(points: list[Point]) -> list[Point]: """ Constructs the convex hull of a set of 2D points using a divide-and-conquer strategy The algorithm exploits the geometric properties of the problem by repeatedly partitioning the set of points into smaller hulls, and finding the convex hull of these smaller hulls. The union of the convex hull from smaller hulls is the solution to the convex hull of the larger problem. Parameter --------- points: array-like of object of Points, lists or tuples. The set of 2d points for which the convex-hull is needed Runtime: O(n log n) Returns ------- convex_set: list, the convex-hull of points sorted in non-decreasing order. Examples --------- >>> convex_hull_recursive([[0, 0], [1, 0], [10, 1]]) [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] >>> convex_hull_recursive([[0, 0], [1, 0], [10, 0]]) [(0.0, 0.0), (10.0, 0.0)] >>> convex_hull_recursive([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], ... [-0.75, 1]]) [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] >>> convex_hull_recursive([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), ... (2, -1), (2, -4), (1, -3)]) [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] """ points = sorted(_validate_input(points)) n = len(points) # divide all the points into an upper hull and a lower hull # the left most point and the right most point are definitely # members of the convex hull by definition. # use these two anchors to divide all the points into two hulls, # an upper hull and a lower hull. # all points to the left (above) the line joining the extreme points belong to the # upper hull # all points to the right (below) the line joining the extreme points below to the # lower hull # ignore all points on the line joining the extreme points since they cannot be # part of the convex hull left_most_point = points[0] right_most_point = points[n - 1] convex_set = {left_most_point, right_most_point} upper_hull = [] lower_hull = [] for i in range(1, n - 1): det = _det(left_most_point, right_most_point, points[i]) if det > 0: upper_hull.append(points[i]) elif det < 0: lower_hull.append(points[i]) _construct_hull(upper_hull, left_most_point, right_most_point, convex_set) _construct_hull(lower_hull, right_most_point, left_most_point, convex_set) return sorted(convex_set) def _construct_hull( points: list[Point], left: Point, right: Point, convex_set: set[Point] ) -> None: """ Parameters --------- points: list or None, the hull of points from which to choose the next convex-hull point left: Point, the point to the left of line segment joining left and right right: The point to the right of the line segment joining left and right convex_set: set, the current convex-hull. The state of convex-set gets updated by this function Note ---- For the line segment 'ab', 'a' is on the left and 'b' on the right. but the reverse is true for the line segment 'ba'. Returns ------- Nothing, only updates the state of convex-set """ if points: extreme_point = None extreme_point_distance = float("-inf") candidate_points = [] for p in points: det = _det(left, right, p) if det > 0: candidate_points.append(p) if det > extreme_point_distance: extreme_point_distance = det extreme_point = p if extreme_point: _construct_hull(candidate_points, left, extreme_point, convex_set) convex_set.add(extreme_point) _construct_hull(candidate_points, extreme_point, right, convex_set) def convex_hull_melkman(points: list[Point]) -> list[Point]: """ Constructs the convex hull of a set of 2D points using the melkman algorithm. The algorithm works by iteratively inserting points of a simple polygonal chain (meaning that no line segments between two consecutive points cross each other). Sorting the points yields such a polygonal chain. For a detailed description, see http://cgm.cs.mcgill.ca/~athens/cs601/Melkman.html Runtime: O(n log n) - O(n) if points are already sorted in the input Parameters --------- points: array-like of object of Points, lists or tuples. The set of 2d points for which the convex-hull is needed Returns ------ convex_set: list, the convex-hull of points sorted in non-decreasing order. See Also -------- Examples --------- >>> convex_hull_melkman([[0, 0], [1, 0], [10, 1]]) [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] >>> convex_hull_melkman([[0, 0], [1, 0], [10, 0]]) [(0.0, 0.0), (10.0, 0.0)] >>> convex_hull_melkman([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], ... [-0.75, 1]]) [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] >>> convex_hull_melkman([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), ... (2, -1), (2, -4), (1, -3)]) [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] """ points = sorted(_validate_input(points)) n = len(points) convex_hull = points[:2] for i in range(2, n): det = _det(convex_hull[1], convex_hull[0], points[i]) if det > 0: convex_hull.insert(0, points[i]) break elif det < 0: convex_hull.append(points[i]) break else: convex_hull[1] = points[i] i += 1 for j in range(i, n): if ( _det(convex_hull[0], convex_hull[-1], points[j]) > 0 and _det(convex_hull[-1], convex_hull[0], points[1]) < 0 ): # The point lies within the convex hull continue convex_hull.insert(0, points[j]) convex_hull.append(points[j]) while _det(convex_hull[0], convex_hull[1], convex_hull[2]) >= 0: del convex_hull[1] while _det(convex_hull[-1], convex_hull[-2], convex_hull[-3]) <= 0: del convex_hull[-2] # `convex_hull` is contains the convex hull in circular order return sorted(convex_hull[1:] if len(convex_hull) > 3 else convex_hull) def main(): points = [ (0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), (2, -1), (2, -4), (1, -3), ] # the convex set of points is # [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)] results_bf = convex_hull_bf(points) results_recursive = convex_hull_recursive(points) assert results_bf == results_recursive results_melkman = convex_hull_melkman(points) assert results_bf == results_melkman print(results_bf) if __name__ == "__main__": main()
""" The convex hull problem is problem of finding all the vertices of convex polygon, P of a set of points in a plane such that all the points are either on the vertices of P or inside P. TH convex hull problem has several applications in geometrical problems, computer graphics and game development. Two algorithms have been implemented for the convex hull problem here. 1. A brute-force algorithm which runs in O(n^3) 2. A divide-and-conquer algorithm which runs in O(n log(n)) There are other several other algorithms for the convex hull problem which have not been implemented here, yet. """ from __future__ import annotations from collections.abc import Iterable class Point: """ Defines a 2-d point for use by all convex-hull algorithms. Parameters ---------- x: an int or a float, the x-coordinate of the 2-d point y: an int or a float, the y-coordinate of the 2-d point Examples -------- >>> Point(1, 2) (1.0, 2.0) >>> Point("1", "2") (1.0, 2.0) >>> Point(1, 2) > Point(0, 1) True >>> Point(1, 1) == Point(1, 1) True >>> Point(-0.5, 1) == Point(0.5, 1) False >>> Point("pi", "e") Traceback (most recent call last): ... ValueError: could not convert string to float: 'pi' """ def __init__(self, x, y): self.x, self.y = float(x), float(y) def __eq__(self, other): return self.x == other.x and self.y == other.y def __ne__(self, other): return not self == other def __gt__(self, other): if self.x > other.x: return True elif self.x == other.x: return self.y > other.y return False def __lt__(self, other): return not self > other def __ge__(self, other): if self.x > other.x: return True elif self.x == other.x: return self.y >= other.y return False def __le__(self, other): if self.x < other.x: return True elif self.x == other.x: return self.y <= other.y return False def __repr__(self): return f"({self.x}, {self.y})" def __hash__(self): return hash(self.x) def _construct_points( list_of_tuples: list[Point] | list[list[float]] | Iterable[list[float]], ) -> list[Point]: """ constructs a list of points from an array-like object of numbers Arguments --------- list_of_tuples: array-like object of type numbers. Acceptable types so far are lists, tuples and sets. Returns -------- points: a list where each item is of type Point. This contains only objects which can be converted into a Point. Examples ------- >>> _construct_points([[1, 1], [2, -1], [0.3, 4]]) [(1.0, 1.0), (2.0, -1.0), (0.3, 4.0)] >>> _construct_points([1, 2]) Ignoring deformed point 1. All points must have at least 2 coordinates. Ignoring deformed point 2. All points must have at least 2 coordinates. [] >>> _construct_points([]) [] >>> _construct_points(None) [] """ points: list[Point] = [] if list_of_tuples: for p in list_of_tuples: if isinstance(p, Point): points.append(p) else: try: points.append(Point(p[0], p[1])) except (IndexError, TypeError): print( f"Ignoring deformed point {p}. All points" " must have at least 2 coordinates." ) return points def _validate_input(points: list[Point] | list[list[float]]) -> list[Point]: """ validates an input instance before a convex-hull algorithms uses it Parameters --------- points: array-like, the 2d points to validate before using with a convex-hull algorithm. The elements of points must be either lists, tuples or Points. Returns ------- points: array_like, an iterable of all well-defined Points constructed passed in. Exception --------- ValueError: if points is empty or None, or if a wrong data structure like a scalar is passed TypeError: if an iterable but non-indexable object (eg. dictionary) is passed. The exception to this a set which we'll convert to a list before using Examples ------- >>> _validate_input([[1, 2]]) [(1.0, 2.0)] >>> _validate_input([(1, 2)]) [(1.0, 2.0)] >>> _validate_input([Point(2, 1), Point(-1, 2)]) [(2.0, 1.0), (-1.0, 2.0)] >>> _validate_input([]) Traceback (most recent call last): ... ValueError: Expecting a list of points but got [] >>> _validate_input(1) Traceback (most recent call last): ... ValueError: Expecting an iterable object but got an non-iterable type 1 """ if not hasattr(points, "__iter__"): msg = f"Expecting an iterable object but got an non-iterable type {points}" raise ValueError(msg) if not points: msg = f"Expecting a list of points but got {points}" raise ValueError(msg) return _construct_points(points) def _det(a: Point, b: Point, c: Point) -> float: """ Computes the sign perpendicular distance of a 2d point c from a line segment ab. The sign indicates the direction of c relative to ab. A Positive value means c is above ab (to the left), while a negative value means c is below ab (to the right). 0 means all three points are on a straight line. As a side note, 0.5 * abs|det| is the area of triangle abc Parameters ---------- a: point, the point on the left end of line segment ab b: point, the point on the right end of line segment ab c: point, the point for which the direction and location is desired. Returns -------- det: float, abs(det) is the distance of c from ab. The sign indicates which side of line segment ab c is. det is computed as (a_xb_y + c_xa_y + b_xc_y) - (a_yb_x + c_ya_x + b_yc_x) Examples ---------- >>> _det(Point(1, 1), Point(1, 2), Point(1, 5)) 0.0 >>> _det(Point(0, 0), Point(10, 0), Point(0, 10)) 100.0 >>> _det(Point(0, 0), Point(10, 0), Point(0, -10)) -100.0 """ det = (a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x) return det def convex_hull_bf(points: list[Point]) -> list[Point]: """ Constructs the convex hull of a set of 2D points using a brute force algorithm. The algorithm basically considers all combinations of points (i, j) and uses the definition of convexity to determine whether (i, j) is part of the convex hull or not. (i, j) is part of the convex hull if and only iff there are no points on both sides of the line segment connecting the ij, and there is no point k such that k is on either end of the ij. Runtime: O(n^3) - definitely horrible Parameters --------- points: array-like of object of Points, lists or tuples. The set of 2d points for which the convex-hull is needed Returns ------ convex_set: list, the convex-hull of points sorted in non-decreasing order. See Also -------- convex_hull_recursive, Examples --------- >>> convex_hull_bf([[0, 0], [1, 0], [10, 1]]) [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] >>> convex_hull_bf([[0, 0], [1, 0], [10, 0]]) [(0.0, 0.0), (10.0, 0.0)] >>> convex_hull_bf([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], ... [-0.75, 1]]) [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] >>> convex_hull_bf([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), ... (2, -1), (2, -4), (1, -3)]) [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] """ points = sorted(_validate_input(points)) n = len(points) convex_set = set() for i in range(n - 1): for j in range(i + 1, n): points_left_of_ij = points_right_of_ij = False ij_part_of_convex_hull = True for k in range(n): if k not in {i, j}: det_k = _det(points[i], points[j], points[k]) if det_k > 0: points_left_of_ij = True elif det_k < 0: points_right_of_ij = True else: # point[i], point[j], point[k] all lie on a straight line # if point[k] is to the left of point[i] or it's to the # right of point[j], then point[i], point[j] cannot be # part of the convex hull of A if points[k] < points[i] or points[k] > points[j]: ij_part_of_convex_hull = False break if points_left_of_ij and points_right_of_ij: ij_part_of_convex_hull = False break if ij_part_of_convex_hull: convex_set.update([points[i], points[j]]) return sorted(convex_set) def convex_hull_recursive(points: list[Point]) -> list[Point]: """ Constructs the convex hull of a set of 2D points using a divide-and-conquer strategy The algorithm exploits the geometric properties of the problem by repeatedly partitioning the set of points into smaller hulls, and finding the convex hull of these smaller hulls. The union of the convex hull from smaller hulls is the solution to the convex hull of the larger problem. Parameter --------- points: array-like of object of Points, lists or tuples. The set of 2d points for which the convex-hull is needed Runtime: O(n log n) Returns ------- convex_set: list, the convex-hull of points sorted in non-decreasing order. Examples --------- >>> convex_hull_recursive([[0, 0], [1, 0], [10, 1]]) [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] >>> convex_hull_recursive([[0, 0], [1, 0], [10, 0]]) [(0.0, 0.0), (10.0, 0.0)] >>> convex_hull_recursive([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], ... [-0.75, 1]]) [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] >>> convex_hull_recursive([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), ... (2, -1), (2, -4), (1, -3)]) [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] """ points = sorted(_validate_input(points)) n = len(points) # divide all the points into an upper hull and a lower hull # the left most point and the right most point are definitely # members of the convex hull by definition. # use these two anchors to divide all the points into two hulls, # an upper hull and a lower hull. # all points to the left (above) the line joining the extreme points belong to the # upper hull # all points to the right (below) the line joining the extreme points below to the # lower hull # ignore all points on the line joining the extreme points since they cannot be # part of the convex hull left_most_point = points[0] right_most_point = points[n - 1] convex_set = {left_most_point, right_most_point} upper_hull = [] lower_hull = [] for i in range(1, n - 1): det = _det(left_most_point, right_most_point, points[i]) if det > 0: upper_hull.append(points[i]) elif det < 0: lower_hull.append(points[i]) _construct_hull(upper_hull, left_most_point, right_most_point, convex_set) _construct_hull(lower_hull, right_most_point, left_most_point, convex_set) return sorted(convex_set) def _construct_hull( points: list[Point], left: Point, right: Point, convex_set: set[Point] ) -> None: """ Parameters --------- points: list or None, the hull of points from which to choose the next convex-hull point left: Point, the point to the left of line segment joining left and right right: The point to the right of the line segment joining left and right convex_set: set, the current convex-hull. The state of convex-set gets updated by this function Note ---- For the line segment 'ab', 'a' is on the left and 'b' on the right. but the reverse is true for the line segment 'ba'. Returns ------- Nothing, only updates the state of convex-set """ if points: extreme_point = None extreme_point_distance = float("-inf") candidate_points = [] for p in points: det = _det(left, right, p) if det > 0: candidate_points.append(p) if det > extreme_point_distance: extreme_point_distance = det extreme_point = p if extreme_point: _construct_hull(candidate_points, left, extreme_point, convex_set) convex_set.add(extreme_point) _construct_hull(candidate_points, extreme_point, right, convex_set) def convex_hull_melkman(points: list[Point]) -> list[Point]: """ Constructs the convex hull of a set of 2D points using the melkman algorithm. The algorithm works by iteratively inserting points of a simple polygonal chain (meaning that no line segments between two consecutive points cross each other). Sorting the points yields such a polygonal chain. For a detailed description, see http://cgm.cs.mcgill.ca/~athens/cs601/Melkman.html Runtime: O(n log n) - O(n) if points are already sorted in the input Parameters --------- points: array-like of object of Points, lists or tuples. The set of 2d points for which the convex-hull is needed Returns ------ convex_set: list, the convex-hull of points sorted in non-decreasing order. See Also -------- Examples --------- >>> convex_hull_melkman([[0, 0], [1, 0], [10, 1]]) [(0.0, 0.0), (1.0, 0.0), (10.0, 1.0)] >>> convex_hull_melkman([[0, 0], [1, 0], [10, 0]]) [(0.0, 0.0), (10.0, 0.0)] >>> convex_hull_melkman([[-1, 1],[-1, -1], [0, 0], [0.5, 0.5], [1, -1], [1, 1], ... [-0.75, 1]]) [(-1.0, -1.0), (-1.0, 1.0), (1.0, -1.0), (1.0, 1.0)] >>> convex_hull_melkman([(0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), ... (2, -1), (2, -4), (1, -3)]) [(0.0, 0.0), (0.0, 3.0), (1.0, -3.0), (2.0, -4.0), (3.0, 0.0), (3.0, 3.0)] """ points = sorted(_validate_input(points)) n = len(points) convex_hull = points[:2] for i in range(2, n): det = _det(convex_hull[1], convex_hull[0], points[i]) if det > 0: convex_hull.insert(0, points[i]) break elif det < 0: convex_hull.append(points[i]) break else: convex_hull[1] = points[i] i += 1 for j in range(i, n): if ( _det(convex_hull[0], convex_hull[-1], points[j]) > 0 and _det(convex_hull[-1], convex_hull[0], points[1]) < 0 ): # The point lies within the convex hull continue convex_hull.insert(0, points[j]) convex_hull.append(points[j]) while _det(convex_hull[0], convex_hull[1], convex_hull[2]) >= 0: del convex_hull[1] while _det(convex_hull[-1], convex_hull[-2], convex_hull[-3]) <= 0: del convex_hull[-2] # `convex_hull` is contains the convex hull in circular order return sorted(convex_hull[1:] if len(convex_hull) > 3 else convex_hull) def main(): points = [ (0, 3), (2, 2), (1, 1), (2, 1), (3, 0), (0, 0), (3, 3), (2, -1), (2, -4), (1, -3), ] # the convex set of points is # [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)] results_bf = convex_hull_bf(points) results_recursive = convex_hull_recursive(points) assert results_bf == results_recursive results_melkman = convex_hull_melkman(points) assert results_bf == results_melkman print(results_bf) if __name__ == "__main__": main()
1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
from collections import deque from math import floor from random import random from time import time # the default weight is 1 if not assigned but all the implementation is weighted class DirectedGraph: def __init__(self): self.graph = {} # adding vertices and edges # adding the weight is optional # handles repetition def add_pair(self, u, v, w=1): if self.graph.get(u): if self.graph[u].count([w, v]) == 0: self.graph[u].append([w, v]) else: self.graph[u] = [[w, v]] if not self.graph.get(v): self.graph[v] = [] def all_nodes(self): return list(self.graph) # handles if the input does not exist def remove_pair(self, u, v): if self.graph.get(u): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_) # if no destination is meant the default value is -1 def dfs(self, s=-2, d=-1): if s == d: return [] stack = [] visited = [] if s == -2: s = list(self.graph)[0] stack.append(s) visited.append(s) ss = s while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for node in self.graph[s]: if visited.count(node[1]) < 1: if node[1] == d: visited.append(d) return visited else: stack.append(node[1]) visited.append(node[1]) ss = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(stack) != 0: s = stack[len(stack) - 1] else: s = ss # check if se have reached the starting point if len(stack) == 0: return visited # c is the count of nodes you want and if you leave it or pass -1 to the function # the count will be random from 10 to 10000 def fill_graph_randomly(self, c=-1): if c == -1: c = floor(random() * 10000) + 10 for i in range(c): # every vertex has max 100 edges for _ in range(floor(random() * 102) + 1): n = floor(random() * c) + 1 if n != i: self.add_pair(i, n, 1) def bfs(self, s=-2): d = deque() visited = [] if s == -2: s = list(self.graph)[0] d.append(s) visited.append(s) while d: s = d.popleft() if len(self.graph[s]) != 0: for node in self.graph[s]: if visited.count(node[1]) < 1: d.append(node[1]) visited.append(node[1]) return visited def in_degree(self, u): count = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def out_degree(self, u): return len(self.graph[u]) def topological_sort(self, s=-2): stack = [] visited = [] if s == -2: s = list(self.graph)[0] stack.append(s) visited.append(s) ss = s sorted_nodes = [] while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for node in self.graph[s]: if visited.count(node[1]) < 1: stack.append(node[1]) visited.append(node[1]) ss = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop()) if len(stack) != 0: s = stack[len(stack) - 1] else: s = ss # check if se have reached the starting point if len(stack) == 0: return sorted_nodes def cycle_nodes(self): stack = [] visited = [] s = list(self.graph)[0] stack.append(s) visited.append(s) parent = -2 indirect_parents = [] ss = s on_the_way_back = False anticipating_nodes = set() while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for node in self.graph[s]: if ( visited.count(node[1]) > 0 and node[1] != parent and indirect_parents.count(node[1]) > 0 and not on_the_way_back ): len_stack = len(stack) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1]) break else: anticipating_nodes.add(stack[len_stack]) len_stack -= 1 if visited.count(node[1]) < 1: stack.append(node[1]) visited.append(node[1]) ss = node[1] break # check if all the children are visited if s == ss: stack.pop() on_the_way_back = True if len(stack) != 0: s = stack[len(stack) - 1] else: on_the_way_back = False indirect_parents.append(parent) parent = s s = ss # check if se have reached the starting point if len(stack) == 0: return list(anticipating_nodes) def has_cycle(self): stack = [] visited = [] s = list(self.graph)[0] stack.append(s) visited.append(s) parent = -2 indirect_parents = [] ss = s on_the_way_back = False anticipating_nodes = set() while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for node in self.graph[s]: if ( visited.count(node[1]) > 0 and node[1] != parent and indirect_parents.count(node[1]) > 0 and not on_the_way_back ): len_stack_minus_one = len(stack) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1]) break else: return True if visited.count(node[1]) < 1: stack.append(node[1]) visited.append(node[1]) ss = node[1] break # check if all the children are visited if s == ss: stack.pop() on_the_way_back = True if len(stack) != 0: s = stack[len(stack) - 1] else: on_the_way_back = False indirect_parents.append(parent) parent = s s = ss # check if se have reached the starting point if len(stack) == 0: return False def dfs_time(self, s=-2, e=-1): begin = time() self.dfs(s, e) end = time() return end - begin def bfs_time(self, s=-2): begin = time() self.bfs(s) end = time() return end - begin class Graph: def __init__(self): self.graph = {} # adding vertices and edges # adding the weight is optional # handles repetition def add_pair(self, u, v, w=1): # check if the u exists if self.graph.get(u): # if there already is a edge if self.graph[u].count([w, v]) == 0: self.graph[u].append([w, v]) else: # if u does not exist self.graph[u] = [[w, v]] # add the other way if self.graph.get(v): # if there already is a edge if self.graph[v].count([w, u]) == 0: self.graph[v].append([w, u]) else: # if u does not exist self.graph[v] = [[w, u]] # handles if the input does not exist def remove_pair(self, u, v): if self.graph.get(u): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_) # the other way round if self.graph.get(v): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(_) # if no destination is meant the default value is -1 def dfs(self, s=-2, d=-1): if s == d: return [] stack = [] visited = [] if s == -2: s = list(self.graph)[0] stack.append(s) visited.append(s) ss = s while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for node in self.graph[s]: if visited.count(node[1]) < 1: if node[1] == d: visited.append(d) return visited else: stack.append(node[1]) visited.append(node[1]) ss = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(stack) != 0: s = stack[len(stack) - 1] else: s = ss # check if se have reached the starting point if len(stack) == 0: return visited # c is the count of nodes you want and if you leave it or pass -1 to the function # the count will be random from 10 to 10000 def fill_graph_randomly(self, c=-1): if c == -1: c = floor(random() * 10000) + 10 for i in range(c): # every vertex has max 100 edges for _ in range(floor(random() * 102) + 1): n = floor(random() * c) + 1 if n != i: self.add_pair(i, n, 1) def bfs(self, s=-2): d = deque() visited = [] if s == -2: s = list(self.graph)[0] d.append(s) visited.append(s) while d: s = d.popleft() if len(self.graph[s]) != 0: for node in self.graph[s]: if visited.count(node[1]) < 1: d.append(node[1]) visited.append(node[1]) return visited def degree(self, u): return len(self.graph[u]) def cycle_nodes(self): stack = [] visited = [] s = list(self.graph)[0] stack.append(s) visited.append(s) parent = -2 indirect_parents = [] ss = s on_the_way_back = False anticipating_nodes = set() while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for node in self.graph[s]: if ( visited.count(node[1]) > 0 and node[1] != parent and indirect_parents.count(node[1]) > 0 and not on_the_way_back ): len_stack = len(stack) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1]) break else: anticipating_nodes.add(stack[len_stack]) len_stack -= 1 if visited.count(node[1]) < 1: stack.append(node[1]) visited.append(node[1]) ss = node[1] break # check if all the children are visited if s == ss: stack.pop() on_the_way_back = True if len(stack) != 0: s = stack[len(stack) - 1] else: on_the_way_back = False indirect_parents.append(parent) parent = s s = ss # check if se have reached the starting point if len(stack) == 0: return list(anticipating_nodes) def has_cycle(self): stack = [] visited = [] s = list(self.graph)[0] stack.append(s) visited.append(s) parent = -2 indirect_parents = [] ss = s on_the_way_back = False anticipating_nodes = set() while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for node in self.graph[s]: if ( visited.count(node[1]) > 0 and node[1] != parent and indirect_parents.count(node[1]) > 0 and not on_the_way_back ): len_stack_minus_one = len(stack) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1]) break else: return True if visited.count(node[1]) < 1: stack.append(node[1]) visited.append(node[1]) ss = node[1] break # check if all the children are visited if s == ss: stack.pop() on_the_way_back = True if len(stack) != 0: s = stack[len(stack) - 1] else: on_the_way_back = False indirect_parents.append(parent) parent = s s = ss # check if se have reached the starting point if len(stack) == 0: return False def all_nodes(self): return list(self.graph) def dfs_time(self, s=-2, e=-1): begin = time() self.dfs(s, e) end = time() return end - begin def bfs_time(self, s=-2): begin = time() self.bfs(s) end = time() return end - begin
from collections import deque from math import floor from random import random from time import time # the default weight is 1 if not assigned but all the implementation is weighted class DirectedGraph: def __init__(self): self.graph = {} # adding vertices and edges # adding the weight is optional # handles repetition def add_pair(self, u, v, w=1): if self.graph.get(u): if self.graph[u].count([w, v]) == 0: self.graph[u].append([w, v]) else: self.graph[u] = [[w, v]] if not self.graph.get(v): self.graph[v] = [] def all_nodes(self): return list(self.graph) # handles if the input does not exist def remove_pair(self, u, v): if self.graph.get(u): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_) # if no destination is meant the default value is -1 def dfs(self, s=-2, d=-1): if s == d: return [] stack = [] visited = [] if s == -2: s = next(iter(self.graph)) stack.append(s) visited.append(s) ss = s while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for node in self.graph[s]: if visited.count(node[1]) < 1: if node[1] == d: visited.append(d) return visited else: stack.append(node[1]) visited.append(node[1]) ss = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(stack) != 0: s = stack[len(stack) - 1] else: s = ss # check if se have reached the starting point if len(stack) == 0: return visited # c is the count of nodes you want and if you leave it or pass -1 to the function # the count will be random from 10 to 10000 def fill_graph_randomly(self, c=-1): if c == -1: c = floor(random() * 10000) + 10 for i in range(c): # every vertex has max 100 edges for _ in range(floor(random() * 102) + 1): n = floor(random() * c) + 1 if n != i: self.add_pair(i, n, 1) def bfs(self, s=-2): d = deque() visited = [] if s == -2: s = next(iter(self.graph)) d.append(s) visited.append(s) while d: s = d.popleft() if len(self.graph[s]) != 0: for node in self.graph[s]: if visited.count(node[1]) < 1: d.append(node[1]) visited.append(node[1]) return visited def in_degree(self, u): count = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def out_degree(self, u): return len(self.graph[u]) def topological_sort(self, s=-2): stack = [] visited = [] if s == -2: s = next(iter(self.graph)) stack.append(s) visited.append(s) ss = s sorted_nodes = [] while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for node in self.graph[s]: if visited.count(node[1]) < 1: stack.append(node[1]) visited.append(node[1]) ss = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop()) if len(stack) != 0: s = stack[len(stack) - 1] else: s = ss # check if se have reached the starting point if len(stack) == 0: return sorted_nodes def cycle_nodes(self): stack = [] visited = [] s = next(iter(self.graph)) stack.append(s) visited.append(s) parent = -2 indirect_parents = [] ss = s on_the_way_back = False anticipating_nodes = set() while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for node in self.graph[s]: if ( visited.count(node[1]) > 0 and node[1] != parent and indirect_parents.count(node[1]) > 0 and not on_the_way_back ): len_stack = len(stack) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1]) break else: anticipating_nodes.add(stack[len_stack]) len_stack -= 1 if visited.count(node[1]) < 1: stack.append(node[1]) visited.append(node[1]) ss = node[1] break # check if all the children are visited if s == ss: stack.pop() on_the_way_back = True if len(stack) != 0: s = stack[len(stack) - 1] else: on_the_way_back = False indirect_parents.append(parent) parent = s s = ss # check if se have reached the starting point if len(stack) == 0: return list(anticipating_nodes) def has_cycle(self): stack = [] visited = [] s = next(iter(self.graph)) stack.append(s) visited.append(s) parent = -2 indirect_parents = [] ss = s on_the_way_back = False anticipating_nodes = set() while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for node in self.graph[s]: if ( visited.count(node[1]) > 0 and node[1] != parent and indirect_parents.count(node[1]) > 0 and not on_the_way_back ): len_stack_minus_one = len(stack) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1]) break else: return True if visited.count(node[1]) < 1: stack.append(node[1]) visited.append(node[1]) ss = node[1] break # check if all the children are visited if s == ss: stack.pop() on_the_way_back = True if len(stack) != 0: s = stack[len(stack) - 1] else: on_the_way_back = False indirect_parents.append(parent) parent = s s = ss # check if se have reached the starting point if len(stack) == 0: return False def dfs_time(self, s=-2, e=-1): begin = time() self.dfs(s, e) end = time() return end - begin def bfs_time(self, s=-2): begin = time() self.bfs(s) end = time() return end - begin class Graph: def __init__(self): self.graph = {} # adding vertices and edges # adding the weight is optional # handles repetition def add_pair(self, u, v, w=1): # check if the u exists if self.graph.get(u): # if there already is a edge if self.graph[u].count([w, v]) == 0: self.graph[u].append([w, v]) else: # if u does not exist self.graph[u] = [[w, v]] # add the other way if self.graph.get(v): # if there already is a edge if self.graph[v].count([w, u]) == 0: self.graph[v].append([w, u]) else: # if u does not exist self.graph[v] = [[w, u]] # handles if the input does not exist def remove_pair(self, u, v): if self.graph.get(u): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(_) # the other way round if self.graph.get(v): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(_) # if no destination is meant the default value is -1 def dfs(self, s=-2, d=-1): if s == d: return [] stack = [] visited = [] if s == -2: s = next(iter(self.graph)) stack.append(s) visited.append(s) ss = s while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for node in self.graph[s]: if visited.count(node[1]) < 1: if node[1] == d: visited.append(d) return visited else: stack.append(node[1]) visited.append(node[1]) ss = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(stack) != 0: s = stack[len(stack) - 1] else: s = ss # check if se have reached the starting point if len(stack) == 0: return visited # c is the count of nodes you want and if you leave it or pass -1 to the function # the count will be random from 10 to 10000 def fill_graph_randomly(self, c=-1): if c == -1: c = floor(random() * 10000) + 10 for i in range(c): # every vertex has max 100 edges for _ in range(floor(random() * 102) + 1): n = floor(random() * c) + 1 if n != i: self.add_pair(i, n, 1) def bfs(self, s=-2): d = deque() visited = [] if s == -2: s = next(iter(self.graph)) d.append(s) visited.append(s) while d: s = d.popleft() if len(self.graph[s]) != 0: for node in self.graph[s]: if visited.count(node[1]) < 1: d.append(node[1]) visited.append(node[1]) return visited def degree(self, u): return len(self.graph[u]) def cycle_nodes(self): stack = [] visited = [] s = next(iter(self.graph)) stack.append(s) visited.append(s) parent = -2 indirect_parents = [] ss = s on_the_way_back = False anticipating_nodes = set() while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for node in self.graph[s]: if ( visited.count(node[1]) > 0 and node[1] != parent and indirect_parents.count(node[1]) > 0 and not on_the_way_back ): len_stack = len(stack) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1]) break else: anticipating_nodes.add(stack[len_stack]) len_stack -= 1 if visited.count(node[1]) < 1: stack.append(node[1]) visited.append(node[1]) ss = node[1] break # check if all the children are visited if s == ss: stack.pop() on_the_way_back = True if len(stack) != 0: s = stack[len(stack) - 1] else: on_the_way_back = False indirect_parents.append(parent) parent = s s = ss # check if se have reached the starting point if len(stack) == 0: return list(anticipating_nodes) def has_cycle(self): stack = [] visited = [] s = next(iter(self.graph)) stack.append(s) visited.append(s) parent = -2 indirect_parents = [] ss = s on_the_way_back = False anticipating_nodes = set() while True: # check if there is any non isolated nodes if len(self.graph[s]) != 0: ss = s for node in self.graph[s]: if ( visited.count(node[1]) > 0 and node[1] != parent and indirect_parents.count(node[1]) > 0 and not on_the_way_back ): len_stack_minus_one = len(stack) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1]) break else: return True if visited.count(node[1]) < 1: stack.append(node[1]) visited.append(node[1]) ss = node[1] break # check if all the children are visited if s == ss: stack.pop() on_the_way_back = True if len(stack) != 0: s = stack[len(stack) - 1] else: on_the_way_back = False indirect_parents.append(parent) parent = s s = ss # check if se have reached the starting point if len(stack) == 0: return False def all_nodes(self): return list(self.graph) def dfs_time(self, s=-2, e=-1): begin = time() self.dfs(s, e) end = time() return end - begin def bfs_time(self, s=-2): begin = time() self.bfs(s) end = time() return end - begin
1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
class FlowNetwork: def __init__(self, graph, sources, sinks): self.source_index = None self.sink_index = None self.graph = graph self._normalize_graph(sources, sinks) self.vertices_count = len(graph) self.maximum_flow_algorithm = None # make only one source and one sink def _normalize_graph(self, sources, sinks): if sources is int: sources = [sources] if sinks is int: sinks = [sinks] if len(sources) == 0 or len(sinks) == 0: return self.source_index = sources[0] self.sink_index = sinks[0] # make fake vertex if there are more # than one source or sink if len(sources) > 1 or len(sinks) > 1: max_input_flow = 0 for i in sources: max_input_flow += sum(self.graph[i]) size = len(self.graph) + 1 for room in self.graph: room.insert(0, 0) self.graph.insert(0, [0] * size) for i in sources: self.graph[0][i + 1] = max_input_flow self.source_index = 0 size = len(self.graph) + 1 for room in self.graph: room.append(0) self.graph.append([0] * size) for i in sinks: self.graph[i + 1][size - 1] = max_input_flow self.sink_index = size - 1 def find_maximum_flow(self): if self.maximum_flow_algorithm is None: raise Exception("You need to set maximum flow algorithm before.") if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def set_maximum_flow_algorithm(self, algorithm): self.maximum_flow_algorithm = algorithm(self) class FlowNetworkAlgorithmExecutor: def __init__(self, flow_network): self.flow_network = flow_network self.verticies_count = flow_network.verticesCount self.source_index = flow_network.sourceIndex self.sink_index = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that self.graph = flow_network.graph self.executed = False def execute(self): if not self.executed: self._algorithm() self.executed = True # You should override it def _algorithm(self): pass class MaximumFlowAlgorithmExecutor(FlowNetworkAlgorithmExecutor): def __init__(self, flow_network): super().__init__(flow_network) # use this to save your result self.maximum_flow = -1 def get_maximum_flow(self): if not self.executed: raise Exception("You should execute algorithm before using its result!") return self.maximum_flow class PushRelabelExecutor(MaximumFlowAlgorithmExecutor): def __init__(self, flow_network): super().__init__(flow_network) self.preflow = [[0] * self.verticies_count for i in range(self.verticies_count)] self.heights = [0] * self.verticies_count self.excesses = [0] * self.verticies_count def _algorithm(self): self.heights[self.source_index] = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index]): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule vertices_list = [ i for i in range(self.verticies_count) if i != self.source_index and i != self.sink_index ] # move through list i = 0 while i < len(vertices_list): vertex_index = vertices_list[i] previous_height = self.heights[vertex_index] self.process_vertex(vertex_index) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0, vertices_list.pop(i)) i = 0 else: i += 1 self.maximum_flow = sum(self.preflow[self.source_index]) def process_vertex(self, vertex_index): while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(vertex_index, neighbour_index) self.relabel(vertex_index) def push(self, from_index, to_index): preflow_delta = min( self.excesses[from_index], self.graph[from_index][to_index] - self.preflow[from_index][to_index], ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def relabel(self, vertex_index): min_height = None for to_index in range(self.verticies_count): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): min_height = self.heights[to_index] if min_height is not None: self.heights[vertex_index] = min_height + 1 if __name__ == "__main__": entrances = [0] exits = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] graph = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network flow_network = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate maximum_flow = flow_network.find_maximum_flow() print(f"maximum flow is {maximum_flow}")
class FlowNetwork: def __init__(self, graph, sources, sinks): self.source_index = None self.sink_index = None self.graph = graph self._normalize_graph(sources, sinks) self.vertices_count = len(graph) self.maximum_flow_algorithm = None # make only one source and one sink def _normalize_graph(self, sources, sinks): if sources is int: sources = [sources] if sinks is int: sinks = [sinks] if len(sources) == 0 or len(sinks) == 0: return self.source_index = sources[0] self.sink_index = sinks[0] # make fake vertex if there are more # than one source or sink if len(sources) > 1 or len(sinks) > 1: max_input_flow = 0 for i in sources: max_input_flow += sum(self.graph[i]) size = len(self.graph) + 1 for room in self.graph: room.insert(0, 0) self.graph.insert(0, [0] * size) for i in sources: self.graph[0][i + 1] = max_input_flow self.source_index = 0 size = len(self.graph) + 1 for room in self.graph: room.append(0) self.graph.append([0] * size) for i in sinks: self.graph[i + 1][size - 1] = max_input_flow self.sink_index = size - 1 def find_maximum_flow(self): if self.maximum_flow_algorithm is None: raise Exception("You need to set maximum flow algorithm before.") if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def set_maximum_flow_algorithm(self, algorithm): self.maximum_flow_algorithm = algorithm(self) class FlowNetworkAlgorithmExecutor: def __init__(self, flow_network): self.flow_network = flow_network self.verticies_count = flow_network.verticesCount self.source_index = flow_network.sourceIndex self.sink_index = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that self.graph = flow_network.graph self.executed = False def execute(self): if not self.executed: self._algorithm() self.executed = True # You should override it def _algorithm(self): pass class MaximumFlowAlgorithmExecutor(FlowNetworkAlgorithmExecutor): def __init__(self, flow_network): super().__init__(flow_network) # use this to save your result self.maximum_flow = -1 def get_maximum_flow(self): if not self.executed: raise Exception("You should execute algorithm before using its result!") return self.maximum_flow class PushRelabelExecutor(MaximumFlowAlgorithmExecutor): def __init__(self, flow_network): super().__init__(flow_network) self.preflow = [[0] * self.verticies_count for i in range(self.verticies_count)] self.heights = [0] * self.verticies_count self.excesses = [0] * self.verticies_count def _algorithm(self): self.heights[self.source_index] = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index]): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule vertices_list = [ i for i in range(self.verticies_count) if i not in {self.source_index, self.sink_index} ] # move through list i = 0 while i < len(vertices_list): vertex_index = vertices_list[i] previous_height = self.heights[vertex_index] self.process_vertex(vertex_index) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0, vertices_list.pop(i)) i = 0 else: i += 1 self.maximum_flow = sum(self.preflow[self.source_index]) def process_vertex(self, vertex_index): while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(vertex_index, neighbour_index) self.relabel(vertex_index) def push(self, from_index, to_index): preflow_delta = min( self.excesses[from_index], self.graph[from_index][to_index] - self.preflow[from_index][to_index], ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def relabel(self, vertex_index): min_height = None for to_index in range(self.verticies_count): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): min_height = self.heights[to_index] if min_height is not None: self.heights[vertex_index] = min_height + 1 if __name__ == "__main__": entrances = [0] exits = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] graph = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network flow_network = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate maximum_flow = flow_network.find_maximum_flow() print(f"maximum flow is {maximum_flow}")
1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
"""Factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial """ def factorial(number: int) -> int: """ Calculate the factorial of specified number (n!). >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(20)) True >>> factorial(0.1) Traceback (most recent call last): ... ValueError: factorial() only accepts integral values >>> factorial(-1) Traceback (most recent call last): ... ValueError: factorial() not defined for negative values >>> factorial(1) 1 >>> factorial(6) 720 >>> factorial(0) 1 """ if number != int(number): raise ValueError("factorial() only accepts integral values") if number < 0: raise ValueError("factorial() not defined for negative values") value = 1 for i in range(1, number + 1): value *= i return value def factorial_recursive(n: int) -> int: """ Calculate the factorial of a positive integer https://en.wikipedia.org/wiki/Factorial >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(20)) True >>> factorial(0.1) Traceback (most recent call last): ... ValueError: factorial() only accepts integral values >>> factorial(-1) Traceback (most recent call last): ... ValueError: factorial() not defined for negative values """ if not isinstance(n, int): raise ValueError("factorial() only accepts integral values") if n < 0: raise ValueError("factorial() not defined for negative values") return 1 if n == 0 or n == 1 else n * factorial(n - 1) if __name__ == "__main__": import doctest doctest.testmod() n = int(input("Enter a positive integer: ").strip() or 0) print(f"factorial{n} is {factorial(n)}")
"""Factorial of a positive integer -- https://en.wikipedia.org/wiki/Factorial """ def factorial(number: int) -> int: """ Calculate the factorial of specified number (n!). >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(20)) True >>> factorial(0.1) Traceback (most recent call last): ... ValueError: factorial() only accepts integral values >>> factorial(-1) Traceback (most recent call last): ... ValueError: factorial() not defined for negative values >>> factorial(1) 1 >>> factorial(6) 720 >>> factorial(0) 1 """ if number != int(number): raise ValueError("factorial() only accepts integral values") if number < 0: raise ValueError("factorial() not defined for negative values") value = 1 for i in range(1, number + 1): value *= i return value def factorial_recursive(n: int) -> int: """ Calculate the factorial of a positive integer https://en.wikipedia.org/wiki/Factorial >>> import math >>> all(factorial(i) == math.factorial(i) for i in range(20)) True >>> factorial(0.1) Traceback (most recent call last): ... ValueError: factorial() only accepts integral values >>> factorial(-1) Traceback (most recent call last): ... ValueError: factorial() not defined for negative values """ if not isinstance(n, int): raise ValueError("factorial() only accepts integral values") if n < 0: raise ValueError("factorial() not defined for negative values") return 1 if n in {0, 1} else n * factorial(n - 1) if __name__ == "__main__": import doctest doctest.testmod() n = int(input("Enter a positive integer: ").strip() or 0) print(f"factorial{n} is {factorial(n)}")
1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Created 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: is_prime(number) sieve_er(N) get_prime_numbers(N) prime_factorization(number) greatest_prime_factor(number) smallest_prime_factor(number) get_prime(n) get_primes_between(pNumber1, pNumber2) ---- is_even(number) is_odd(number) gcd(number1, number2) // greatest common divisor kg_v(number1, number2) // least common multiple get_divisors(number) // all divisors of 'number' inclusive 1, number is_perfect_number(number) NEW-FUNCTIONS simplify_fraction(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 sieve_er(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 begin_list = list(range(2, n + 1)) ans = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(begin_list)): for j in range(i + 1, len(begin_list)): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): begin_list[j] = 0 # filters actual prime numbers. ans = [x for x in begin_list if x != 0] # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # -------------------------------- def get_prime_numbers(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 prime_factorization(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 greatest_prime_factor(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' prime_factors = prime_factorization(number) ans = max(prime_factors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans # ---------------------------------------------- def smallest_prime_factor(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' prime_factors = prime_factorization(number) ans = min(prime_factors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans # ---------------------- def is_even(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 is_odd(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 is_even(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' prime_numbers = get_prime_numbers(number) len_pn = len(prime_numbers) # run variable for while-loops. i = 0 j = None # exit variable. for break up the loops loop = True while i < len_pn and loop: j = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: loop = False ans.append(prime_numbers[i]) ans.append(prime_numbers[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 kg_v(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' prime_fac_1 = prime_factorization(number1) prime_fac_2 = prime_factorization(number2) elif number1 == 1 or number2 == 1: prime_fac_1 = [] prime_fac_2 = [] ans = max(number1, number2) count1 = 0 count2 = 0 done = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_1: if n not in done: if n in prime_fac_2: count1 = prime_fac_1.count(n) count2 = prime_fac_2.count(n) for _ in range(max(count1, count2)): ans *= n else: count1 = prime_fac_1.count(n) for _ in range(count1): ans *= n done.append(n) # iterates through primeFac2 for n in prime_fac_2: if n not in done: count2 = prime_fac_2.count(n) for _ 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 get_prime(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 get_primes_between(p_number_1, p_number_2): """ 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(p_number_1) and is_prime(p_number_2) and (p_number_1 < p_number_2) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" number = p_number_1 + 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 < p_number_2: 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] != p_number_1 and ans[len(ans) - 1] != p_number_2 ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans # ---------------------------------------------------- def get_divisors(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 is_perfect_number(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 = get_divisors(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 simplify_fraction(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. gcd_of_fraction = gcd(abs(numerator), abs(denominator)) # precondition assert ( isinstance(gcd_of_fraction, int) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) # ----------------------------------------------------------------- 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 _ 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: is_prime(number) sieve_er(N) get_prime_numbers(N) prime_factorization(number) greatest_prime_factor(number) smallest_prime_factor(number) get_prime(n) get_primes_between(pNumber1, pNumber2) ---- is_even(number) is_odd(number) gcd(number1, number2) // greatest common divisor kg_v(number1, number2) // least common multiple get_divisors(number) // all divisors of 'number' inclusive 1, number is_perfect_number(number) NEW-FUNCTIONS simplify_fraction(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 sieve_er(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 begin_list = list(range(2, n + 1)) ans = [] # this list will be returns. # actual sieve of erathostenes for i in range(len(begin_list)): for j in range(i + 1, len(begin_list)): if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0): begin_list[j] = 0 # filters actual prime numbers. ans = [x for x in begin_list if x != 0] # precondition assert isinstance(ans, list), "'ans' must been from type list" return ans # -------------------------------- def get_prime_numbers(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 prime_factorization(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 in {0, 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 greatest_prime_factor(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' prime_factors = prime_factorization(number) ans = max(prime_factors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans # ---------------------------------------------- def smallest_prime_factor(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' prime_factors = prime_factorization(number) ans = min(prime_factors) # precondition assert isinstance(ans, int), "'ans' must been from type int" return ans # ---------------------- def is_even(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 is_odd(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 is_even(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' prime_numbers = get_prime_numbers(number) len_pn = len(prime_numbers) # run variable for while-loops. i = 0 j = None # exit variable. for break up the loops loop = True while i < len_pn and loop: j = i + 1 while j < len_pn and loop: if prime_numbers[i] + prime_numbers[j] == number: loop = False ans.append(prime_numbers[i]) ans.append(prime_numbers[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 kg_v(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' prime_fac_1 = prime_factorization(number1) prime_fac_2 = prime_factorization(number2) elif number1 == 1 or number2 == 1: prime_fac_1 = [] prime_fac_2 = [] ans = max(number1, number2) count1 = 0 count2 = 0 done = [] # captured numbers int both 'primeFac1' and 'primeFac2' # iterates through primeFac1 for n in prime_fac_1: if n not in done: if n in prime_fac_2: count1 = prime_fac_1.count(n) count2 = prime_fac_2.count(n) for _ in range(max(count1, count2)): ans *= n else: count1 = prime_fac_1.count(n) for _ in range(count1): ans *= n done.append(n) # iterates through primeFac2 for n in prime_fac_2: if n not in done: count2 = prime_fac_2.count(n) for _ 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 get_prime(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 get_primes_between(p_number_1, p_number_2): """ 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(p_number_1) and is_prime(p_number_2) and (p_number_1 < p_number_2) ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'" number = p_number_1 + 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 < p_number_2: 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] != p_number_1 and ans[len(ans) - 1] != p_number_2 ), "'ans' must been a list without the arguments" # 'ans' contains not 'pNumber1' and 'pNumber2' ! return ans # ---------------------------------------------------- def get_divisors(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 is_perfect_number(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 = get_divisors(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 simplify_fraction(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. gcd_of_fraction = gcd(abs(numerator), abs(denominator)) # precondition assert ( isinstance(gcd_of_fraction, int) and (numerator % gcd_of_fraction == 0) and (denominator % gcd_of_fraction == 0) ), "Error in function gcd(...,...)" return (numerator // gcd_of_fraction, denominator // gcd_of_fraction) # ----------------------------------------------------------------- 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 _ in range(n - 1): tmp = ans ans += fib1 fib1 = tmp return ans
1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
#!/usr/bin/env python3 """ Davis–Putnam–Logemann–Loveland (DPLL) algorithm is a complete, backtracking-based search algorithm for deciding the satisfiability of propositional logic formulae in conjunctive normal form, i.e, for solving the Conjunctive Normal Form SATisfiability (CNF-SAT) problem. For more information about the algorithm: https://en.wikipedia.org/wiki/DPLL_algorithm """ from __future__ import annotations import random from collections.abc import Iterable class Clause: """ A clause represented in Conjunctive Normal Form. A clause is a set of literals, either complemented or otherwise. For example: {A1, A2, A3'} is the clause (A1 v A2 v A3') {A5', A2', A1} is the clause (A5' v A2' v A1) Create model >>> clause = Clause(["A1", "A2'", "A3"]) >>> clause.evaluate({"A1": True}) True """ def __init__(self, literals: list[str]) -> None: """ Represent the literals and an assignment in a clause." """ # Assign all literals to None initially self.literals: dict[str, bool | None] = {literal: None for literal in literals} def __str__(self) -> str: """ To print a clause as in Conjunctive Normal Form. >>> str(Clause(["A1", "A2'", "A3"])) "{A1 , A2' , A3}" """ return "{" + " , ".join(self.literals) + "}" def __len__(self) -> int: """ To print a clause as in Conjunctive Normal Form. >>> len(Clause([])) 0 >>> len(Clause(["A1", "A2'", "A3"])) 3 """ return len(self.literals) def assign(self, model: dict[str, bool | None]) -> None: """ Assign values to literals of the clause as given by model. """ for literal in self.literals: symbol = literal[:2] if symbol in model: value = model[symbol] else: continue if value is not None: # Complement assignment if literal is in complemented form if literal.endswith("'"): value = not value self.literals[literal] = value def evaluate(self, model: dict[str, bool | None]) -> bool | None: """ Evaluates the clause with the assignments in model. This has the following steps: 1. Return True if both a literal and its complement exist in the clause. 2. Return True if a single literal has the assignment True. 3. Return None(unable to complete evaluation) if a literal has no assignment. 4. Compute disjunction of all values assigned in clause. """ for literal in self.literals: symbol = literal.rstrip("'") if literal.endswith("'") else literal + "'" if symbol in self.literals: return True self.assign(model) for value in self.literals.values(): if value in (True, None): return value return any(self.literals.values()) class Formula: """ A formula represented in Conjunctive Normal Form. A formula is a set of clauses. For example, {{A1, A2, A3'}, {A5', A2', A1}} is ((A1 v A2 v A3') and (A5' v A2' v A1)) """ def __init__(self, clauses: Iterable[Clause]) -> None: """ Represent the number of clauses and the clauses themselves. """ self.clauses = list(clauses) def __str__(self) -> str: """ To print a formula as in Conjunctive Normal Form. str(Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])])) "{{A1 , A2' , A3} , {A5' , A2' , A1}}" """ return "{" + " , ".join(str(clause) for clause in self.clauses) + "}" def generate_clause() -> Clause: """ Randomly generate a clause. All literals have the name Ax, where x is an integer from 1 to 5. """ literals = [] no_of_literals = random.randint(1, 5) base_var = "A" i = 0 while i < no_of_literals: var_no = random.randint(1, 5) var_name = base_var + str(var_no) var_complement = random.randint(0, 1) if var_complement == 1: var_name += "'" if var_name in literals: i -= 1 else: literals.append(var_name) i += 1 return Clause(literals) def generate_formula() -> Formula: """ Randomly generate a formula. """ clauses: set[Clause] = set() no_of_clauses = random.randint(1, 10) while len(clauses) < no_of_clauses: clauses.add(generate_clause()) return Formula(clauses) def generate_parameters(formula: Formula) -> tuple[list[Clause], list[str]]: """ Return the clauses and symbols from a formula. A symbol is the uncomplemented form of a literal. For example, Symbol of A3 is A3. Symbol of A5' is A5. >>> formula = Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])]) >>> clauses, symbols = generate_parameters(formula) >>> clauses_list = [str(i) for i in clauses] >>> clauses_list ["{A1 , A2' , A3}", "{A5' , A2' , A1}"] >>> symbols ['A1', 'A2', 'A3', 'A5'] """ clauses = formula.clauses symbols_set = [] for clause in formula.clauses: for literal in clause.literals: symbol = literal[:2] if symbol not in symbols_set: symbols_set.append(symbol) return clauses, symbols_set def find_pure_symbols( clauses: list[Clause], symbols: list[str], model: dict[str, bool | None] ) -> tuple[list[str], dict[str, bool | None]]: """ Return pure symbols and their values to satisfy clause. Pure symbols are symbols in a formula that exist only in one form, either complemented or otherwise. For example, { { A4 , A3 , A5' , A1 , A3' } , { A4 } , { A3 } } has pure symbols A4, A5' and A1. This has the following steps: 1. Ignore clauses that have already evaluated to be True. 2. Find symbols that occur only in one form in the rest of the clauses. 3. Assign value True or False depending on whether the symbols occurs in normal or complemented form respectively. >>> formula = Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])]) >>> clauses, symbols = generate_parameters(formula) >>> pure_symbols, values = find_pure_symbols(clauses, symbols, {}) >>> pure_symbols ['A1', 'A2', 'A3', 'A5'] >>> values {'A1': True, 'A2': False, 'A3': True, 'A5': False} """ pure_symbols = [] assignment: dict[str, bool | None] = {} literals = [] for clause in clauses: if clause.evaluate(model): continue for literal in clause.literals: literals.append(literal) for s in symbols: sym = s + "'" if (s in literals and sym not in literals) or ( s not in literals and sym in literals ): pure_symbols.append(s) for p in pure_symbols: assignment[p] = None for s in pure_symbols: sym = s + "'" if s in literals: assignment[s] = True elif sym in literals: assignment[s] = False return pure_symbols, assignment def find_unit_clauses( clauses: list[Clause], model: dict[str, bool | None] ) -> tuple[list[str], dict[str, bool | None]]: """ Returns the unit symbols and their values to satisfy clause. Unit symbols are symbols in a formula that are: - Either the only symbol in a clause - Or all other literals in that clause have been assigned False This has the following steps: 1. Find symbols that are the only occurrences in a clause. 2. Find symbols in a clause where all other literals are assigned False. 3. Assign True or False depending on whether the symbols occurs in normal or complemented form respectively. >>> clause1 = Clause(["A4", "A3", "A5'", "A1", "A3'"]) >>> clause2 = Clause(["A4"]) >>> clause3 = Clause(["A3"]) >>> clauses, symbols = generate_parameters(Formula([clause1, clause2, clause3])) >>> unit_clauses, values = find_unit_clauses(clauses, {}) >>> unit_clauses ['A4', 'A3'] >>> values {'A4': True, 'A3': True} """ unit_symbols = [] for clause in clauses: if len(clause) == 1: unit_symbols.append(list(clause.literals.keys())[0]) else: f_count, n_count = 0, 0 for literal, value in clause.literals.items(): if value is False: f_count += 1 elif value is None: sym = literal n_count += 1 if f_count == len(clause) - 1 and n_count == 1: unit_symbols.append(sym) assignment: dict[str, bool | None] = {} for i in unit_symbols: symbol = i[:2] assignment[symbol] = len(i) == 2 unit_symbols = [i[:2] for i in unit_symbols] return unit_symbols, assignment def dpll_algorithm( clauses: list[Clause], symbols: list[str], model: dict[str, bool | None] ) -> tuple[bool | None, dict[str, bool | None] | None]: """ Returns the model if the formula is satisfiable, else None This has the following steps: 1. If every clause in clauses is True, return True. 2. If some clause in clauses is False, return False. 3. Find pure symbols. 4. Find unit symbols. >>> formula = Formula([Clause(["A4", "A3", "A5'", "A1", "A3'"]), Clause(["A4"])]) >>> clauses, symbols = generate_parameters(formula) >>> soln, model = dpll_algorithm(clauses, symbols, {}) >>> soln True >>> model {'A4': True} """ check_clause_all_true = True for clause in clauses: clause_check = clause.evaluate(model) if clause_check is False: return False, None elif clause_check is None: check_clause_all_true = False continue if check_clause_all_true: return True, model try: pure_symbols, assignment = find_pure_symbols(clauses, symbols, model) except RecursionError: print("raises a RecursionError and is") return None, {} p = None if len(pure_symbols) > 0: p, value = pure_symbols[0], assignment[pure_symbols[0]] if p: tmp_model = model tmp_model[p] = value tmp_symbols = list(symbols) if p in tmp_symbols: tmp_symbols.remove(p) return dpll_algorithm(clauses, tmp_symbols, tmp_model) unit_symbols, assignment = find_unit_clauses(clauses, model) p = None if len(unit_symbols) > 0: p, value = unit_symbols[0], assignment[unit_symbols[0]] if p: tmp_model = model tmp_model[p] = value tmp_symbols = list(symbols) if p in tmp_symbols: tmp_symbols.remove(p) return dpll_algorithm(clauses, tmp_symbols, tmp_model) p = symbols[0] rest = symbols[1:] tmp1, tmp2 = model, model tmp1[p], tmp2[p] = True, False return dpll_algorithm(clauses, rest, tmp1) or dpll_algorithm(clauses, rest, tmp2) if __name__ == "__main__": import doctest doctest.testmod() formula = generate_formula() print(f"The formula {formula} is", end=" ") clauses, symbols = generate_parameters(formula) solution, model = dpll_algorithm(clauses, symbols, {}) if solution: print(f"satisfiable with the assignment {model}.") else: print("not satisfiable.")
#!/usr/bin/env python3 """ Davis–Putnam–Logemann–Loveland (DPLL) algorithm is a complete, backtracking-based search algorithm for deciding the satisfiability of propositional logic formulae in conjunctive normal form, i.e, for solving the Conjunctive Normal Form SATisfiability (CNF-SAT) problem. For more information about the algorithm: https://en.wikipedia.org/wiki/DPLL_algorithm """ from __future__ import annotations import random from collections.abc import Iterable class Clause: """ A clause represented in Conjunctive Normal Form. A clause is a set of literals, either complemented or otherwise. For example: {A1, A2, A3'} is the clause (A1 v A2 v A3') {A5', A2', A1} is the clause (A5' v A2' v A1) Create model >>> clause = Clause(["A1", "A2'", "A3"]) >>> clause.evaluate({"A1": True}) True """ def __init__(self, literals: list[str]) -> None: """ Represent the literals and an assignment in a clause." """ # Assign all literals to None initially self.literals: dict[str, bool | None] = {literal: None for literal in literals} def __str__(self) -> str: """ To print a clause as in Conjunctive Normal Form. >>> str(Clause(["A1", "A2'", "A3"])) "{A1 , A2' , A3}" """ return "{" + " , ".join(self.literals) + "}" def __len__(self) -> int: """ To print a clause as in Conjunctive Normal Form. >>> len(Clause([])) 0 >>> len(Clause(["A1", "A2'", "A3"])) 3 """ return len(self.literals) def assign(self, model: dict[str, bool | None]) -> None: """ Assign values to literals of the clause as given by model. """ for literal in self.literals: symbol = literal[:2] if symbol in model: value = model[symbol] else: continue if value is not None: # Complement assignment if literal is in complemented form if literal.endswith("'"): value = not value self.literals[literal] = value def evaluate(self, model: dict[str, bool | None]) -> bool | None: """ Evaluates the clause with the assignments in model. This has the following steps: 1. Return True if both a literal and its complement exist in the clause. 2. Return True if a single literal has the assignment True. 3. Return None(unable to complete evaluation) if a literal has no assignment. 4. Compute disjunction of all values assigned in clause. """ for literal in self.literals: symbol = literal.rstrip("'") if literal.endswith("'") else literal + "'" if symbol in self.literals: return True self.assign(model) for value in self.literals.values(): if value in (True, None): return value return any(self.literals.values()) class Formula: """ A formula represented in Conjunctive Normal Form. A formula is a set of clauses. For example, {{A1, A2, A3'}, {A5', A2', A1}} is ((A1 v A2 v A3') and (A5' v A2' v A1)) """ def __init__(self, clauses: Iterable[Clause]) -> None: """ Represent the number of clauses and the clauses themselves. """ self.clauses = list(clauses) def __str__(self) -> str: """ To print a formula as in Conjunctive Normal Form. str(Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])])) "{{A1 , A2' , A3} , {A5' , A2' , A1}}" """ return "{" + " , ".join(str(clause) for clause in self.clauses) + "}" def generate_clause() -> Clause: """ Randomly generate a clause. All literals have the name Ax, where x is an integer from 1 to 5. """ literals = [] no_of_literals = random.randint(1, 5) base_var = "A" i = 0 while i < no_of_literals: var_no = random.randint(1, 5) var_name = base_var + str(var_no) var_complement = random.randint(0, 1) if var_complement == 1: var_name += "'" if var_name in literals: i -= 1 else: literals.append(var_name) i += 1 return Clause(literals) def generate_formula() -> Formula: """ Randomly generate a formula. """ clauses: set[Clause] = set() no_of_clauses = random.randint(1, 10) while len(clauses) < no_of_clauses: clauses.add(generate_clause()) return Formula(clauses) def generate_parameters(formula: Formula) -> tuple[list[Clause], list[str]]: """ Return the clauses and symbols from a formula. A symbol is the uncomplemented form of a literal. For example, Symbol of A3 is A3. Symbol of A5' is A5. >>> formula = Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])]) >>> clauses, symbols = generate_parameters(formula) >>> clauses_list = [str(i) for i in clauses] >>> clauses_list ["{A1 , A2' , A3}", "{A5' , A2' , A1}"] >>> symbols ['A1', 'A2', 'A3', 'A5'] """ clauses = formula.clauses symbols_set = [] for clause in formula.clauses: for literal in clause.literals: symbol = literal[:2] if symbol not in symbols_set: symbols_set.append(symbol) return clauses, symbols_set def find_pure_symbols( clauses: list[Clause], symbols: list[str], model: dict[str, bool | None] ) -> tuple[list[str], dict[str, bool | None]]: """ Return pure symbols and their values to satisfy clause. Pure symbols are symbols in a formula that exist only in one form, either complemented or otherwise. For example, { { A4 , A3 , A5' , A1 , A3' } , { A4 } , { A3 } } has pure symbols A4, A5' and A1. This has the following steps: 1. Ignore clauses that have already evaluated to be True. 2. Find symbols that occur only in one form in the rest of the clauses. 3. Assign value True or False depending on whether the symbols occurs in normal or complemented form respectively. >>> formula = Formula([Clause(["A1", "A2'", "A3"]), Clause(["A5'", "A2'", "A1"])]) >>> clauses, symbols = generate_parameters(formula) >>> pure_symbols, values = find_pure_symbols(clauses, symbols, {}) >>> pure_symbols ['A1', 'A2', 'A3', 'A5'] >>> values {'A1': True, 'A2': False, 'A3': True, 'A5': False} """ pure_symbols = [] assignment: dict[str, bool | None] = {} literals = [] for clause in clauses: if clause.evaluate(model): continue for literal in clause.literals: literals.append(literal) for s in symbols: sym = s + "'" if (s in literals and sym not in literals) or ( s not in literals and sym in literals ): pure_symbols.append(s) for p in pure_symbols: assignment[p] = None for s in pure_symbols: sym = s + "'" if s in literals: assignment[s] = True elif sym in literals: assignment[s] = False return pure_symbols, assignment def find_unit_clauses( clauses: list[Clause], model: dict[str, bool | None] ) -> tuple[list[str], dict[str, bool | None]]: """ Returns the unit symbols and their values to satisfy clause. Unit symbols are symbols in a formula that are: - Either the only symbol in a clause - Or all other literals in that clause have been assigned False This has the following steps: 1. Find symbols that are the only occurrences in a clause. 2. Find symbols in a clause where all other literals are assigned False. 3. Assign True or False depending on whether the symbols occurs in normal or complemented form respectively. >>> clause1 = Clause(["A4", "A3", "A5'", "A1", "A3'"]) >>> clause2 = Clause(["A4"]) >>> clause3 = Clause(["A3"]) >>> clauses, symbols = generate_parameters(Formula([clause1, clause2, clause3])) >>> unit_clauses, values = find_unit_clauses(clauses, {}) >>> unit_clauses ['A4', 'A3'] >>> values {'A4': True, 'A3': True} """ unit_symbols = [] for clause in clauses: if len(clause) == 1: unit_symbols.append(next(iter(clause.literals.keys()))) else: f_count, n_count = 0, 0 for literal, value in clause.literals.items(): if value is False: f_count += 1 elif value is None: sym = literal n_count += 1 if f_count == len(clause) - 1 and n_count == 1: unit_symbols.append(sym) assignment: dict[str, bool | None] = {} for i in unit_symbols: symbol = i[:2] assignment[symbol] = len(i) == 2 unit_symbols = [i[:2] for i in unit_symbols] return unit_symbols, assignment def dpll_algorithm( clauses: list[Clause], symbols: list[str], model: dict[str, bool | None] ) -> tuple[bool | None, dict[str, bool | None] | None]: """ Returns the model if the formula is satisfiable, else None This has the following steps: 1. If every clause in clauses is True, return True. 2. If some clause in clauses is False, return False. 3. Find pure symbols. 4. Find unit symbols. >>> formula = Formula([Clause(["A4", "A3", "A5'", "A1", "A3'"]), Clause(["A4"])]) >>> clauses, symbols = generate_parameters(formula) >>> soln, model = dpll_algorithm(clauses, symbols, {}) >>> soln True >>> model {'A4': True} """ check_clause_all_true = True for clause in clauses: clause_check = clause.evaluate(model) if clause_check is False: return False, None elif clause_check is None: check_clause_all_true = False continue if check_clause_all_true: return True, model try: pure_symbols, assignment = find_pure_symbols(clauses, symbols, model) except RecursionError: print("raises a RecursionError and is") return None, {} p = None if len(pure_symbols) > 0: p, value = pure_symbols[0], assignment[pure_symbols[0]] if p: tmp_model = model tmp_model[p] = value tmp_symbols = list(symbols) if p in tmp_symbols: tmp_symbols.remove(p) return dpll_algorithm(clauses, tmp_symbols, tmp_model) unit_symbols, assignment = find_unit_clauses(clauses, model) p = None if len(unit_symbols) > 0: p, value = unit_symbols[0], assignment[unit_symbols[0]] if p: tmp_model = model tmp_model[p] = value tmp_symbols = list(symbols) if p in tmp_symbols: tmp_symbols.remove(p) return dpll_algorithm(clauses, tmp_symbols, tmp_model) p = symbols[0] rest = symbols[1:] tmp1, tmp2 = model, model tmp1[p], tmp2[p] = True, False return dpll_algorithm(clauses, rest, tmp1) or dpll_algorithm(clauses, rest, tmp2) if __name__ == "__main__": import doctest doctest.testmod() formula = generate_formula() print(f"The formula {formula} is", end=" ") clauses, symbols = generate_parameters(formula) solution, model = dpll_algorithm(clauses, symbols, {}) if solution: print(f"satisfiable with the assignment {model}.") else: print("not satisfiable.")
1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
""" Project Euler Problem 9: https://projecteuler.net/problem=9 Special Pythagorean triplet A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product a*b*c. References: - https://en.wikipedia.org/wiki/Pythagorean_triple """ def solution() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a**2 + b**2 = c**2 2. a + b + c = 1000 >>> solution() 31875000 """ return [ a * b * (1000 - a - b) for a in range(1, 999) for b in range(a, 999) if (a * a + b * b == (1000 - a - b) ** 2) ][0] if __name__ == "__main__": print(f"{solution() = }")
""" Project Euler Problem 9: https://projecteuler.net/problem=9 Special Pythagorean triplet A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product a*b*c. References: - https://en.wikipedia.org/wiki/Pythagorean_triple """ def solution() -> int: """ Returns the product of a,b,c which are Pythagorean Triplet that satisfies the following: 1. a**2 + b**2 = c**2 2. a + b + c = 1000 >>> solution() 31875000 """ return next( iter( [ a * b * (1000 - a - b) for a in range(1, 999) for b in range(a, 999) if (a * a + b * b == (1000 - a - b) ** 2) ] ) ) if __name__ == "__main__": print(f"{solution() = }")
1
TheAlgorithms/Python
8,879
[Upgrade Ruff] Fix all errors raised from ruff
### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
CaedenPH
"2023-07-22T08:47:09Z"
"2023-07-22T10:05:11Z"
5aefc00f0f1c692ce772ddbc616d7cd91233236b
93fb169627ea9fe43436a312fdfa751818808180
[Upgrade Ruff] Fix all errors raised from ruff. ### Describe your change: Fixes all errors shown in the failing tests here https://github.com/TheAlgorithms/Python/actions/runs/5629561962/job/15254651560?pr=8875 Fixes #8876 Fixes #8877 Fixes #8878 Fixes #8880 * [ ] Add an algorithm? * [x] Fix a bug or typo in an existing algorithm? * [ ] Documentation change? ### Checklist: * [ ] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md). * [ ] This pull request is all my own work -- I have not plagiarized. * [ ] I know that pull requests will not be merged if they fail the automated tests. * [ ] This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms. * [ ] All new Python files are placed inside an existing directory. * [ ] All filenames are in all lowercase characters with no spaces or dashes. * [ ] All functions and variable names follow Python naming conventions. * [ ] All function parameters and return values are annotated with Python [type hints](https://docs.python.org/3/library/typing.html). * [ ] All functions have [doctests](https://docs.python.org/3/library/doctest.html) that pass the automated testing. * [ ] All new algorithms include at least one URL that points to Wikipedia or another similar explanation. * [ ] If this pull request resolves one or more open issues then the description above includes the issue number(s) with a [closing keyword](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue): "Fixes #ISSUE-NUMBER".
# https://github.com/rupansh/QuantumComputing/blob/master/rippleadd.py # https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder # https://en.wikipedia.org/wiki/Controlled_NOT_gate import qiskit from qiskit.providers import Backend def store_two_classics(val1: int, val2: int) -> tuple[qiskit.QuantumCircuit, str, str]: """ Generates a Quantum Circuit which stores two classical integers Returns the circuit and binary representation of the integers """ x, y = bin(val1)[2:], bin(val2)[2:] # Remove leading '0b' # Ensure that both strings are of the same length if len(x) > len(y): y = y.zfill(len(x)) else: x = x.zfill(len(y)) # We need (3 * number of bits in the larger number)+1 qBits # The second parameter is the number of classical registers, to measure the result circuit = qiskit.QuantumCircuit((len(x) * 3) + 1, len(x) + 1) # We are essentially "not-ing" the bits that are 1 # Reversed because it's easier to perform ops on more significant bits for i in range(len(x)): if x[::-1][i] == "1": circuit.x(i) for j in range(len(y)): if y[::-1][j] == "1": circuit.x(len(x) + j) return circuit, x, y def full_adder( circuit: qiskit.QuantumCircuit, input1_loc: int, input2_loc: int, carry_in: int, carry_out: int, ): """ Quantum Equivalent of a Full Adder Circuit CX/CCX is like 2-way/3-way XOR """ circuit.ccx(input1_loc, input2_loc, carry_out) circuit.cx(input1_loc, input2_loc) circuit.ccx(input2_loc, carry_in, carry_out) circuit.cx(input2_loc, carry_in) circuit.cx(input1_loc, input2_loc) # The default value for **backend** is the result of a function call which is not # normally recommended and causes ruff to raise a B008 error. However, in this case, # this is acceptable because `Aer.get_backend()` is called when the function is defined # and that same backend is then reused for all function calls. def ripple_adder( val1: int, val2: int, backend: Backend = qiskit.Aer.get_backend("aer_simulator"), # noqa: B008 ) -> int: """ Quantum Equivalent of a Ripple Adder Circuit Uses qasm_simulator backend by default Currently only adds 'emulated' Classical Bits but nothing prevents us from doing this with hadamard'd bits :) Only supports adding positive integers >>> ripple_adder(3, 4) 7 >>> ripple_adder(10, 4) 14 >>> ripple_adder(-1, 10) Traceback (most recent call last): ... ValueError: Both Integers must be positive! """ if val1 < 0 or val2 < 0: raise ValueError("Both Integers must be positive!") # Store the Integers circuit, x, y = store_two_classics(val1, val2) """ We are essentially using each bit of x & y respectively as full_adder's input the carry_input is used from the previous circuit (for circuit num > 1) the carry_out is just below carry_input because it will be essentially the carry_input for the next full_adder """ for i in range(len(x)): full_adder(circuit, i, len(x) + i, len(x) + len(y) + i, len(x) + len(y) + i + 1) circuit.barrier() # Optional, just for aesthetics # Measure the resultant qBits for i in range(len(x) + 1): circuit.measure([(len(x) * 2) + i], [i]) res = qiskit.execute(circuit, backend, shots=1).result() # The result is in binary. Convert it back to int return int(list(res.get_counts())[0], 2) if __name__ == "__main__": import doctest doctest.testmod()
# https://github.com/rupansh/QuantumComputing/blob/master/rippleadd.py # https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder # https://en.wikipedia.org/wiki/Controlled_NOT_gate import qiskit from qiskit.providers import Backend def store_two_classics(val1: int, val2: int) -> tuple[qiskit.QuantumCircuit, str, str]: """ Generates a Quantum Circuit which stores two classical integers Returns the circuit and binary representation of the integers """ x, y = bin(val1)[2:], bin(val2)[2:] # Remove leading '0b' # Ensure that both strings are of the same length if len(x) > len(y): y = y.zfill(len(x)) else: x = x.zfill(len(y)) # We need (3 * number of bits in the larger number)+1 qBits # The second parameter is the number of classical registers, to measure the result circuit = qiskit.QuantumCircuit((len(x) * 3) + 1, len(x) + 1) # We are essentially "not-ing" the bits that are 1 # Reversed because it's easier to perform ops on more significant bits for i in range(len(x)): if x[::-1][i] == "1": circuit.x(i) for j in range(len(y)): if y[::-1][j] == "1": circuit.x(len(x) + j) return circuit, x, y def full_adder( circuit: qiskit.QuantumCircuit, input1_loc: int, input2_loc: int, carry_in: int, carry_out: int, ): """ Quantum Equivalent of a Full Adder Circuit CX/CCX is like 2-way/3-way XOR """ circuit.ccx(input1_loc, input2_loc, carry_out) circuit.cx(input1_loc, input2_loc) circuit.ccx(input2_loc, carry_in, carry_out) circuit.cx(input2_loc, carry_in) circuit.cx(input1_loc, input2_loc) # The default value for **backend** is the result of a function call which is not # normally recommended and causes ruff to raise a B008 error. However, in this case, # this is acceptable because `Aer.get_backend()` is called when the function is defined # and that same backend is then reused for all function calls. def ripple_adder( val1: int, val2: int, backend: Backend = qiskit.Aer.get_backend("aer_simulator"), # noqa: B008 ) -> int: """ Quantum Equivalent of a Ripple Adder Circuit Uses qasm_simulator backend by default Currently only adds 'emulated' Classical Bits but nothing prevents us from doing this with hadamard'd bits :) Only supports adding positive integers >>> ripple_adder(3, 4) 7 >>> ripple_adder(10, 4) 14 >>> ripple_adder(-1, 10) Traceback (most recent call last): ... ValueError: Both Integers must be positive! """ if val1 < 0 or val2 < 0: raise ValueError("Both Integers must be positive!") # Store the Integers circuit, x, y = store_two_classics(val1, val2) """ We are essentially using each bit of x & y respectively as full_adder's input the carry_input is used from the previous circuit (for circuit num > 1) the carry_out is just below carry_input because it will be essentially the carry_input for the next full_adder """ for i in range(len(x)): full_adder(circuit, i, len(x) + i, len(x) + len(y) + i, len(x) + len(y) + i + 1) circuit.barrier() # Optional, just for aesthetics # Measure the resultant qBits for i in range(len(x) + 1): circuit.measure([(len(x) * 2) + i], [i]) res = qiskit.execute(circuit, backend, shots=1).result() # The result is in binary. Convert it back to int return int(next(iter(res.get_counts())), 2) if __name__ == "__main__": import doctest doctest.testmod()
1